@staix/vault-mem-ui 0.0.0-stage → 0.0.0

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 (64) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +96 -2
  4. package/THIRD_PARTY_NOTICES.md +164 -0
  5. package/bin/vmem-ui.ts +26 -0
  6. package/dist/panel.css +666 -0
  7. package/dist/panel.js +355 -0
  8. package/package.json +53 -4
  9. package/src/client/App.tsx +167 -0
  10. package/src/client/a11y.ts +54 -0
  11. package/src/client/acon.ts +46 -0
  12. package/src/client/components.tsx +243 -0
  13. package/src/client/data.ts +66 -0
  14. package/src/client/fake.ts +48 -0
  15. package/src/client/graph-export.tsx +21 -0
  16. package/src/client/host.ts +80 -0
  17. package/src/client/markdown/parse.ts +620 -0
  18. package/src/client/markdown/render.tsx +270 -0
  19. package/src/client/panel.css +666 -0
  20. package/src/client/panel.tsx +66 -0
  21. package/src/client/prefs.ts +76 -0
  22. package/src/client/standalone.ts +44 -0
  23. package/src/client/store.ts +201 -0
  24. package/src/client/views/assertions.tsx +109 -0
  25. package/src/client/views/common.ts +15 -0
  26. package/src/client/views/history.tsx +205 -0
  27. package/src/client/views/lint.tsx +27 -0
  28. package/src/client/views/log.tsx +64 -0
  29. package/src/client/views/note.tsx +128 -0
  30. package/src/client/views/notes.tsx +34 -0
  31. package/src/client/views/overview.tsx +74 -0
  32. package/src/client/views/promote.tsx +112 -0
  33. package/src/client/views/proposals.tsx +55 -0
  34. package/src/client/views/settings.tsx +57 -0
  35. package/src/client/write.ts +144 -0
  36. package/src/graph/decisionChains.ts +122 -0
  37. package/src/graph/derive.ts +338 -0
  38. package/src/graph/export.ts +44 -0
  39. package/src/graph/insights.ts +254 -0
  40. package/src/graph/labels.ts +67 -0
  41. package/src/graph/layout/client.ts +139 -0
  42. package/src/graph/layout/engine.ts +107 -0
  43. package/src/graph/layout/fa2.d.ts +8 -0
  44. package/src/graph/layout/protocol.ts +70 -0
  45. package/src/graph/layout/worker.ts +132 -0
  46. package/src/graph/model.ts +230 -0
  47. package/src/graph/positions.ts +41 -0
  48. package/src/graph/search.ts +54 -0
  49. package/src/graph/style.ts +301 -0
  50. package/src/graph/target.ts +38 -0
  51. package/src/graph/types.ts +64 -0
  52. package/src/graph/view/GraphView.tsx +279 -0
  53. package/src/graph/view/SidePanels.tsx +141 -0
  54. package/src/graph/view/cache.ts +42 -0
  55. package/src/graph/view/canvas.ts +309 -0
  56. package/src/graph/view/graph-snapshot.ts +75 -0
  57. package/src/graph/view/lod.ts +30 -0
  58. package/src/graph/view/motion.ts +4 -0
  59. package/src/graph/view/state.ts +240 -0
  60. package/src/plugin/assets.ts +33 -0
  61. package/src/plugin/graph.ts +71 -0
  62. package/src/plugin/index.ts +23 -0
  63. package/src/server/cli.ts +99 -0
  64. package/src/server/host.ts +287 -0
@@ -0,0 +1,254 @@
1
+ // Ported from STAIxBWLB/maru@b33341df src/lib/graph/insights.ts.
2
+ // Graph insight engine — the "ideation" layer over the read-only graph.
3
+ //
4
+ // All analyses run in a worker over the in-memory GraphModel, so nothing here
5
+ // depends on the weekly `vmem graph build` report; these are the same ideas
6
+ // (god nodes, surprising cross-community links, community bridges) recomputed
7
+ // live, plus link prediction (hidden links) and path finding for exploration.
8
+
9
+ import { buildAdjacency, type GraphModel, type GraphNode } from "./model";
10
+
11
+ /** Types excluded from insight endpoints: ghosts aren't real notes, and MOCs
12
+ * are deliberate hubs that connect everything — a shared MOC neighbor or an
13
+ * MOC endpoint is never a "surprising" signal. */
14
+ const HUB_TYPES = new Set(["moc", "unresolved"]);
15
+
16
+ // ponytail: findHiddenLinks is O(Σ deg²). Capping the bridging degree bounds
17
+ // it and improves quality — a mega-hub linking everything doesn't make two of
18
+ // its neighbors meaningfully related. Raise the cap if recall matters more.
19
+ const COMMON_NEIGHBOR_DEGREE_CAP = 30;
20
+ const DAY_MS = 86_400_000;
21
+
22
+ function isHub(node: GraphNode | undefined): boolean {
23
+ return !node || HUB_TYPES.has(node.type);
24
+ }
25
+
26
+ function pairKey(a: string, b: string): string {
27
+ return a < b ? `${a}\u0000${b}` : `${b}\u0000${a}`;
28
+ }
29
+
30
+ export interface HiddenLink {
31
+ source: string;
32
+ target: string;
33
+ /** Number of shared neighbors (common-neighbor link-prediction score). */
34
+ shared: number;
35
+ /** Adamic-Adar style weighted score; specific shared neighbors count more. */
36
+ score: number;
37
+ /** Ids of a few shared neighbors, for "connected via …" explanation. */
38
+ via: string[];
39
+ }
40
+
41
+ /** Non-adjacent note pairs that share ≥2 neighbors — candidate links the
42
+ * author hasn't drawn yet. This is the core "derive new relationships"
43
+ * feature. */
44
+ export function findHiddenLinks(model: GraphModel, limit = 12): HiddenLink[] {
45
+ const adjacency = buildAdjacency(model);
46
+ const nodeById = new Map(model.nodes.map((n) => [n.id, n]));
47
+ const nodeIndex = new Map(model.nodes.map((node, index) => [node.id, index]));
48
+ const nodeCount = model.nodes.length;
49
+ // A numeric pair key avoids allocating and later splitting a temporary
50
+ // string for every candidate pair. nodeCount² remains safely below
51
+ // Number.MAX_SAFE_INTEGER for the graph sizes the view supports.
52
+ const pairs = new Map<number, { count: number; score: number; via: string[] }>();
53
+
54
+ for (const node of model.nodes) {
55
+ if (isHub(node)) continue;
56
+ const neighbors = [...(adjacency.get(node.id) ?? [])].filter(
57
+ (id) => !isHub(nodeById.get(id)),
58
+ );
59
+ if (neighbors.length < 2 || neighbors.length > COMMON_NEIGHBOR_DEGREE_CAP) {
60
+ continue;
61
+ }
62
+ const weight = 1 / Math.log2(2 + Math.max(1, node.degree));
63
+ for (let i = 0; i < neighbors.length; i += 1) {
64
+ for (let j = i + 1; j < neighbors.length; j += 1) {
65
+ const a = neighbors[i];
66
+ const b = neighbors[j];
67
+ if (adjacency.get(a)?.has(b)) continue; // already directly linked
68
+ const aIndex = nodeIndex.get(a)!;
69
+ const bIndex = nodeIndex.get(b)!;
70
+ const key =
71
+ aIndex < bIndex
72
+ ? aIndex * nodeCount + bIndex
73
+ : bIndex * nodeCount + aIndex;
74
+ const entry = pairs.get(key);
75
+ if (entry) {
76
+ entry.count += 1;
77
+ entry.score += weight;
78
+ if (entry.via.length < 5) entry.via.push(node.id);
79
+ } else {
80
+ pairs.set(key, { count: 1, score: weight, via: [node.id] });
81
+ }
82
+ }
83
+ }
84
+ }
85
+
86
+ const out: HiddenLink[] = [];
87
+ for (const [key, { count, score, via }] of pairs) {
88
+ if (count < 2) continue;
89
+ const source = model.nodes[Math.floor(key / nodeCount)].id;
90
+ const target = model.nodes[key % nodeCount].id;
91
+ out.push({ source, target, shared: count, score, via });
92
+ }
93
+ out.sort((a, b) => b.score - a.score || b.shared - a.shared || a.source.localeCompare(b.source));
94
+ return out.slice(0, limit);
95
+ }
96
+
97
+ export interface SurprisingConnection {
98
+ source: string;
99
+ target: string;
100
+ score: number;
101
+ sourceCommunity: number | null;
102
+ targetCommunity: number | null;
103
+ }
104
+
105
+ /** Existing edges that cross community boundaries, ranked by combined degree
106
+ * (the producer's "Surprising Connections (Cross-Community)" report section).
107
+ * Requires the community overlay; returns [] on the degraded live graph. */
108
+ export function findSurprisingConnections(
109
+ model: GraphModel,
110
+ limit = 12,
111
+ ): SurprisingConnection[] {
112
+ if (!model.enriched) return [];
113
+ const nodeById = new Map(model.nodes.map((n) => [n.id, n]));
114
+ const seen = new Set<string>();
115
+ const out: SurprisingConnection[] = [];
116
+ for (const edge of model.edges) {
117
+ const s = nodeById.get(edge.source);
118
+ const t = nodeById.get(edge.target);
119
+ if (isHub(s) || isHub(t)) continue;
120
+ if (s!.community == null || t!.community == null) continue;
121
+ if (s!.community === t!.community) continue;
122
+ const key = pairKey(edge.source, edge.target);
123
+ if (seen.has(key)) continue;
124
+ seen.add(key);
125
+ out.push({
126
+ source: edge.source,
127
+ target: edge.target,
128
+ score: s!.degree + t!.degree,
129
+ sourceCommunity: s!.community,
130
+ targetCommunity: t!.community,
131
+ });
132
+ }
133
+ out.sort((a, b) => b.score - a.score);
134
+ return out.slice(0, limit);
135
+ }
136
+
137
+ export interface BridgeNode {
138
+ id: string;
139
+ communityCount: number;
140
+ neighborCount: number;
141
+ communities: number[];
142
+ }
143
+
144
+ /** Notes whose neighbors span the most distinct communities — the connectors
145
+ * that hold otherwise-separate clusters together (a cheap betweenness proxy).
146
+ * Requires the community overlay. */
147
+ export function findBridges(model: GraphModel, limit = 12): BridgeNode[] {
148
+ if (!model.enriched) return [];
149
+ const adjacency = buildAdjacency(model);
150
+ const nodeById = new Map(model.nodes.map((n) => [n.id, n]));
151
+ const out: BridgeNode[] = [];
152
+ for (const node of model.nodes) {
153
+ if (isHub(node)) continue;
154
+ const neighbors = adjacency.get(node.id);
155
+ if (!neighbors) continue;
156
+ const communities = new Set<number>();
157
+ for (const id of neighbors) {
158
+ const n = nodeById.get(id);
159
+ if (n && n.community != null) communities.add(n.community);
160
+ }
161
+ if (communities.size >= 2) {
162
+ out.push({
163
+ id: node.id,
164
+ communityCount: communities.size,
165
+ neighborCount: neighbors.size,
166
+ communities: [...communities].sort((a, b) => a - b),
167
+ });
168
+ }
169
+ }
170
+ out.sort(
171
+ (a, b) => b.communityCount - a.communityCount || b.neighborCount - a.neighborCount,
172
+ );
173
+ return out.slice(0, limit);
174
+ }
175
+
176
+ export interface OrphanNode {
177
+ id: string;
178
+ degree: number;
179
+ }
180
+
181
+ /** Notes with ≤1 connection (excluding ghosts and MOC hubs) — candidates to
182
+ * link into the graph or archive. */
183
+ export function findOrphans(model: GraphModel, limit = 20): OrphanNode[] {
184
+ const out: OrphanNode[] = [];
185
+ for (const node of model.nodes) {
186
+ if (node.type === "unresolved" || node.type === "moc") continue;
187
+ if (node.degree <= 1) out.push({ id: node.id, degree: node.degree });
188
+ }
189
+ out.sort((a, b) => a.degree - b.degree || a.id.localeCompare(b.id));
190
+ return out.slice(0, limit);
191
+ }
192
+
193
+ export interface StaleNode {
194
+ id: string;
195
+ degree: number;
196
+ updatedAt: string | null;
197
+ }
198
+
199
+ /** Well-connected notes not touched in `olderThanDays` — worth revisiting.
200
+ * `now` is passed for deterministic tests. */
201
+ export function findStale(
202
+ model: GraphModel,
203
+ olderThanDays: number,
204
+ now: number,
205
+ limit = 20,
206
+ ): StaleNode[] {
207
+ const cutoff = now - olderThanDays * DAY_MS;
208
+ const out: StaleNode[] = [];
209
+ for (const node of model.nodes) {
210
+ if (node.type === "unresolved") continue;
211
+ if (node.degree < 2) continue;
212
+ const ts = node.updatedAt ? Date.parse(node.updatedAt) : NaN;
213
+ if (Number.isNaN(ts) || ts >= cutoff) continue;
214
+ out.push({ id: node.id, degree: node.degree, updatedAt: node.updatedAt });
215
+ }
216
+ out.sort((a, b) => (a.updatedAt ?? "").localeCompare(b.updatedAt ?? ""));
217
+ return out.slice(0, limit);
218
+ }
219
+
220
+ /** Shortest path between two nodes (BFS over the undirected graph) — "how are
221
+ * these two ideas connected?". Returns the id chain (inclusive) or null. */
222
+ export function shortestPath(
223
+ model: GraphModel,
224
+ sourceId: string,
225
+ targetId: string,
226
+ ): string[] | null {
227
+ if (sourceId === targetId) return [sourceId];
228
+ const adjacency = buildAdjacency(model);
229
+ if (!adjacency.has(sourceId) || !adjacency.has(targetId)) return null;
230
+ const prev = new Map<string, string>();
231
+ const visited = new Set<string>([sourceId]);
232
+ // ponytail: array-shift BFS is O(n²) worst case; fine at vault scale, swap
233
+ // for a ring buffer if this ever runs on 10k+ nodes.
234
+ const queue: string[] = [sourceId];
235
+ while (queue.length > 0) {
236
+ const current = queue.shift()!;
237
+ for (const next of adjacency.get(current) ?? []) {
238
+ if (visited.has(next)) continue;
239
+ visited.add(next);
240
+ prev.set(next, current);
241
+ if (next === targetId) {
242
+ const path = [targetId];
243
+ let step = targetId;
244
+ while (step !== sourceId) {
245
+ step = prev.get(step)!;
246
+ path.push(step);
247
+ }
248
+ return path.reverse();
249
+ }
250
+ queue.push(next);
251
+ }
252
+ }
253
+ return null;
254
+ }
@@ -0,0 +1,67 @@
1
+ // Ported from STAIxBWLB/maru@b33341df src/components/graph/graphLabels.ts.
2
+ // Sigma is not a dependency yet (the canvas lands with M2's Sigma work), so the Sigma shapes these renderers read
3
+ // are declared structurally here; Sigma's NodeDisplayData and Settings satisfy them.
4
+ import { graphTheme } from "./style";
5
+
6
+ export interface NodeLabelData {
7
+ x: number;
8
+ y: number;
9
+ size: number;
10
+ label: string | null;
11
+ color: string;
12
+ forceLabel?: boolean;
13
+ highlighted?: boolean;
14
+ }
15
+ export interface LabelSettings {
16
+ labelFont: string;
17
+ labelSize: number;
18
+ labelWeight: string;
19
+ }
20
+ // Obsidian-style zoom-linked fade: labels are invisible while a node renders
21
+ // small, ramp in as it grows on screen (zoom-in or high degree).
22
+ const FADE_START = 6;
23
+ const FADE_END = 12;
24
+
25
+ export function labelAlpha(renderedSize: number, forced: boolean): number {
26
+ if (forced) return 1;
27
+ if (renderedSize <= FADE_START) return 0;
28
+ if (renderedSize >= FADE_END) return 0.3;
29
+ return ((renderedSize - FADE_START) / (FADE_END - FADE_START)) * 0.3;
30
+ }
31
+
32
+ function drawLabelText(
33
+ context: CanvasRenderingContext2D,
34
+ data: NodeLabelData,
35
+ settings: LabelSettings,
36
+ alpha: number,
37
+ sizePx: number,
38
+ weight: string,
39
+ ): void {
40
+ if (!data.label || alpha <= 0) return;
41
+ const theme = graphTheme();
42
+ context.save();
43
+ context.globalAlpha = alpha;
44
+ context.font = `${weight} ${sizePx}px ${settings.labelFont}`;
45
+ context.textAlign = "center";
46
+ context.textBaseline = "top";
47
+ // bg-colored stroke halo keeps labels readable over edges (cheaper than shadowBlur)
48
+ context.lineJoin = "round";
49
+ context.lineWidth = 3;
50
+ context.strokeStyle = theme.bg;
51
+ const x = data.x;
52
+ const y = data.y + data.size + 3;
53
+ context.strokeText(data.label, x, y);
54
+ context.fillStyle = theme.labelColor;
55
+ context.fillText(data.label, x, y);
56
+ context.restore();
57
+ }
58
+
59
+ export function drawNodeLabel(context: CanvasRenderingContext2D, data: NodeLabelData, settings: LabelSettings): void {
60
+ const forced = data.forceLabel === true || data.highlighted === true;
61
+ drawLabelText(context, data, settings, labelAlpha(data.size, forced), settings.labelSize, settings.labelWeight);
62
+ }
63
+
64
+ export function drawNodeHover(context: CanvasRenderingContext2D, data: NodeLabelData, settings: LabelSettings): void {
65
+ // Hovered node: always-on, slightly larger label; no white box (Obsidian look).
66
+ drawLabelText(context, data, settings, 1, settings.labelSize + 1, "600");
67
+ }
@@ -0,0 +1,139 @@
1
+ // Main-thread side of the layout protocol. Starts the panel's own module as a module worker and, when that is not
2
+ // possible (no Worker, a CSP SecurityError, a script load refused by a static multi-node host), reports a
3
+ // "cached-only" state instead: the view then shows cached positions and runs no layout loop. It never falls back to a
4
+ // blob: worker or to layout on the main thread.
5
+
6
+ import {
7
+ LAYOUT_WORKER_NAME,
8
+ batchIntervalMs,
9
+ inferLayoutSettings,
10
+ type ForceAtlas2Settings,
11
+ type FromWorker,
12
+ type LayoutGraph,
13
+ type ToWorker,
14
+ } from "./protocol";
15
+
16
+ export const WORKER_START_TIMEOUT_MS = 5_000;
17
+
18
+ export interface LayoutCallbacks {
19
+ onPositions(positions: Float32Array, iterations: number): void;
20
+ onState?(state: "running" | "paused" | "stopped" | "done"): void;
21
+ onError?(message: string): void;
22
+ }
23
+
24
+ export interface LayoutHandle {
25
+ readonly state: "running";
26
+ pause(): void;
27
+ resume(): void;
28
+ /** Pins or releases nodes in the live layout (see ToWorker "fix"). */
29
+ fix(nodes: { index: number; fixed: boolean; position?: [number, number] }[]): void;
30
+ /** Stops iterating; the worker sends the final positions and stays alive until teardown. */
31
+ stop(): void;
32
+ /** Ends the worker. Safe to call more than once. */
33
+ teardown(): void;
34
+ }
35
+
36
+ export interface CachedOnly {
37
+ readonly state: "cached-only";
38
+ /** Cause and next step, ready to show. */
39
+ readonly reason: string;
40
+ }
41
+
42
+ export interface StartLayoutOptions extends LayoutCallbacks {
43
+ /** The panel module's own URL: `new URL(import.meta.url)`. */
44
+ moduleUrl: URL | string;
45
+ graph: LayoutGraph;
46
+ settings?: ForceAtlas2Settings;
47
+ batchMs?: number;
48
+ /** Overrides MAX_LAYOUT_ITERATIONS (the safety cap). */
49
+ maxIterations?: number;
50
+ /** Override CONVERGED_MOVEMENT / CONVERGED_STREAK (the default end condition). */
51
+ convergedMovement?: number;
52
+ convergedStreak?: number;
53
+ /** False on hosts that cannot start a worker (the static multi-node host). */
54
+ workerAllowed?: boolean;
55
+ /** Worker constructor; defaults to the global Worker. */
56
+ createWorker?: (url: URL | string, options: WorkerOptions) => Worker;
57
+ startTimeoutMs?: number;
58
+ }
59
+
60
+ const cachedOnly = (cause: string): CachedOnly => ({
61
+ state: "cached-only",
62
+ reason: `live layout is unavailable: ${cause}; showing cached positions only. Open the graph from the standalone vmem-ui or a single acon host to lay it out.`,
63
+ });
64
+
65
+ export function startLayout(options: StartLayoutOptions): Promise<LayoutHandle | CachedOnly> {
66
+ if (options.workerAllowed === false) return Promise.resolve(cachedOnly("this host does not allow layout workers"));
67
+ const create = options.createWorker ?? (typeof Worker === "undefined" ? undefined : (url: URL | string, o: WorkerOptions) => new Worker(url, o));
68
+ if (!create) return Promise.resolve(cachedOnly("this browser has no Worker support"));
69
+
70
+ let worker: Worker;
71
+ try {
72
+ worker = create(options.moduleUrl, { type: "module", name: LAYOUT_WORKER_NAME });
73
+ } catch (error) {
74
+ const name = error instanceof Error ? error.name : "";
75
+ return Promise.resolve(cachedOnly(name === "SecurityError" ? "the page's security policy refused the layout worker" : `the layout worker could not start (${error instanceof Error ? error.message : String(error)})`));
76
+ }
77
+
78
+ return new Promise((resolve) => {
79
+ let ready = false;
80
+ let ended = false;
81
+ const send = (message: ToWorker, transfer: Transferable[] = []) => { if (!ended) worker.postMessage(message, transfer); };
82
+ const end = () => { if (ended) return; ended = true; worker.terminate(); };
83
+ const timer = setTimeout(() => {
84
+ if (ready) return;
85
+ end();
86
+ resolve(cachedOnly(`the layout worker did not start within ${(options.startTimeoutMs ?? WORKER_START_TIMEOUT_MS) / 1000} s`));
87
+ }, options.startTimeoutMs ?? WORKER_START_TIMEOUT_MS);
88
+
89
+ const handle: LayoutHandle = {
90
+ state: "running",
91
+ pause: () => send({ type: "pause" }),
92
+ resume: () => send({ type: "resume" }),
93
+ fix: (nodes) => send({ type: "fix", nodes }),
94
+ stop: () => send({ type: "stop" }),
95
+ teardown: () => { if (ended) return; send({ type: "teardown" }); end(); },
96
+ };
97
+
98
+ worker.addEventListener("message", (event: MessageEvent<FromWorker>) => {
99
+ const message = event.data;
100
+ switch (message.type) {
101
+ case "ready":
102
+ ready = true;
103
+ clearTimeout(timer);
104
+ resolve(handle);
105
+ break;
106
+ case "positions":
107
+ options.onPositions(message.positions, message.iterations);
108
+ break;
109
+ case "state":
110
+ options.onState?.(message.state);
111
+ break;
112
+ case "error":
113
+ if (!ready) { clearTimeout(timer); end(); resolve(cachedOnly(message.message)); } else options.onError?.(message.message);
114
+ break;
115
+ }
116
+ });
117
+ // A script refused by CSP or a failed module load arrives as an error event, not a throw.
118
+ worker.addEventListener("error", (event: Event) => {
119
+ event.preventDefault?.();
120
+ const detail = (event as ErrorEvent).message || "the module could not be loaded";
121
+ if (!ready) { clearTimeout(timer); end(); resolve(cachedOnly(`the layout worker failed to load (${detail})`)); return; }
122
+ end();
123
+ options.onError?.(`graph layout stopped: ${detail}; reload the graph to restart the layout, or keep the cached positions`);
124
+ });
125
+
126
+ const graph = options.graph;
127
+ const init: ToWorker = {
128
+ type: "init",
129
+ graph,
130
+ settings: options.settings ?? inferLayoutSettings(graph.nodeCount),
131
+ batchMs: options.batchMs ?? batchIntervalMs(graph.sources.length),
132
+ ...(options.maxIterations !== undefined ? { maxIterations: options.maxIterations } : {}),
133
+ ...(options.convergedMovement !== undefined ? { convergedMovement: options.convergedMovement } : {}),
134
+ ...(options.convergedStreak !== undefined ? { convergedStreak: options.convergedStreak } : {}),
135
+ };
136
+ // Copy, not transfer: the caller keeps its arrays (they may be the cached layout on screen).
137
+ send(init);
138
+ });
139
+ }
@@ -0,0 +1,107 @@
1
+ // ForceAtlas2 engine over persistent matrices, built straight from index arrays (no graphology instance in the
2
+ // worker). Matrix layout and settings merge follow graphology-layout-forceatlas2 0.10.1 helpers.graphToByteArrays and
3
+ // index.js; one step is that library's own `iterate`, so the arithmetic matches its public `assign`.
4
+ // The stock FA2 worker supervisor is not used: it starts its worker from a blob: URL, which the panel CSP blocks.
5
+
6
+ import DEFAULTS from "graphology-layout-forceatlas2/defaults";
7
+ import iterate from "graphology-layout-forceatlas2/iterate";
8
+ import type { ForceAtlas2Settings, LayoutGraph } from "./protocol";
9
+
10
+ const PPN = 10; // floats per node in FA2's NodeMatrix
11
+ const PPE = 3; // floats per edge in FA2's EdgeMatrix
12
+
13
+ export interface LayoutEngine {
14
+ readonly nodeCount: number;
15
+ readonly iterations: number;
16
+ /** Runs `n` ForceAtlas2 iterations. */
17
+ step(n?: number): void;
18
+ /** Spike 2's movement proxy for the last iteration: sqrt(sum |dp|^2 / sum |p|^2); 0 before the first step. */
19
+ readonly movement: number;
20
+ /** Current coordinates as a fresh x0,y0,x1,y1,... array (safe to transfer). */
21
+ positions(): Float32Array;
22
+ /** Sets or clears node `index`'s fixed flag, optionally moving it first. Out-of-range or non-finite input is ignored. */
23
+ setFixed(index: number, fixed: boolean, position?: [number, number]): void;
24
+ }
25
+
26
+ /** Validates the graph and returns the cause of the first problem, or null. */
27
+ export function layoutGraphProblem(graph: LayoutGraph): string | null {
28
+ const n = graph.nodeCount;
29
+ if (!Number.isInteger(n) || n < 0) return `nodeCount must be a whole number, got ${n}`;
30
+ if (graph.positions.length !== n * 2) return `positions has ${graph.positions.length} values, expected ${n * 2} (x,y per node)`;
31
+ if (graph.sources.length !== graph.targets.length) return `sources (${graph.sources.length}) and targets (${graph.targets.length}) differ in length`;
32
+ for (let i = 0; i < graph.sources.length; i += 1) {
33
+ if (graph.sources[i]! >= n || graph.targets[i]! >= n) return `edge ${i} points at node ${Math.max(graph.sources[i]!, graph.targets[i]!)}, but there are only ${n} nodes`;
34
+ }
35
+ if (graph.sizes && graph.sizes.length !== n) return `sizes has ${graph.sizes.length} values, expected ${n}`;
36
+ if (graph.fixed && graph.fixed.length !== n) return `fixed has ${graph.fixed.length} values, expected ${n}`;
37
+ return null;
38
+ }
39
+
40
+ export function createLayoutEngine(graph: LayoutGraph, settings: ForceAtlas2Settings): LayoutEngine {
41
+ const problem = layoutGraphProblem(graph);
42
+ if (problem) throw new Error(problem);
43
+ const n = graph.nodeCount;
44
+ const m = graph.sources.length;
45
+ const nodes = new Float32Array(n * PPN);
46
+ const edges = new Float32Array(m * PPE);
47
+ for (let i = 0; i < n; i += 1) {
48
+ const j = i * PPN;
49
+ nodes[j] = graph.positions[i * 2]!;
50
+ nodes[j + 1] = graph.positions[i * 2 + 1]!;
51
+ nodes[j + 6] = 1; // mass, incremented by weighted degree below
52
+ nodes[j + 7] = 1; // convergence
53
+ nodes[j + 8] = graph.sizes?.[i] || 1;
54
+ nodes[j + 9] = graph.fixed?.[i] ? 1 : 0;
55
+ }
56
+ for (let e = 0; e < m; e += 1) {
57
+ const sj = graph.sources[e]! * PPN;
58
+ const tj = graph.targets[e]! * PPN;
59
+ nodes[sj + 6] += 1;
60
+ nodes[tj + 6] += 1;
61
+ edges[e * PPE] = sj;
62
+ edges[e * PPE + 1] = tj;
63
+ edges[e * PPE + 2] = 1;
64
+ }
65
+ const merged = { ...DEFAULTS, ...settings };
66
+ let iterations = 0;
67
+ let movement = 0;
68
+ const prev = new Float32Array(n * 2);
69
+ return {
70
+ nodeCount: n,
71
+ get iterations() { return iterations; },
72
+ get movement() { return movement; },
73
+ step(count = 1) {
74
+ if (n === 0) return;
75
+ for (let k = 0; k < count; k += 1) {
76
+ for (let i = 0; i < n; i += 1) { prev[i * 2] = nodes[i * PPN]!; prev[i * 2 + 1] = nodes[i * PPN + 1]!; }
77
+ iterate(merged, nodes, edges);
78
+ let moved = 0, extent = 0;
79
+ for (let i = 0; i < n; i += 1) {
80
+ const x = nodes[i * PPN]!, y = nodes[i * PPN + 1]!;
81
+ const dx = x - prev[i * 2]!, dy = y - prev[i * 2 + 1]!;
82
+ moved += dx * dx + dy * dy;
83
+ extent += x * x + y * y;
84
+ }
85
+ movement = extent > 0 ? Math.sqrt(moved / extent) : (moved > 0 ? Infinity : 0);
86
+ }
87
+ iterations += count;
88
+ },
89
+ positions() {
90
+ const out = new Float32Array(n * 2);
91
+ for (let i = 0; i < n; i += 1) {
92
+ out[i * 2] = nodes[i * PPN]!;
93
+ out[i * 2 + 1] = nodes[i * PPN + 1]!;
94
+ }
95
+ return out;
96
+ },
97
+ setFixed(index, fixed, position) {
98
+ if (!Number.isInteger(index) || index < 0 || index >= n) return;
99
+ const j = index * PPN;
100
+ if (position && Number.isFinite(position[0]) && Number.isFinite(position[1])) {
101
+ nodes[j] = position[0];
102
+ nodes[j + 1] = position[1];
103
+ }
104
+ nodes[j + 9] = fixed ? 1 : 0;
105
+ },
106
+ };
107
+ }
@@ -0,0 +1,8 @@
1
+ // Typings for the two CommonJS subpaths of graphology-layout-forceatlas2 0.10.1 that ship without .d.ts files.
2
+ declare module "graphology-layout-forceatlas2/iterate" {
3
+ export default function iterate(settings: Record<string, unknown>, nodeMatrix: Float32Array, edgeMatrix: Float32Array): void;
4
+ }
5
+ declare module "graphology-layout-forceatlas2/defaults" {
6
+ const defaults: Record<string, unknown>;
7
+ export default defaults;
8
+ }
@@ -0,0 +1,70 @@
1
+ // Layout worker protocol and tuning constants (issue #1, "Layout"; evidence docs/spikes/02-layout-worker.md).
2
+ // The worker is the panel's own module started as a module worker; it never uses a blob: URL and the layout never
3
+ // runs on the main thread.
4
+
5
+ import type { ForceAtlas2Settings } from "graphology-layout-forceatlas2";
6
+
7
+ export type { ForceAtlas2Settings };
8
+
9
+ /** Above this many edges, batches are applied less often (spike 2b: a batch costs ~6 ms of main-thread work at
10
+ * 30,000 edges and ~20 ms at 100,000). The view tunes these. */
11
+ export const LARGE_GRAPH_EDGES = 30_000;
12
+ /** Batch interval for graphs up to LARGE_GRAPH_EDGES: about one frame. */
13
+ export const SMALL_BATCH_MS = 16;
14
+ /** Batch interval above LARGE_GRAPH_EDGES, the spike 2b starting point. */
15
+ export const LARGE_BATCH_MS = 100;
16
+
17
+ export function batchIntervalMs(edgeCount: number): number {
18
+ return edgeCount > LARGE_GRAPH_EDGES ? LARGE_BATCH_MS : SMALL_BATCH_MS;
19
+ }
20
+
21
+ /** Default end condition. The layout stops as `done` when the movement proxy from spike 2,
22
+ * sqrt(sum of squared node displacements / sum of squared coordinates), stays below CONVERGED_MOVEMENT for
23
+ * CONVERGED_STREAK consecutive iterations. This is a heuristic, not a visual-quality guarantee. */
24
+ export const CONVERGED_MOVEMENT = 0.01;
25
+ export const CONVERGED_STREAK = 5;
26
+ /** Safety cap: the layout ends as `done` after this many iterations even if it has not settled. */
27
+ export const MAX_LAYOUT_ITERATIONS = 2_000;
28
+
29
+ /** ForceAtlas2's own inferSettings formula (graphology-layout-forceatlas2 0.10.1 index.js, MIT), taking only the
30
+ * node count so the main thread does not need a graphology instance. */
31
+ export function inferLayoutSettings(nodeCount: number): ForceAtlas2Settings {
32
+ return {
33
+ barnesHutOptimize: nodeCount > 2000,
34
+ strongGravityMode: true,
35
+ gravity: 0.05,
36
+ scalingRatio: 10,
37
+ slowDown: 1 + Math.log(Math.max(1, nodeCount)),
38
+ };
39
+ }
40
+
41
+ /** Graph shape sent to the worker: node i is index i; edges are parallel index arrays. */
42
+ export interface LayoutGraph {
43
+ nodeCount: number;
44
+ /** Initial coordinates, x0,y0,x1,y1,... (length 2 * nodeCount). Cached positions go here. */
45
+ positions: Float32Array;
46
+ sources: Uint32Array;
47
+ targets: Uint32Array;
48
+ /** Optional per-node size (adjustSizes) and pinned flag. */
49
+ sizes?: Float32Array;
50
+ fixed?: Uint8Array;
51
+ }
52
+
53
+ export type ToWorker =
54
+ | { type: "init"; graph: LayoutGraph; settings: ForceAtlas2Settings; batchMs: number; maxIterations?: number; convergedMovement?: number; convergedStreak?: number }
55
+ | { type: "pause" }
56
+ /** Pins (fixed) or releases nodes in the running layout; a pinned node keeps `position` when given. Restarts a settled layout. */
57
+ | { type: "fix"; nodes: { index: number; fixed: boolean; position?: [number, number] }[] }
58
+ | { type: "resume" }
59
+ | { type: "stop" }
60
+ | { type: "teardown" };
61
+
62
+ export type FromWorker =
63
+ | { type: "ready" }
64
+ /** x0,y0,x1,y1,...; the buffer is transferred. */
65
+ | { type: "positions"; positions: Float32Array; iterations: number }
66
+ | { type: "state"; state: "running" | "paused" | "stopped" | "done" }
67
+ | { type: "error"; message: string };
68
+
69
+ /** Marker the panel module checks to know it was started as the layout worker. */
70
+ export const LAYOUT_WORKER_NAME = "vmem-ui-layout";