@myrialabs/clopen 0.4.29 → 0.4.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/chat/stream-manager.ts +1 -1
- package/backend/database/migrations/067_add_memory_graph_layout.ts +91 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/graph-queries.ts +417 -32
- package/backend/db-client/drivers/mssql.ts +57 -22
- package/backend/db-client/drivers/mysql.ts +69 -48
- package/backend/db-client/drivers/postgres.ts +65 -53
- package/backend/engine/adapters/claude/stream.ts +81 -15
- package/backend/engine/adapters/codex/stream.ts +6 -3
- package/backend/engine/adapters/opencode/server.ts +13 -4
- package/backend/engine/bootstrap-default-engine.ts +67 -38
- package/backend/engine/docs/artifacts.md +1 -1
- package/backend/engine/docs/quick-reference.md +1 -1
- package/backend/engine/engine-cli.ts +313 -0
- package/backend/engine/engine-setup.ts +40 -3
- package/backend/engine/install-recipes.test.ts +99 -5
- package/backend/engine/install-recipes.ts +47 -11
- package/backend/engine/install-runner.ts +34 -16
- package/backend/engine/stack-project.ts +72 -0
- package/backend/index.ts +5 -0
- package/backend/memory/bootstrap.ts +9 -0
- package/backend/memory/layout.ts +985 -0
- package/backend/memory/notify.ts +33 -7
- package/backend/memory/view.ts +375 -69
- package/backend/permissions/index.ts +4 -2
- package/backend/permissions/resolve.ts +7 -5
- package/backend/utils/path-enrich.ts +2 -0
- package/backend/utils/process-warnings.ts +41 -0
- package/backend/ws/engine/claude/accounts.ts +9 -4
- package/backend/ws/engine/codex/accounts.ts +8 -5
- package/backend/ws/engine/codex/status.ts +10 -17
- package/backend/ws/memory/crud.ts +50 -2
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/stack/access.ts +5 -2
- package/dist/assets/{index-C7e5TWG3.js → index-DUc5T21e.js} +1 -1
- package/dist/assets/{index-Derlqeyy.js → index-DYwQ5bP8.js} +1 -1
- package/dist/assets/main-VgdjTBLR.css +1 -0
- package/dist/assets/{main-OGhsRKU1.js → main-r0iv2PDz.js} +393 -386
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/memory.ts +70 -0
- package/dist/assets/main-CqzaPnux.css +0 -1
|
@@ -815,7 +815,7 @@ class StreamManager extends EventEmitter {
|
|
|
815
815
|
// exact fix (Stack to install/update, Engines to sign in). Thrown here
|
|
816
816
|
// so the processStream catch surfaces it as a chat error, which the
|
|
817
817
|
// ErrorMessage renderer turns into a one-click action.
|
|
818
|
-
const setupIssue = checkEngineSetup(requestEngine.type, requestEngine.account.id);
|
|
818
|
+
const setupIssue = await checkEngineSetup(requestEngine.type, requestEngine.account.id);
|
|
819
819
|
if (setupIssue) throw new Error(setupIssue.message);
|
|
820
820
|
|
|
821
821
|
// Stream EngineOutput events through the engine adapter
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
2
|
+
import { debug } from '$shared/utils/logger';
|
|
3
|
+
|
|
4
|
+
export const description =
|
|
5
|
+
'Persist memory-graph communities and layout positions, and index the graph view ordering';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Make the Memory view stop paying for the whole graph on every look.
|
|
9
|
+
*
|
|
10
|
+
* Two things used to be recomputed from scratch on every single fetch, and both
|
|
11
|
+
* of them grow with the store rather than with what is being displayed:
|
|
12
|
+
*
|
|
13
|
+
* - COMMUNITY DETECTION. Louvain ran inside `buildGraphView`, so opening the
|
|
14
|
+
* modal, changing a filter, or any conversation writing a memory made every
|
|
15
|
+
* connected client re-cluster the graph server-side. The result is stable
|
|
16
|
+
* per dataset, so it belonged in a table all along.
|
|
17
|
+
*
|
|
18
|
+
* - LAYOUT. ForceAtlas2 ran in the browser on every open, from a deterministic
|
|
19
|
+
* seed — several hundred iterations to arrive at the same arrangement it
|
|
20
|
+
* arrived at last time, discarded the moment the modal closed. That is what
|
|
21
|
+
* made opening the modal janky once the graph got big: the animation and a
|
|
22
|
+
* few hundred milliseconds of layout were competing for one thread.
|
|
23
|
+
*
|
|
24
|
+
* `graph_layout` holds both, keyed by node. It is deliberately a SEPARATE table
|
|
25
|
+
* rather than columns on `graph_nodes`: a position is a property of an
|
|
26
|
+
* arrangement, not of a memory, so a re-layout must never look like an edit to
|
|
27
|
+
* the memory itself — `updated_at` on `graph_nodes` drives recall ranking, and
|
|
28
|
+
* bumping it every time a node drifted two pixels would have quietly reordered
|
|
29
|
+
* what agents get told.
|
|
30
|
+
*
|
|
31
|
+
* The row is derived data. Losing it costs a background pass, never a memory,
|
|
32
|
+
* which is why it cascades away with its node and is safe to delete wholesale.
|
|
33
|
+
*/
|
|
34
|
+
export const up = (db: DatabaseConnection): void => {
|
|
35
|
+
debug.log('migration', 'Creating the memory graph layout table...');
|
|
36
|
+
|
|
37
|
+
// `placed` separates the two halves of what a pass produces, and they do NOT
|
|
38
|
+
// have the same reach. Community detection runs over every live node — it is
|
|
39
|
+
// linear in the edges and it is what the overview groups by, so leaving nodes
|
|
40
|
+
// out of it would leave them out of the picture entirely. The force simulation
|
|
41
|
+
// is superlinear and therefore capped, so the lowest-ranked nodes get their
|
|
42
|
+
// community's neighbourhood as a position rather than a computed one.
|
|
43
|
+
//
|
|
44
|
+
// Without the flag those two are indistinguishable, and a guessed position
|
|
45
|
+
// would be handed to the client as though it were a real one — every member of
|
|
46
|
+
// a large lobe stacked on a single point, with nothing to say they should be
|
|
47
|
+
// spread out.
|
|
48
|
+
db.exec(`
|
|
49
|
+
CREATE TABLE IF NOT EXISTS graph_layout (
|
|
50
|
+
node_id TEXT PRIMARY KEY REFERENCES graph_nodes(id) ON DELETE CASCADE,
|
|
51
|
+
community INTEGER NOT NULL DEFAULT 0,
|
|
52
|
+
x REAL NOT NULL DEFAULT 0,
|
|
53
|
+
y REAL NOT NULL DEFAULT 0,
|
|
54
|
+
placed INTEGER NOT NULL DEFAULT 1,
|
|
55
|
+
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
56
|
+
)
|
|
57
|
+
`);
|
|
58
|
+
|
|
59
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_layout_community ON graph_layout (community)`);
|
|
60
|
+
|
|
61
|
+
// Zooming into part of the map asks for the nodes inside a rectangle, which
|
|
62
|
+
// without this is a scan of the whole arrangement for a handful of rows.
|
|
63
|
+
db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_layout_position ON graph_layout (x, y)`);
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The graph view's own ordering, which had no index at all.
|
|
67
|
+
*
|
|
68
|
+
* `graphQueries.list` selects `ORDER BY pinned DESC, weight DESC, updated_at
|
|
69
|
+
* DESC LIMIT n`, and with nothing to read that order from SQLite had to scan
|
|
70
|
+
* every live row and sort ALL of them before taking the first few thousand.
|
|
71
|
+
* That is the one part of a fetch that grew without bound: the cap limited
|
|
72
|
+
* what was returned, never what was examined.
|
|
73
|
+
*
|
|
74
|
+
* Partial on the same predicate the view always applies, so it stays the size
|
|
75
|
+
* of the live graph however much history accumulates behind it.
|
|
76
|
+
*/
|
|
77
|
+
db.exec(`
|
|
78
|
+
CREATE INDEX IF NOT EXISTS idx_graph_nodes_view
|
|
79
|
+
ON graph_nodes (pinned DESC, weight DESC, updated_at DESC)
|
|
80
|
+
WHERE archived_at IS NULL AND superseded_by IS NULL
|
|
81
|
+
`);
|
|
82
|
+
|
|
83
|
+
debug.log('migration', 'Memory graph layout table ready');
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export const down = (db: DatabaseConnection): void => {
|
|
87
|
+
db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_view`);
|
|
88
|
+
db.exec(`DROP INDEX IF EXISTS idx_graph_layout_position`);
|
|
89
|
+
db.exec(`DROP INDEX IF EXISTS idx_graph_layout_community`);
|
|
90
|
+
db.exec(`DROP TABLE IF EXISTS graph_layout`);
|
|
91
|
+
};
|
|
@@ -65,6 +65,7 @@ import * as migration063 from './063_add_invite_project_ids';
|
|
|
65
65
|
import * as migration064 from './064_create_messages_fts';
|
|
66
66
|
import * as migration065 from './065_add_session_reasoning_effort';
|
|
67
67
|
import * as migration066 from './066_create_memory_graph';
|
|
68
|
+
import * as migration067 from './067_add_memory_graph_layout';
|
|
68
69
|
|
|
69
70
|
// Export all migrations in order
|
|
70
71
|
export const migrations = [
|
|
@@ -463,6 +464,12 @@ export const migrations = [
|
|
|
463
464
|
description: migration066.description,
|
|
464
465
|
up: migration066.up,
|
|
465
466
|
down: migration066.down
|
|
467
|
+
},
|
|
468
|
+
{
|
|
469
|
+
id: '067',
|
|
470
|
+
description: migration067.description,
|
|
471
|
+
up: migration067.up,
|
|
472
|
+
down: migration067.down
|
|
466
473
|
}
|
|
467
474
|
];
|
|
468
475
|
|
|
@@ -269,57 +269,89 @@ export interface GraphListFilter {
|
|
|
269
269
|
* Kept in one place because the three drifting apart is how a node ends up
|
|
270
270
|
* counted but not shown, or shown in the graph after being forgotten.
|
|
271
271
|
*/
|
|
272
|
-
|
|
272
|
+
/**
|
|
273
|
+
* An id set as ONE bound parameter instead of one placeholder per id.
|
|
274
|
+
*
|
|
275
|
+
* The graph view hands these queries up to three thousand ids at a time, and
|
|
276
|
+
* `IN (?, ?, … ×3000)` builds a different SQL string for every distinct length —
|
|
277
|
+
* so the statement cache never hits and SQLite recompiles the query on each
|
|
278
|
+
* call. `edgesWithin` was the worst of them, repeating the set twice for six
|
|
279
|
+
* thousand bound parameters. `json_each` takes the whole set as a single JSON
|
|
280
|
+
* argument, which makes the SQL text constant and the statement cacheable.
|
|
281
|
+
*/
|
|
282
|
+
const ID_SET = '(SELECT value FROM json_each(?))';
|
|
283
|
+
|
|
284
|
+
const idSet = (ids: string[]): string => JSON.stringify(ids);
|
|
285
|
+
|
|
286
|
+
function appendProjectFilter(
|
|
287
|
+
filter: GraphListFilter,
|
|
288
|
+
where: string[],
|
|
289
|
+
params: unknown[],
|
|
290
|
+
as: string = ''
|
|
291
|
+
): void {
|
|
273
292
|
if (filter.projectIds !== undefined) {
|
|
274
293
|
// Nothing selected is "global only", not "everything": the user has narrowed
|
|
275
294
|
// away every repository, and what remains is what was never a repository's.
|
|
276
|
-
if (filter.projectIds.length === 0) where.push(
|
|
295
|
+
if (filter.projectIds.length === 0) where.push(`${as}project_id IS NULL`);
|
|
277
296
|
else {
|
|
278
|
-
where.push(
|
|
297
|
+
where.push(
|
|
298
|
+
`(${as}project_id IN (${filter.projectIds.map(() => '?').join(',')}) OR ${as}project_id IS NULL)`
|
|
299
|
+
);
|
|
279
300
|
params.push(...filter.projectIds);
|
|
280
301
|
}
|
|
281
302
|
return;
|
|
282
303
|
}
|
|
283
304
|
if (filter.projectId === undefined) return;
|
|
284
305
|
if (filter.projectId === null) {
|
|
285
|
-
where.push(
|
|
306
|
+
where.push(`${as}project_id IS NULL`);
|
|
286
307
|
return;
|
|
287
308
|
}
|
|
288
309
|
// A project view also shows the global memories that apply to it —
|
|
289
310
|
// conventions and preferences are part of that project's context.
|
|
290
|
-
where.push(`(project_id = ? OR project_id IS NULL)`);
|
|
311
|
+
where.push(`(${as}project_id = ? OR ${as}project_id IS NULL)`);
|
|
291
312
|
params.push(filter.projectId);
|
|
292
313
|
}
|
|
293
314
|
|
|
294
|
-
|
|
315
|
+
/**
|
|
316
|
+
* The graph view's WHERE clause, optionally qualified by a table alias.
|
|
317
|
+
*
|
|
318
|
+
* The alias exists for the queries that join `graph_nodes` to itself through an
|
|
319
|
+
* edge — the cluster-adjacency rollup has to apply the SAME narrowing to both
|
|
320
|
+
* ends of every edge, and unqualified column names are ambiguous there. Callers
|
|
321
|
+
* pass `'n.'`; everything else keeps the bare form it always had.
|
|
322
|
+
*/
|
|
323
|
+
function buildNodeFilter(
|
|
324
|
+
filter: GraphListFilter,
|
|
325
|
+
as: string = ''
|
|
326
|
+
): { where: string[]; params: unknown[] } {
|
|
295
327
|
const where: string[] = [];
|
|
296
328
|
const params: unknown[] = [];
|
|
297
329
|
|
|
298
|
-
appendProjectFilter(filter, where, params);
|
|
330
|
+
appendProjectFilter(filter, where, params, as);
|
|
299
331
|
if (filter.kinds?.length) {
|
|
300
|
-
where.push(
|
|
332
|
+
where.push(`${as}kind IN (${filter.kinds.map(() => '?').join(',')})`);
|
|
301
333
|
params.push(...filter.kinds);
|
|
302
334
|
}
|
|
303
335
|
if (filter.subkinds?.length) {
|
|
304
|
-
where.push(
|
|
336
|
+
where.push(`${as}subkind IN (${filter.subkinds.map(() => '?').join(',')})`);
|
|
305
337
|
params.push(...filter.subkinds);
|
|
306
338
|
}
|
|
307
339
|
if (filter.scopes?.length) {
|
|
308
|
-
where.push(
|
|
340
|
+
where.push(`${as}scope IN (${filter.scopes.map(() => '?').join(',')})`);
|
|
309
341
|
params.push(...filter.scopes);
|
|
310
342
|
}
|
|
311
343
|
if (filter.sources?.length) {
|
|
312
|
-
where.push(
|
|
344
|
+
where.push(`${as}source IN (${filter.sources.map(() => '?').join(',')})`);
|
|
313
345
|
params.push(...filter.sources);
|
|
314
346
|
}
|
|
315
347
|
|
|
316
|
-
if (filter.archivedOnly) where.push(
|
|
317
|
-
else if (!filter.includeArchived) where.push(
|
|
348
|
+
if (filter.archivedOnly) where.push(`${as}archived_at IS NOT NULL`);
|
|
349
|
+
else if (!filter.includeArchived) where.push(`${as}archived_at IS NULL`);
|
|
318
350
|
|
|
319
351
|
// The graph view shows current beliefs. Superseded ones stay reachable by
|
|
320
352
|
// walking a `supersedes` edge from the node that replaced them, which is where
|
|
321
353
|
// that history belongs.
|
|
322
|
-
if (!filter.includeSuperseded) where.push(
|
|
354
|
+
if (!filter.includeSuperseded) where.push(`${as}superseded_by IS NULL`);
|
|
323
355
|
|
|
324
356
|
return { where, params };
|
|
325
357
|
}
|
|
@@ -437,10 +469,9 @@ export const graphQueries = {
|
|
|
437
469
|
|
|
438
470
|
getByIds(ids: string[]): GraphNode[] {
|
|
439
471
|
if (ids.length === 0) return [];
|
|
440
|
-
const placeholders = ids.map(() => '?').join(',');
|
|
441
472
|
const rows = getDatabase()
|
|
442
|
-
.prepare(`SELECT * FROM graph_nodes WHERE id IN
|
|
443
|
-
.all(
|
|
473
|
+
.prepare(`SELECT * FROM graph_nodes WHERE id IN ${ID_SET}`)
|
|
474
|
+
.all(idSet(ids)) as GraphNodeRow[];
|
|
444
475
|
return rows.map(toNode);
|
|
445
476
|
},
|
|
446
477
|
|
|
@@ -767,11 +798,13 @@ export const graphQueries = {
|
|
|
767
798
|
if (nodeIds.length === 0) return byNode;
|
|
768
799
|
const rows = getDatabase()
|
|
769
800
|
.prepare(
|
|
770
|
-
`SELECT node_id, name FROM graph_node_entities WHERE node_id IN
|
|
801
|
+
`SELECT node_id, name FROM graph_node_entities WHERE node_id IN ${ID_SET}`
|
|
771
802
|
)
|
|
772
|
-
.all(
|
|
803
|
+
.all(idSet(nodeIds)) as { node_id: string; name: string }[];
|
|
773
804
|
for (const row of rows) {
|
|
774
|
-
|
|
805
|
+
const names = byNode.get(row.node_id);
|
|
806
|
+
if (names) names.push(row.name);
|
|
807
|
+
else byNode.set(row.node_id, [row.name]);
|
|
775
808
|
}
|
|
776
809
|
return byNode;
|
|
777
810
|
},
|
|
@@ -813,7 +846,7 @@ export const graphQueries = {
|
|
|
813
846
|
/** Links each memory draws per group, toward the heaviest members. */
|
|
814
847
|
const LINKS_PER_MEMBER = 4;
|
|
815
848
|
|
|
816
|
-
const
|
|
849
|
+
const set = idSet(nodeIds);
|
|
817
850
|
const edges: { srcId: string; dstId: string; weight: number; via: 'subject' | 'project' }[] = [];
|
|
818
851
|
const seen = new Set<string>();
|
|
819
852
|
|
|
@@ -837,12 +870,21 @@ export const graphQueries = {
|
|
|
837
870
|
`SELECT e.entity_key AS groupKey, e.node_id AS nodeId
|
|
838
871
|
FROM graph_node_entities e
|
|
839
872
|
INNER JOIN graph_nodes n ON n.id = e.node_id
|
|
840
|
-
WHERE e.node_id IN
|
|
873
|
+
WHERE e.node_id IN ${ID_SET}
|
|
841
874
|
ORDER BY e.entity_key, n.weight DESC, n.updated_at DESC`
|
|
842
875
|
)
|
|
843
|
-
.all(
|
|
876
|
+
.all(set) as { groupKey: string; nodeId: string }[];
|
|
877
|
+
// Appended, not rebuilt. Spreading the existing array on every row made this
|
|
878
|
+
// quadratic in the size of a group — invisible for the subject groups, which
|
|
879
|
+
// are capped at two dozen, and the dominant cost of the whole call for the
|
|
880
|
+
// project groups, which routinely run to hundreds before the size check
|
|
881
|
+
// below discards them.
|
|
844
882
|
const bySubject = new Map<string, string[]>();
|
|
845
|
-
for (const row of rows)
|
|
883
|
+
for (const row of rows) {
|
|
884
|
+
const members = bySubject.get(row.groupKey);
|
|
885
|
+
if (members) members.push(row.nodeId);
|
|
886
|
+
else bySubject.set(row.groupKey, [row.nodeId]);
|
|
887
|
+
}
|
|
846
888
|
// `members` is heaviest-first, so linking forward attaches the tail of a
|
|
847
889
|
// subject to its most reinforced memories rather than to whichever happened
|
|
848
890
|
// to be written first.
|
|
@@ -861,12 +903,16 @@ export const graphQueries = {
|
|
|
861
903
|
const projectRows = getDatabase()
|
|
862
904
|
.prepare(
|
|
863
905
|
`SELECT project_id AS groupKey, id AS nodeId FROM graph_nodes
|
|
864
|
-
WHERE id IN
|
|
906
|
+
WHERE id IN ${ID_SET} AND project_id IS NOT NULL AND kind = 'episodic'
|
|
865
907
|
ORDER BY project_id, weight DESC, updated_at DESC`
|
|
866
908
|
)
|
|
867
|
-
.all(
|
|
909
|
+
.all(set) as { groupKey: string; nodeId: string }[];
|
|
868
910
|
const byProject = new Map<string, string[]>();
|
|
869
|
-
for (const row of projectRows)
|
|
911
|
+
for (const row of projectRows) {
|
|
912
|
+
const members = byProject.get(row.groupKey);
|
|
913
|
+
if (members) members.push(row.nodeId);
|
|
914
|
+
else byProject.set(row.groupKey, [row.nodeId]);
|
|
915
|
+
}
|
|
870
916
|
for (const members of byProject.values()) connect(members, 0.4, 'project');
|
|
871
917
|
|
|
872
918
|
return edges;
|
|
@@ -1250,14 +1296,30 @@ export const graphQueries = {
|
|
|
1250
1296
|
/** Every edge with both ends inside the given set — the induced subgraph. */
|
|
1251
1297
|
edgesWithin(nodeIds: string[]): GraphEdge[] {
|
|
1252
1298
|
if (nodeIds.length === 0) return [];
|
|
1253
|
-
|
|
1299
|
+
|
|
1300
|
+
/**
|
|
1301
|
+
* Driven from the index, with the second end checked in JS.
|
|
1302
|
+
*
|
|
1303
|
+
* `WHERE src_id IN (…) AND dst_id IN (…)` reads naturally and is 200× slower,
|
|
1304
|
+
* measured: SQLite scans `graph_edges` and tests each row against a set of up
|
|
1305
|
+
* to three thousand values twice over, using neither of the indexes on the
|
|
1306
|
+
* columns being tested. 220 ms for 1,789 edges. Joining the id set to
|
|
1307
|
+
* `idx_graph_edges_src` turns it into one seek per id — 1 ms for the same
|
|
1308
|
+
* data — and the surviving rows are few enough that filtering the far end
|
|
1309
|
+
* against a `Set` here costs nothing.
|
|
1310
|
+
*
|
|
1311
|
+
* The placeholder form this replaced was no better; the cost was never the
|
|
1312
|
+
* binding, it was the plan.
|
|
1313
|
+
*/
|
|
1314
|
+
const wanted = new Set(nodeIds);
|
|
1254
1315
|
const rows = getDatabase()
|
|
1255
1316
|
.prepare(
|
|
1256
|
-
`SELECT
|
|
1257
|
-
|
|
1317
|
+
`SELECT e.* FROM json_each(?) ids
|
|
1318
|
+
INNER JOIN graph_edges e ON e.src_id = ids.value`
|
|
1258
1319
|
)
|
|
1259
|
-
.all(
|
|
1260
|
-
|
|
1320
|
+
.all(idSet(nodeIds)) as GraphEdgeRow[];
|
|
1321
|
+
|
|
1322
|
+
return rows.filter(row => wanted.has(row.dst_id)).map(toEdge);
|
|
1261
1323
|
},
|
|
1262
1324
|
|
|
1263
1325
|
/**
|
|
@@ -1355,6 +1417,36 @@ export const graphQueries = {
|
|
|
1355
1417
|
return rows.map(toNode);
|
|
1356
1418
|
},
|
|
1357
1419
|
|
|
1420
|
+
/**
|
|
1421
|
+
* The same listing, narrowed to a rectangle of the persisted layout.
|
|
1422
|
+
*
|
|
1423
|
+
* This is what opening a bin reads, and it is why the view can be complete
|
|
1424
|
+
* without being unbounded: zooming into part of the map costs that part. The
|
|
1425
|
+
* bounds come from the layout's own coordinate space, which the client already
|
|
1426
|
+
* holds — every mark it drew carries the cell it stands for.
|
|
1427
|
+
*/
|
|
1428
|
+
listInRegion(
|
|
1429
|
+
filter: GraphListFilter & { limit?: number },
|
|
1430
|
+
region: { minX: number; maxX: number; minY: number; maxY: number }
|
|
1431
|
+
): GraphNode[] {
|
|
1432
|
+
const { where, params } = buildNodeFilter(filter);
|
|
1433
|
+
where.push(
|
|
1434
|
+
`id IN (SELECT node_id FROM graph_layout
|
|
1435
|
+
WHERE x >= ? AND x <= ? AND y >= ? AND y <= ?)`
|
|
1436
|
+
);
|
|
1437
|
+
params.push(region.minX, region.maxX, region.minY, region.maxY);
|
|
1438
|
+
params.push(filter.limit ?? 2000);
|
|
1439
|
+
|
|
1440
|
+
const rows = getDatabase()
|
|
1441
|
+
.prepare(
|
|
1442
|
+
`SELECT * FROM graph_nodes WHERE ${where.join(' AND ')}
|
|
1443
|
+
ORDER BY pinned DESC, weight DESC, updated_at DESC
|
|
1444
|
+
LIMIT ?`
|
|
1445
|
+
)
|
|
1446
|
+
.all(...params) as GraphNodeRow[];
|
|
1447
|
+
return rows.map(toNode);
|
|
1448
|
+
},
|
|
1449
|
+
|
|
1358
1450
|
/**
|
|
1359
1451
|
* Whether the graph holds any live memory at all.
|
|
1360
1452
|
*
|
|
@@ -1762,3 +1854,296 @@ export const graphQueries = {
|
|
|
1762
1854
|
return Number(result.changes ?? 0);
|
|
1763
1855
|
}
|
|
1764
1856
|
};
|
|
1857
|
+
|
|
1858
|
+
/** One node's place in the persisted arrangement. */
|
|
1859
|
+
export interface GraphLayoutRow {
|
|
1860
|
+
nodeId: string;
|
|
1861
|
+
community: number;
|
|
1862
|
+
x: number;
|
|
1863
|
+
y: number;
|
|
1864
|
+
/**
|
|
1865
|
+
* 1 when the force simulation computed this position, 0 when it is a guess
|
|
1866
|
+
* from the community's neighbourhood. See migration 067 for why the two must
|
|
1867
|
+
* stay distinguishable.
|
|
1868
|
+
*/
|
|
1869
|
+
placed: number;
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
/** How many nodes match a filter, and the rectangle their layout occupies. */
|
|
1873
|
+
export interface GraphLayoutExtent {
|
|
1874
|
+
total: number;
|
|
1875
|
+
/** Matching nodes with no position yet — counted, but outside the bounds. */
|
|
1876
|
+
unplaced: number;
|
|
1877
|
+
minX: number;
|
|
1878
|
+
maxX: number;
|
|
1879
|
+
minY: number;
|
|
1880
|
+
maxY: number;
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
/** The grid a binned view is rolled up to, in layout coordinates. */
|
|
1884
|
+
export interface GraphBinGrid {
|
|
1885
|
+
originX: number;
|
|
1886
|
+
originY: number;
|
|
1887
|
+
cellWidth: number;
|
|
1888
|
+
cellHeight: number;
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
/** One occupied cell: how many it holds, where they average, and which speaks for it. */
|
|
1892
|
+
export interface GraphBinRow {
|
|
1893
|
+
cellX: number;
|
|
1894
|
+
cellY: number;
|
|
1895
|
+
members: number;
|
|
1896
|
+
x: number;
|
|
1897
|
+
y: number;
|
|
1898
|
+
/** The most reinforced member — the mark itself when `members` is 1. */
|
|
1899
|
+
id: string;
|
|
1900
|
+
label: string;
|
|
1901
|
+
community: number;
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
export interface GraphBinEdgeRow {
|
|
1905
|
+
srcX: number;
|
|
1906
|
+
srcY: number;
|
|
1907
|
+
dstX: number;
|
|
1908
|
+
dstY: number;
|
|
1909
|
+
weight: number;
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
/**
|
|
1913
|
+
* Reading and writing the persisted arrangement (see migration 067).
|
|
1914
|
+
*
|
|
1915
|
+
* Kept apart from `graphQueries` because it answers a different question:
|
|
1916
|
+
* `graphQueries` is about what is remembered, this is about how it is drawn.
|
|
1917
|
+
* Every row here is derived and disposable — deleting the table costs one
|
|
1918
|
+
* background pass and no memory.
|
|
1919
|
+
*/
|
|
1920
|
+
export const graphLayoutQueries = {
|
|
1921
|
+
/** Positions and communities for a set of nodes. */
|
|
1922
|
+
read(nodeIds: string[]): Map<string, GraphLayoutRow> {
|
|
1923
|
+
const result = new Map<string, GraphLayoutRow>();
|
|
1924
|
+
if (nodeIds.length === 0) return result;
|
|
1925
|
+
const rows = getDatabase()
|
|
1926
|
+
.prepare(
|
|
1927
|
+
`SELECT node_id AS nodeId, community, x, y, placed FROM graph_layout
|
|
1928
|
+
WHERE node_id IN ${ID_SET}`
|
|
1929
|
+
)
|
|
1930
|
+
.all(idSet(nodeIds)) as GraphLayoutRow[];
|
|
1931
|
+
for (const row of rows) result.set(row.nodeId, row);
|
|
1932
|
+
return result;
|
|
1933
|
+
},
|
|
1934
|
+
|
|
1935
|
+
/** Replace the arrangement for the nodes given, in one transaction. */
|
|
1936
|
+
writeMany(rows: GraphLayoutRow[]): number {
|
|
1937
|
+
if (rows.length === 0) return 0;
|
|
1938
|
+
return graphQueries.transaction(() => {
|
|
1939
|
+
const statement = getDatabase().prepare(
|
|
1940
|
+
`INSERT INTO graph_layout (node_id, community, x, y, placed, updated_at)
|
|
1941
|
+
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
|
|
1942
|
+
ON CONFLICT(node_id) DO UPDATE SET
|
|
1943
|
+
community = excluded.community, x = excluded.x, y = excluded.y,
|
|
1944
|
+
placed = excluded.placed, updated_at = CURRENT_TIMESTAMP`
|
|
1945
|
+
);
|
|
1946
|
+
for (const row of rows) {
|
|
1947
|
+
statement.run(row.nodeId, row.community, row.x, row.y, row.placed);
|
|
1948
|
+
}
|
|
1949
|
+
return rows.length;
|
|
1950
|
+
});
|
|
1951
|
+
},
|
|
1952
|
+
|
|
1953
|
+
/**
|
|
1954
|
+
* Live nodes in the order the view itself ranks them, for the layout pass.
|
|
1955
|
+
*
|
|
1956
|
+
* Capped, because a force layout over an unbounded set is unbounded work. What
|
|
1957
|
+
* survives the cap is what the view would have shown anyway — pinned, then
|
|
1958
|
+
* most reinforced, then most recent — so anything left unplaced is also the
|
|
1959
|
+
* least likely to be looked at.
|
|
1960
|
+
*/
|
|
1961
|
+
liveNodeIds(limit: number): string[] {
|
|
1962
|
+
const rows = getDatabase()
|
|
1963
|
+
.prepare(
|
|
1964
|
+
// `id` is the tiebreak, and it is load-bearing rather than tidy. Most
|
|
1965
|
+
// live nodes share a weight and a timestamp, so without it SQLite is
|
|
1966
|
+
// free to return ties in any order — and this order decides the order
|
|
1967
|
+
// the layout graph is built in, which ForceAtlas2 is sensitive to. The
|
|
1968
|
+
// same store laid out to a different map on every pass.
|
|
1969
|
+
`SELECT id FROM graph_nodes
|
|
1970
|
+
WHERE archived_at IS NULL AND superseded_by IS NULL
|
|
1971
|
+
ORDER BY pinned DESC, weight DESC, updated_at DESC, id ASC
|
|
1972
|
+
LIMIT ?`
|
|
1973
|
+
)
|
|
1974
|
+
.all(limit) as { id: string }[];
|
|
1975
|
+
return rows.map(row => row.id);
|
|
1976
|
+
},
|
|
1977
|
+
|
|
1978
|
+
/** Whether any live node is still waiting to be placed. */
|
|
1979
|
+
hasUnplaced(): boolean {
|
|
1980
|
+
const row = getDatabase()
|
|
1981
|
+
.prepare(
|
|
1982
|
+
`SELECT 1 AS present FROM graph_nodes n
|
|
1983
|
+
LEFT JOIN graph_layout l ON l.node_id = n.id
|
|
1984
|
+
WHERE n.archived_at IS NULL AND n.superseded_by IS NULL AND l.node_id IS NULL
|
|
1985
|
+
LIMIT 1`
|
|
1986
|
+
)
|
|
1987
|
+
.get() as { present: number } | null;
|
|
1988
|
+
return row !== null && row !== undefined;
|
|
1989
|
+
},
|
|
1990
|
+
|
|
1991
|
+
/** Rows whose node no longer exists. Foreign keys are not always enforced. */
|
|
1992
|
+
pruneOrphans(): number {
|
|
1993
|
+
const result = getDatabase()
|
|
1994
|
+
.prepare(`DELETE FROM graph_layout WHERE node_id NOT IN (SELECT id FROM graph_nodes)`)
|
|
1995
|
+
.run() as { changes?: number };
|
|
1996
|
+
return Number(result.changes ?? 0);
|
|
1997
|
+
},
|
|
1998
|
+
|
|
1999
|
+
/** Drop the whole arrangement — used when the graph is purged. */
|
|
2000
|
+
clear(): void {
|
|
2001
|
+
getDatabase().prepare(`DELETE FROM graph_layout`).run();
|
|
2002
|
+
},
|
|
2003
|
+
|
|
2004
|
+
/**
|
|
2005
|
+
* How many nodes match, and the rectangle their arrangement occupies.
|
|
2006
|
+
*
|
|
2007
|
+
* One pass answering both, because the two are always wanted together: the
|
|
2008
|
+
* count decides whether the view has to bin at all, and the extent is what the
|
|
2009
|
+
* grid is laid over. `MIN`/`MAX` skip NULLs, so a node still waiting to be
|
|
2010
|
+
* placed is counted without dragging the bounds toward the origin.
|
|
2011
|
+
*/
|
|
2012
|
+
extent(filter: GraphListFilter): GraphLayoutExtent {
|
|
2013
|
+
const { where, params } = buildNodeFilter(filter, 'n.');
|
|
2014
|
+
const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
|
|
2015
|
+
|
|
2016
|
+
const row = getDatabase()
|
|
2017
|
+
.prepare(
|
|
2018
|
+
`SELECT COUNT(*) AS total,
|
|
2019
|
+
SUM(CASE WHEN l.node_id IS NULL THEN 1 ELSE 0 END) AS unplaced,
|
|
2020
|
+
MIN(l.x) AS minX, MAX(l.x) AS maxX,
|
|
2021
|
+
MIN(l.y) AS minY, MAX(l.y) AS maxY
|
|
2022
|
+
FROM graph_nodes n
|
|
2023
|
+
LEFT JOIN graph_layout l ON l.node_id = n.id
|
|
2024
|
+
${clause}`
|
|
2025
|
+
)
|
|
2026
|
+
.get(...params) as {
|
|
2027
|
+
total: number;
|
|
2028
|
+
unplaced: number | null;
|
|
2029
|
+
minX: number | null;
|
|
2030
|
+
maxX: number | null;
|
|
2031
|
+
minY: number | null;
|
|
2032
|
+
maxY: number | null;
|
|
2033
|
+
};
|
|
2034
|
+
|
|
2035
|
+
return {
|
|
2036
|
+
total: row.total ?? 0,
|
|
2037
|
+
unplaced: row.unplaced ?? 0,
|
|
2038
|
+
minX: row.minX ?? 0,
|
|
2039
|
+
maxX: row.maxX ?? 0,
|
|
2040
|
+
minY: row.minY ?? 0,
|
|
2041
|
+
maxY: row.maxY ?? 0
|
|
2042
|
+
};
|
|
2043
|
+
},
|
|
2044
|
+
|
|
2045
|
+
/**
|
|
2046
|
+
* One row per occupied cell of the grid: its size, its centroid, and its most
|
|
2047
|
+
* reinforced member.
|
|
2048
|
+
*
|
|
2049
|
+
* The count of rows is bounded by the grid, not by the store — that is the
|
|
2050
|
+
* whole point. A cell holding one memory comes back with `members = 1` and
|
|
2051
|
+
* that memory's id, so the caller can return the memory ITSELF rather than a
|
|
2052
|
+
* bin standing for it; below the render budget that is every cell, and the
|
|
2053
|
+
* view is bit-for-bit the flat one.
|
|
2054
|
+
*
|
|
2055
|
+
* `CAST(... AS INTEGER)` truncates toward zero, which would fold the cells on
|
|
2056
|
+
* either side of the origin into one — the grid is therefore anchored at the
|
|
2057
|
+
* arrangement's minimum, so every offset it sees is positive.
|
|
2058
|
+
*/
|
|
2059
|
+
binnedNodes(filter: GraphListFilter, grid: GraphBinGrid): GraphBinRow[] {
|
|
2060
|
+
const { where, params } = buildNodeFilter(filter, 'n.');
|
|
2061
|
+
const clause = where.length ? `WHERE ${where.join(' AND ')}` : '';
|
|
2062
|
+
|
|
2063
|
+
return getDatabase()
|
|
2064
|
+
.prepare(
|
|
2065
|
+
`SELECT cellX, cellY, members, cx AS x, cy AS y, id, label, community
|
|
2066
|
+
FROM (
|
|
2067
|
+
SELECT cellX, cellY, id, label, community,
|
|
2068
|
+
COUNT(*) OVER (PARTITION BY cellX, cellY) AS members,
|
|
2069
|
+
AVG(x) OVER (PARTITION BY cellX, cellY) AS cx,
|
|
2070
|
+
AVG(y) OVER (PARTITION BY cellX, cellY) AS cy,
|
|
2071
|
+
ROW_NUMBER() OVER (
|
|
2072
|
+
PARTITION BY cellX, cellY
|
|
2073
|
+
ORDER BY pinned DESC, weight DESC, updated_at DESC
|
|
2074
|
+
) AS rn
|
|
2075
|
+
FROM (
|
|
2076
|
+
SELECT CAST((l.x - ?) / ? AS INTEGER) AS cellX,
|
|
2077
|
+
CAST((l.y - ?) / ? AS INTEGER) AS cellY,
|
|
2078
|
+
l.x AS x, l.y AS y, l.community AS community,
|
|
2079
|
+
n.id AS id, n.label AS label,
|
|
2080
|
+
n.pinned AS pinned, n.weight AS weight, n.updated_at AS updated_at
|
|
2081
|
+
FROM graph_nodes n
|
|
2082
|
+
INNER JOIN graph_layout l ON l.node_id = n.id
|
|
2083
|
+
${clause}
|
|
2084
|
+
)
|
|
2085
|
+
)
|
|
2086
|
+
WHERE rn = 1`
|
|
2087
|
+
)
|
|
2088
|
+
.all(
|
|
2089
|
+
grid.originX,
|
|
2090
|
+
grid.cellWidth,
|
|
2091
|
+
grid.originY,
|
|
2092
|
+
grid.cellHeight,
|
|
2093
|
+
...params
|
|
2094
|
+
) as GraphBinRow[];
|
|
2095
|
+
},
|
|
2096
|
+
|
|
2097
|
+
/**
|
|
2098
|
+
* Edges rolled up to the same grid, so the binned picture keeps its structure.
|
|
2099
|
+
*
|
|
2100
|
+
* Stored edges only. The derived ones (see `derivedEdges`) exist to hold a
|
|
2101
|
+
* subject's memories together, and the layout pass already consumed them —
|
|
2102
|
+
* their effect is in the POSITIONS, which is where it belongs at this
|
|
2103
|
+
* resolution. Recomputing them here would mean handing this query the id of
|
|
2104
|
+
* every matching node, which is the unbounded thing the grid exists to avoid.
|
|
2105
|
+
*
|
|
2106
|
+
* Edges inside a single cell are dropped: both ends are the same mark.
|
|
2107
|
+
*/
|
|
2108
|
+
binnedEdges(filter: GraphListFilter, grid: GraphBinGrid, limit: number): GraphBinEdgeRow[] {
|
|
2109
|
+
const src = buildNodeFilter(filter, 'na.');
|
|
2110
|
+
const dst = buildNodeFilter(filter, 'nb.');
|
|
2111
|
+
const conditions = [...src.where, ...dst.where];
|
|
2112
|
+
const clause = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
2113
|
+
|
|
2114
|
+
return getDatabase()
|
|
2115
|
+
.prepare(
|
|
2116
|
+
`SELECT srcX, srcY, dstX, dstY, SUM(weight) AS weight
|
|
2117
|
+
FROM (
|
|
2118
|
+
SELECT CAST((la.x - ?) / ? AS INTEGER) AS srcX,
|
|
2119
|
+
CAST((la.y - ?) / ? AS INTEGER) AS srcY,
|
|
2120
|
+
CAST((lb.x - ?) / ? AS INTEGER) AS dstX,
|
|
2121
|
+
CAST((lb.y - ?) / ? AS INTEGER) AS dstY,
|
|
2122
|
+
e.weight AS weight
|
|
2123
|
+
FROM graph_edges e
|
|
2124
|
+
INNER JOIN graph_layout la ON la.node_id = e.src_id
|
|
2125
|
+
INNER JOIN graph_layout lb ON lb.node_id = e.dst_id
|
|
2126
|
+
INNER JOIN graph_nodes na ON na.id = e.src_id
|
|
2127
|
+
INNER JOIN graph_nodes nb ON nb.id = e.dst_id
|
|
2128
|
+
${clause}
|
|
2129
|
+
)
|
|
2130
|
+
WHERE NOT (srcX = dstX AND srcY = dstY)
|
|
2131
|
+
GROUP BY 1, 2, 3, 4
|
|
2132
|
+
ORDER BY weight DESC
|
|
2133
|
+
LIMIT ?`
|
|
2134
|
+
)
|
|
2135
|
+
.all(
|
|
2136
|
+
grid.originX,
|
|
2137
|
+
grid.cellWidth,
|
|
2138
|
+
grid.originY,
|
|
2139
|
+
grid.cellHeight,
|
|
2140
|
+
grid.originX,
|
|
2141
|
+
grid.cellWidth,
|
|
2142
|
+
grid.originY,
|
|
2143
|
+
grid.cellHeight,
|
|
2144
|
+
...src.params,
|
|
2145
|
+
...dst.params,
|
|
2146
|
+
limit
|
|
2147
|
+
) as GraphBinEdgeRow[];
|
|
2148
|
+
}
|
|
2149
|
+
};
|