@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.
Files changed (42) hide show
  1. package/backend/chat/stream-manager.ts +1 -1
  2. package/backend/database/migrations/067_add_memory_graph_layout.ts +91 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/graph-queries.ts +417 -32
  5. package/backend/db-client/drivers/mssql.ts +57 -22
  6. package/backend/db-client/drivers/mysql.ts +69 -48
  7. package/backend/db-client/drivers/postgres.ts +65 -53
  8. package/backend/engine/adapters/claude/stream.ts +81 -15
  9. package/backend/engine/adapters/codex/stream.ts +6 -3
  10. package/backend/engine/adapters/opencode/server.ts +13 -4
  11. package/backend/engine/bootstrap-default-engine.ts +67 -38
  12. package/backend/engine/docs/artifacts.md +1 -1
  13. package/backend/engine/docs/quick-reference.md +1 -1
  14. package/backend/engine/engine-cli.ts +313 -0
  15. package/backend/engine/engine-setup.ts +40 -3
  16. package/backend/engine/install-recipes.test.ts +99 -5
  17. package/backend/engine/install-recipes.ts +47 -11
  18. package/backend/engine/install-runner.ts +34 -16
  19. package/backend/engine/stack-project.ts +72 -0
  20. package/backend/index.ts +5 -0
  21. package/backend/memory/bootstrap.ts +9 -0
  22. package/backend/memory/layout.ts +985 -0
  23. package/backend/memory/notify.ts +33 -7
  24. package/backend/memory/view.ts +375 -69
  25. package/backend/permissions/index.ts +4 -2
  26. package/backend/permissions/resolve.ts +7 -5
  27. package/backend/utils/path-enrich.ts +2 -0
  28. package/backend/utils/process-warnings.ts +41 -0
  29. package/backend/ws/engine/claude/accounts.ts +9 -4
  30. package/backend/ws/engine/codex/accounts.ts +8 -5
  31. package/backend/ws/engine/codex/status.ts +10 -17
  32. package/backend/ws/memory/crud.ts +50 -2
  33. package/backend/ws/settings/crud.ts +1 -1
  34. package/backend/ws/stack/access.ts +5 -2
  35. package/dist/assets/{index-C7e5TWG3.js → index-DUc5T21e.js} +1 -1
  36. package/dist/assets/{index-Derlqeyy.js → index-DYwQ5bP8.js} +1 -1
  37. package/dist/assets/main-VgdjTBLR.css +1 -0
  38. package/dist/assets/{main-OGhsRKU1.js → main-r0iv2PDz.js} +393 -386
  39. package/dist/index.html +2 -2
  40. package/package.json +1 -1
  41. package/shared/types/memory.ts +70 -0
  42. package/dist/assets/main-CqzaPnux.css +0 -1
@@ -20,6 +20,7 @@
20
20
  */
21
21
 
22
22
  import { ws } from '$backend/utils/ws';
23
+ import { scheduleGraphLayout } from './layout';
23
24
  import { debug } from '$shared/utils/logger';
24
25
 
25
26
  /**
@@ -44,22 +45,47 @@ let statusTimer: ReturnType<typeof setTimeout> | null = null;
44
45
  export function notifyGraphChanged(reason: string, projectId: string | null = null): void {
45
46
  pendingReason = reason;
46
47
  pendingProjectId = projectId;
48
+
49
+ // The arrangement is derived from the graph, so anything that changes one
50
+ // changes the other. Hanging it off this call rather than off each write path
51
+ // keeps a single answer to "the graph moved" — and the pass debounces far
52
+ // longer than the broadcast does, because a position that settles four
53
+ // seconds late costs nothing while a view that updates four seconds late is
54
+ // the bug this notification exists to fix.
55
+ scheduleGraphLayout();
56
+
47
57
  if (timer) return;
48
58
 
49
59
  timer = setTimeout(() => {
50
60
  timer = null;
51
- try {
52
- ws.emit.global('memory:changed', { reason: pendingReason, projectId: pendingProjectId });
53
- } catch (error) {
54
- // A view that misses a refresh is a stale view, not a broken one, and this
55
- // is called from write paths that must never fail for a UI concern.
56
- debug.warn('memory', 'Failed to broadcast memory change', error);
57
- }
61
+ broadcastGraphChanged(pendingReason, pendingProjectId);
58
62
  }, COALESCE_MS);
59
63
  // Housekeeping — never a reason to hold the process open at shutdown.
60
64
  timer.unref?.();
61
65
  }
62
66
 
67
+ /**
68
+ * Ring the doorbell without asking for a new arrangement.
69
+ *
70
+ * The layout pass calls this when it has written new positions. It must NOT go
71
+ * through `notifyGraphChanged`, which schedules a layout — a pass announcing its
72
+ * own result would ask for another one, and while that next pass would find
73
+ * nothing to do and return early, a job that re-queues itself every time it
74
+ * succeeds is a shape worth not having.
75
+ *
76
+ * Uncoalesced, because a pass is already debounced by seconds and produces at
77
+ * most one of these.
78
+ */
79
+ export function broadcastGraphChanged(reason: string, projectId: string | null = null): void {
80
+ try {
81
+ ws.emit.global('memory:changed', { reason, projectId });
82
+ } catch (error) {
83
+ // A view that misses a refresh is a stale view, not a broken one, and this
84
+ // is called from write paths that must never fail for a UI concern.
85
+ debug.warn('memory', 'Failed to broadcast memory change', error);
86
+ }
87
+ }
88
+
63
89
  /**
64
90
  * Tell open views that the extraction queue moved.
65
91
  *
@@ -1,39 +1,68 @@
1
1
  /**
2
2
  * Graph view assembly for the visualization.
3
3
  *
4
- * Community detection runs HERE, not in the browser. Louvain is O(n log n)-ish
5
- * but iterative, and running it on the client would compete with the force
6
- * simulation for the same main thread on exactly the low-powered devices this
7
- * has to stay usable on. It is also stable per dataset, so computing it server
8
- * side lets the result be sent once instead of recomputed on every mount.
4
+ * ── What this file is NOT allowed to do any more ─────────────────────────────
5
+ * It used to run Louvain on every call. Community detection is stable per
6
+ * dataset, so opening the modal, changing a filter, or any conversation
7
+ * recording a memory made every connected client pay for the same clustering
8
+ * again — and the cost grew with the store rather than with what was on screen.
9
+ * It now lives in `graph_layout`, written by the background pass in `layout.ts`,
10
+ * and this file only reads it.
9
11
  *
10
- * Communities are what make the view legible: each becomes a coloured "lobe", so
11
- * the clustering the user sees comes out of their own memory's structure rather
12
- * than being imposed by a layout algorithm.
12
+ * ── Showing everything, at bounded cost ──────────────────────────────────────
13
+ * The old view answered scale with a cap: return the three thousand most
14
+ * reinforced memories and set `truncated`. That is not a scale strategy, it is a
15
+ * silent ceiling — past it the rest of the store simply was not in the picture,
16
+ * with no way to reach it but narrowing a filter.
17
+ *
18
+ * The answer here is to aggregate by POSITION rather than to trim by rank, and
19
+ * the difference is what the user sees. Grouping by community — the obvious
20
+ * alternative, and the first thing tried — replaces the picture: you get lobes
21
+ * instead of memories, and reaching any memory means opening one first. Grouping
22
+ * by position keeps the picture. The layout plane is divided into a grid fine
23
+ * enough that the number of OCCUPIED cells is bounded, and each occupied cell
24
+ * becomes one mark. Marks merge only where their dots would have overlapped
25
+ * anyway, so the silhouette, the lobes and the colours are the ones the full
26
+ * graph would have drawn, and nothing is missing from it.
27
+ *
28
+ * Below `RENDER_BUDGET` no cell holds more than one memory, so every mark IS a
29
+ * memory and the view is exactly the flat one it always was. Above it, a cell
30
+ * holding one memory still returns that memory — fidelity is lost only where
31
+ * the display had none to give.
32
+ *
33
+ * Zooming into a mark asks for its cell as a rectangle, which costs that
34
+ * rectangle rather than the store.
13
35
  */
14
36
 
15
- import Graph from 'graphology';
16
- import louvain from 'graphology-communities-louvain';
17
- import { graphQueries } from '$backend/database/queries/graph-queries';
18
- import { debug } from '$shared/utils/logger';
37
+ import { graphQueries, graphLayoutQueries, type GraphBinGrid } from '$backend/database/queries/graph-queries';
19
38
  import type {
39
+ GraphNode,
20
40
  GraphNodeKind,
41
+ GraphRegion,
21
42
  GraphScope,
22
43
  GraphSource,
23
44
  GraphView,
45
+ GraphViewBin,
46
+ GraphViewBinEdge,
24
47
  GraphViewEdge,
25
48
  GraphViewNode
26
49
  } from '$shared/types/memory';
27
50
 
28
51
  /**
29
- * Nodes sent to the client at once.
52
+ * Marks the client is asked to draw at once.
30
53
  *
31
- * Beyond a few thousand, a force layout stops communicating structure — it
32
- * becomes a hairball — and the payload starts costing more than it explains. The
33
- * cap is reported through `truncated` so the UI can say so rather than implying
34
- * the graph is smaller than it is.
54
+ * A ceiling on the WORK, not on the content: past it marks merge rather than
55
+ * disappear. Set where a WebGL scene stays comfortable on a low-powered machine
56
+ * — the graph build, sigma's indexation and the per-frame reducers are all
57
+ * linear in this number, and it is the only number they are linear in.
35
58
  */
36
- const MAX_VIEW_NODES = 3_000;
59
+ const RENDER_BUDGET = 3_000;
60
+
61
+ /** Bin edges drawn at once, heaviest first. Lines are cheaper than marks, not free. */
62
+ const MAX_BIN_EDGES = 6_000;
63
+
64
+ /** Longest caption a mark carries; the full text belongs to the inspector. */
65
+ const BIN_LABEL_MAX = 60;
37
66
 
38
67
  export interface GraphViewFilter {
39
68
  /** `undefined` = every project (cross-project view); `null` = global only. */
@@ -49,28 +78,75 @@ export interface GraphViewFilter {
49
78
  includeArchived?: boolean;
50
79
  /** Show memories that have been replaced by a newer belief. Off by default. */
51
80
  includeSuperseded?: boolean;
81
+ /**
82
+ * A rectangle of the layout to restrict to — how a mark is opened.
83
+ *
84
+ * Navigation, not filtering: it narrows what is DRAWN without changing what
85
+ * the graph is, which is why the totals it reports are the region's.
86
+ */
87
+ region?: GraphRegion;
52
88
  limit?: number;
53
89
  }
54
90
 
55
91
  export function buildGraphView(filter: GraphViewFilter): GraphView {
56
- const limit = Math.min(filter.limit ?? MAX_VIEW_NODES, MAX_VIEW_NODES);
92
+ const limit = Math.min(filter.limit ?? RENDER_BUDGET, RENDER_BUDGET);
93
+ const region = filter.region ?? null;
57
94
 
58
- // `list` orders by pinned, then weight, then recency — so when the cap bites,
59
- // what survives is what the user reinforced and touched most recently.
60
- const nodes = graphQueries.list({ ...filter, limit });
61
- const totalNodes = graphQueries.count(filter);
95
+ // Zoomed in: the rectangle is already a bounded slice of the arrangement, so
96
+ // it is drawn at full fidelity and counted within itself.
97
+ if (region) {
98
+ const nodes = graphQueries.listInRegion({ ...filter, limit }, region);
99
+ return flat(nodes, region, nodes.length, false);
100
+ }
101
+
102
+ const extent = graphLayoutQueries.extent(filter);
103
+
104
+ // Either it fits, or nothing has been laid out yet — a fresh install, or the
105
+ // first fetch after the upgrade added the table. Both draw the flat view: the
106
+ // second because binning needs positions, and falling back to what the feature
107
+ // always did means the graph is never empty while the background pass catches
108
+ // up.
109
+ const laidOut = extent.total - extent.unplaced;
110
+ if (extent.total <= RENDER_BUDGET || laidOut === 0) {
111
+ const nodes = graphQueries.list({ ...filter, limit });
112
+ return flat(nodes, null, extent.total, extent.total > nodes.length);
113
+ }
114
+
115
+ return binned(filter, extent, limit);
116
+ }
62
117
 
118
+ /**
119
+ * Every matching memory, drawn individually.
120
+ *
121
+ * The ordinary case and the one the view is tuned for — below the render budget
122
+ * this is the whole story, and it is unchanged from before any of this existed.
123
+ */
124
+ function flat(
125
+ nodes: GraphNode[],
126
+ region: GraphRegion | null,
127
+ totalNodes: number,
128
+ truncated: boolean
129
+ ): GraphView {
63
130
  if (nodes.length === 0) {
64
- return { nodes: [], edges: [], totalNodes, truncated: false };
131
+ return {
132
+ level: 'flat',
133
+ nodes: [],
134
+ edges: [],
135
+ bins: [],
136
+ binEdges: [],
137
+ region,
138
+ totalNodes,
139
+ truncated: false
140
+ };
65
141
  }
66
142
 
67
- const ids = nodes.map(n => n.id);
143
+ const ids = nodes.map(node => node.id);
68
144
  const stored = graphQueries.edgesWithin(ids);
69
145
 
70
146
  // Two memories about the same subject ARE connected, and that connection is
71
147
  // stated by extraction rather than inferred from how they are worded. It is
72
148
  // derived here rather than stored, so it can never outlive the claim it came
73
- // from — see `derivedEntityEdges`.
149
+ // from — see `derivedEdges`.
74
150
  //
75
151
  // Without it the episodic half has almost no structure at all. Similarity
76
152
  // linking used to supply it, badly: on a real graph 144 of 371 edges were
@@ -88,70 +164,300 @@ export function buildGraphView(filter: GraphViewFilter): GraphView {
88
164
  weight: edge.weight
89
165
  }));
90
166
 
91
- // Undirected for community detection: `about` and `imports` point one way, but
92
- // whether two nodes belong to the same cluster does not depend on direction,
93
- // and treating them as directed splits obvious groups in half.
94
- const graph = new Graph({ type: 'undirected', multi: false });
95
- for (const node of nodes) graph.addNode(node.id);
96
-
167
+ // Degree is counted over what is being DRAWN, so a node's size answers "how
168
+ // connected is this within what I am looking at" — which is the question the
169
+ // eye is actually asking.
97
170
  const degree = new Map<string, number>();
98
- const link = (srcId: string, dstId: string, weight: number): void => {
171
+ const bump = (srcId: string, dstId: string): void => {
99
172
  degree.set(srcId, (degree.get(srcId) ?? 0) + 1);
100
173
  degree.set(dstId, (degree.get(dstId) ?? 0) + 1);
101
- if (srcId === dstId) return;
102
- if (!graph.hasNode(srcId) || !graph.hasNode(dstId)) return;
103
- if (!graph.hasEdge(srcId, dstId)) graph.addUndirectedEdge(srcId, dstId, { weight });
104
174
  };
105
- for (const edge of stored) link(edge.srcId, edge.dstId, edge.weight);
106
- for (const edge of derived) link(edge.source, edge.target, edge.weight);
107
-
108
- let communities: Record<string, number> = {};
109
- try {
110
- // Louvain needs at least one edge; an edgeless graph leaves every node in
111
- // its own community, which is also the honest answer.
112
- if (graph.size > 0) {
113
- communities = louvain(graph, { getEdgeWeight: 'weight' });
175
+ for (const edge of stored) bump(edge.srcId, edge.dstId);
176
+ for (const edge of derived) bump(edge.source, edge.target);
177
+
178
+ const layout = graphLayoutQueries.read(ids);
179
+ const viewNodes = nodes.map(node => toViewNode(node, degree.get(node.id) ?? 0, layout.get(node.id)));
180
+ placeArrivals(viewNodes, [...stored.map(edge => ({ source: edge.srcId, target: edge.dstId })), ...derived]);
181
+
182
+ return {
183
+ level: 'flat',
184
+ nodes: viewNodes,
185
+ edges: [
186
+ ...stored.map(edge => ({
187
+ id: edge.id,
188
+ source: edge.srcId,
189
+ target: edge.dstId,
190
+ rel: edge.rel,
191
+ weight: edge.weight
192
+ })),
193
+ ...derived
194
+ ],
195
+ bins: [],
196
+ binEdges: [],
197
+ region,
198
+ totalNodes,
199
+ truncated
200
+ };
201
+ }
202
+
203
+ /**
204
+ * The whole graph, with crowded neighbourhoods folded into single marks.
205
+ *
206
+ * Cells holding exactly one memory come back as that memory, so this is a flat
207
+ * view everywhere the display could have drawn one — which, in a force layout,
208
+ * is most of the periphery. Only the dense middle merges, and only as far as it
209
+ * was going to overlap.
210
+ */
211
+ function binned(
212
+ filter: GraphViewFilter,
213
+ extent: { total: number; minX: number; maxX: number; minY: number; maxY: number },
214
+ limit: number
215
+ ): GraphView {
216
+ const grid = gridFor(extent);
217
+ const cells = graphLayoutQueries.binnedNodes(filter, grid);
218
+
219
+ // A cell of one is not a bin, it is a memory. Splitting them here is what
220
+ // keeps the picture inspectable: everything the grid did not have to merge
221
+ // stays clickable, hoverable and highlightable exactly as before.
222
+ const singles = cells.filter(cell => cell.members === 1);
223
+ const groups = cells.filter(cell => cell.members > 1);
224
+
225
+ const nodes = graphQueries.getByIds(singles.map(cell => cell.id));
226
+ const byId = new Map(nodes.map(node => [node.id, node]));
227
+ const layout = graphLayoutQueries.read(nodes.map(node => node.id));
228
+
229
+ // Which mark each cell is, so the rolled-up edges can name their ends. A
230
+ // single's mark is the memory's own id; a group's is the cell.
231
+ const markOf = new Map<string, string>();
232
+ for (const cell of cells) {
233
+ markOf.set(cellKey(cell.cellX, cell.cellY), cell.members === 1 ? cell.id : binId(cell.cellX, cell.cellY));
234
+ }
235
+
236
+ const binEdges: GraphViewBinEdge[] = [];
237
+ const nodeEdges: GraphViewEdge[] = [];
238
+ let syntheticId = -1;
239
+
240
+ for (const edge of graphLayoutQueries.binnedEdges(filter, grid, MAX_BIN_EDGES)) {
241
+ const source = markOf.get(cellKey(edge.srcX, edge.srcY));
242
+ const target = markOf.get(cellKey(edge.dstX, edge.dstY));
243
+ if (!source || !target || source === target) continue;
244
+
245
+ // An edge between two singles is a real edge between two real memories, and
246
+ // the canvas dims and highlights those against the node it is anchored on.
247
+ // Demoting it to a bin edge would break hover on exactly the marks that did
248
+ // not need binning in the first place.
249
+ if (byId.has(source) && byId.has(target)) {
250
+ nodeEdges.push({
251
+ id: syntheticId--,
252
+ source,
253
+ target,
254
+ rel: 'relates_to',
255
+ weight: edge.weight
256
+ });
257
+ } else {
258
+ binEdges.push({ source, target, weight: edge.weight });
114
259
  }
115
- } catch (error) {
116
- // A failed clustering must not cost the user their graph — the view just
117
- // renders in one colour.
118
- debug.warn('memory', 'Community detection failed; rendering without lobes', error);
119
- communities = {};
120
260
  }
121
261
 
122
- const viewNodes: GraphViewNode[] = nodes.map(node => ({
262
+ // Degree over what is drawn, same as the flat path — counting both kinds of
263
+ // edge, because a memory next to a dense clump is well connected whether or
264
+ // not the thing it connects to had to be merged.
265
+ const degree = new Map<string, number>();
266
+ const bump = (id: string): void => {
267
+ degree.set(id, (degree.get(id) ?? 0) + 1);
268
+ };
269
+ for (const edge of nodeEdges) {
270
+ bump(edge.source);
271
+ bump(edge.target);
272
+ }
273
+ for (const edge of binEdges) {
274
+ bump(edge.source);
275
+ bump(edge.target);
276
+ }
277
+
278
+ const bins: GraphViewBin[] = groups.map(cell => ({
279
+ id: binId(cell.cellX, cell.cellY),
280
+ members: cell.members,
281
+ label: truncate(cell.label ?? ''),
282
+ community: cell.community,
283
+ x: cell.x,
284
+ y: cell.y,
285
+ region: {
286
+ minX: grid.originX + cell.cellX * grid.cellWidth,
287
+ maxX: grid.originX + (cell.cellX + 1) * grid.cellWidth,
288
+ minY: grid.originY + cell.cellY * grid.cellHeight,
289
+ maxY: grid.originY + (cell.cellY + 1) * grid.cellHeight
290
+ }
291
+ }));
292
+
293
+ return {
294
+ level: 'binned',
295
+ nodes: singles
296
+ .map(cell => byId.get(cell.id))
297
+ .filter((node): node is GraphNode => node !== undefined)
298
+ .map(node => toViewNode(node, degree.get(node.id) ?? 0, layout.get(node.id))),
299
+ edges: nodeEdges,
300
+ bins,
301
+ binEdges,
302
+ region: null,
303
+ totalNodes: extent.total,
304
+ // Nothing was left out — every memory is inside one of these marks. The
305
+ // only thing a binned view withholds is which memory is which inside a
306
+ // crowd, and opening the mark answers that.
307
+ truncated: nodes.length + bins.length > limit
308
+ };
309
+ }
310
+
311
+ /**
312
+ * The grid, sized so the number of cells cannot exceed the render budget.
313
+ *
314
+ * Cells are square in layout space rather than fitted to the extent's aspect
315
+ * ratio: a non-square cell merges more readily along one axis than the other,
316
+ * which shows up as marks that smear horizontally or vertically — the eye reads
317
+ * that as structure, and there is none.
318
+ */
319
+ function gridFor(extent: { minX: number; maxX: number; minY: number; maxY: number }): GraphBinGrid {
320
+ const width = Math.max(1e-6, extent.maxX - extent.minX);
321
+ const height = Math.max(1e-6, extent.maxY - extent.minY);
322
+
323
+ // One axis of the grid. Squared, this is the cell count, so it is the budget's
324
+ // square root — and the longer side sets the cell size for both.
325
+ const perAxis = Math.max(1, Math.floor(Math.sqrt(RENDER_BUDGET)));
326
+ const cell = Math.max(width, height) / perAxis;
327
+
328
+ return {
329
+ originX: extent.minX,
330
+ originY: extent.minY,
331
+ cellWidth: cell,
332
+ cellHeight: cell
333
+ };
334
+ }
335
+
336
+ function toViewNode(
337
+ node: GraphNode,
338
+ degree: number,
339
+ placed?: { community: number; x: number; y: number; placed: number }
340
+ ): GraphViewNode {
341
+ return {
123
342
  id: node.id,
124
343
  kind: node.kind,
125
344
  subkind: node.subkind,
126
345
  scope: node.scope,
127
346
  label: node.label,
128
347
  projectId: node.projectId,
129
- degree: degree.get(node.id) ?? 0,
348
+ degree,
130
349
  weight: node.weight,
131
350
  pinned: node.pinned,
132
- community: communities[node.id] ?? 0,
133
- createdAt: node.createdAt
134
- }));
351
+ community: placed?.community ?? 0,
352
+ createdAt: node.createdAt,
353
+ // Sent ONLY when the simulation computed it. A memory written since the
354
+ // last pass has no row at all, and one below the simulation cap has a row
355
+ // holding a guess — in both cases the client seeds it from its neighbours,
356
+ // which is a far better answer than drawing a whole lobe on one point.
357
+ ...(placed?.placed === 1 && { x: placed.x, y: placed.y })
358
+ };
359
+ }
360
+
361
+ /**
362
+ * Give a position to anything the arrangement has not reached yet.
363
+ *
364
+ * A memory recorded while the modal is open has no layout row: the background
365
+ * pass is debounced behind the notification that announces the memory, so the
366
+ * first fetch after it lands is always a few seconds early. Sending it without
367
+ * coordinates left the client to invent some, and what it invented was the
368
+ * middle of the map — a new memory appearing nowhere near the subject it is
369
+ * about.
370
+ *
371
+ * Derived HERE instead, from the same rule the layout pass itself uses: the
372
+ * centroid of whatever it connects to. The answer is therefore the one the pass
373
+ * will confirm a few seconds later rather than one it will have to correct, and
374
+ * the client stops having an opinion about placement at all.
375
+ *
376
+ * Read-time only — nothing is written. A position that has not been through the
377
+ * simulation is a guess, and guesses do not belong in the table the simulation
378
+ * owns.
379
+ *
380
+ * A node with no placed neighbour is deliberately LEFT without a position. That
381
+ * is the honest signal for "the arrangement does not cover this yet", and it is
382
+ * what the client's cold fallback keys on — inventing a centroid for a store that
383
+ * has never been laid out would replace a considered scatter with a meaningless
384
+ * one.
385
+ */
386
+ function placeArrivals(nodes: GraphViewNode[], edges: { source: string; target: string }[]): void {
387
+ const arrivals = nodes.filter(node => node.x === undefined);
388
+ if (arrivals.length === 0) return;
389
+
390
+ const byId = new Map(nodes.map(node => [node.id, node]));
391
+ const adjacency = new Map<string, string[]>();
392
+ const link = (from: string, to: string): void => {
393
+ const neighbours = adjacency.get(from);
394
+ if (neighbours) neighbours.push(to);
395
+ else adjacency.set(from, [to]);
396
+ };
397
+ for (const edge of edges) {
398
+ link(edge.source, edge.target);
399
+ link(edge.target, edge.source);
400
+ }
401
+
402
+ // Three passes, so a small cluster of arrivals resolves outward from whichever
403
+ // end touches the existing map rather than all of them giving up at once.
404
+ for (let pass = 0; pass < 3; pass++) {
405
+ let settled = 0;
135
406
 
136
- const viewEdges: GraphViewEdge[] = [
137
- ...stored.map(edge => ({
138
- id: edge.id,
139
- source: edge.srcId,
140
- target: edge.dstId,
141
- rel: edge.rel,
142
- weight: edge.weight
143
- })),
144
- ...derived
145
- ];
407
+ for (const node of arrivals) {
408
+ if (node.x !== undefined) continue;
146
409
 
410
+ let sumX = 0;
411
+ let sumY = 0;
412
+ let count = 0;
413
+ for (const neighbour of adjacency.get(node.id) ?? []) {
414
+ const other = byId.get(neighbour);
415
+ if (!other || other.x === undefined || other.y === undefined) continue;
416
+ sumX += other.x;
417
+ sumY += other.y;
418
+ count++;
419
+ }
420
+ if (count === 0) continue;
421
+
422
+ // Nudged off the exact centroid, or several arrivals about one subject
423
+ // land on the same point and read as a single node.
424
+ const jitter = jitterOf(node.id);
425
+ node.x = sumX / count + jitter.x * 24;
426
+ node.y = sumY / count + jitter.y * 24;
427
+ settled++;
428
+ }
429
+
430
+ if (settled === 0) break;
431
+ }
432
+ }
433
+
434
+ /** A deterministic offset in [-1, 1]², derived from an id. FNV-1a. */
435
+ function jitterOf(id: string): { x: number; y: number } {
436
+ let hash = 2166136261;
437
+ for (let i = 0; i < id.length; i++) {
438
+ hash ^= id.charCodeAt(i);
439
+ hash = Math.imul(hash, 16777619);
440
+ }
441
+ hash = hash >>> 0;
147
442
  return {
148
- nodes: viewNodes,
149
- edges: viewEdges,
150
- totalNodes,
151
- truncated: totalNodes > nodes.length
443
+ x: ((hash % 65536) / 65536) * 2 - 1,
444
+ y: (((hash >>> 16) % 65536) / 65536) * 2 - 1
152
445
  };
153
446
  }
154
447
 
448
+ /** Namespaced so a bin's id can never collide with a node's. */
449
+ function binId(cellX: number, cellY: number): string {
450
+ return `bin:${cellX}:${cellY}`;
451
+ }
452
+
453
+ function cellKey(cellX: number, cellY: number): string {
454
+ return `${cellX}:${cellY}`;
455
+ }
456
+
457
+ function truncate(label: string): string {
458
+ return label.length > BIN_LABEL_MAX ? `${label.slice(0, BIN_LABEL_MAX - 1)}…` : label;
459
+ }
460
+
155
461
  /** A node plus the nodes it reaches — what the inspector renders. */
156
462
  export function buildNodeDetail(nodeId: string, hops = 1) {
157
463
  const node = graphQueries.getById(nodeId);
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Permissions — public facade. Settings → Permissions manages per-engine tool
3
- * allow/deny rules; enforcement is a runtime hook each engine adapter consults
4
- * at its auto-approve point (see `resolvePermissionsFromDb` + `isToolAllowed`).
3
+ * allow/deny rules; enforcement is a runtime check each engine adapter performs
4
+ * (see `resolvePermissionsFromDb` + `isToolAllowed`) at whichever surface fires
5
+ * for every tool call — for Claude that is a `PreToolUse` hook, because its
6
+ * permission callback is shadowed under `bypassPermissions`.
5
7
  */
6
8
 
7
9
  export {
@@ -2,11 +2,13 @@
2
2
  * Permission resolution — the pure decision logic behind Settings → Permissions.
3
3
  *
4
4
  * A permission set is a pair of tool-pattern lists (`allow` + `deny`) stored per
5
- * `(scope, project, engine)`. This module answers one question at the engine's
6
- * auto-approve hook: *is this tool allowed to run?* The stored sets are enforced
7
- * at runtime (each engine consults {@link isToolAllowed} in the hook it already
8
- * uses to auto-approve tools — see the adapters), which is why enforcement is
9
- * real even though every engine otherwise auto-approves.
5
+ * `(scope, project, engine)`. This module answers one question: *is this tool
6
+ * allowed to run?* The stored sets are enforced at runtime — each engine calls
7
+ * {@link isToolAllowed} from whichever surface it has that fires for every tool
8
+ * call (see the adapters) — which is why enforcement is real even though every
9
+ * engine otherwise auto-approves. Claude uses a `PreToolUse` hook rather than
10
+ * its permission callback: `bypassPermissions` auto-approves a call before the
11
+ * callback is consulted, so a check there would never run.
10
12
  *
11
13
  * Resolution across the two scopes (documented in migration 049):
12
14
  * - deny = global.deny ∪ project.deny (deny always adds restriction)
@@ -84,6 +84,8 @@ function windowsKnownDirs(): string[] {
84
84
  join(home, '.bun', 'bin'),
85
85
  join(home, '.deno', 'bin'),
86
86
  join(home, '.cargo', 'bin'),
87
+ // install-script target (Open Code), the Windows twin of the posix entry
88
+ join(home, '.opencode', 'bin'),
87
89
  join(home, 'scoop', 'shims'),
88
90
  join(localAppData, 'Microsoft', 'WinGet', 'Links'),
89
91
  join(localAppData, 'Programs', 'Git', 'cmd'),
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Process warning filter — the single place that decides which
3
+ * `process.emitWarning` output reaches the server log.
4
+ *
5
+ * Registering ANY 'warning' listener silences the runtime's default printer
6
+ * (Bun only prints when the event has no listener at all — verified on Bun
7
+ * 1.3.x, where `process.listenerCount('warning')` is 0 out of the box). So this
8
+ * module owns the printing too: anything it does not explicitly suppress is
9
+ * re-emitted to the log, or we would swallow deprecation notices,
10
+ * MaxListenersExceededWarning, TimeoutOverflowWarning and friends.
11
+ *
12
+ * Suppress by `code`, never by message text — codes are stable, wording is not.
13
+ */
14
+
15
+ import { debug } from '$shared/utils/logger';
16
+
17
+ /**
18
+ * Warning codes we deliberately drop, each with the reason it is noise here.
19
+ *
20
+ * - CLAUDE_SDK_CAN_USE_TOOL_SHADOWED: @anthropic-ai/claude-agent-sdk >= 0.3.229
21
+ * emits this on every query() when `canUseTool` is passed alongside
22
+ * permissionMode 'bypassPermissions' — a static check on the options object,
23
+ * not an observed failure. Clopen keeps the callback for one job the CLI does
24
+ * still route through it (AskUserQuestion, which must wait on a human without
25
+ * a deadline); tool gating moved to the PreToolUse hook the warning itself
26
+ * recommends. See backend/engine/adapters/claude/stream.ts.
27
+ */
28
+ const SUPPRESSED_WARNING_CODES = new Set(['CLAUDE_SDK_CAN_USE_TOOL_SHADOWED']);
29
+
30
+ let installed = false;
31
+
32
+ /** Idempotent — safe to call from more than one entry point. */
33
+ export function installProcessWarningFilter(): void {
34
+ if (installed) return;
35
+ installed = true;
36
+
37
+ process.on('warning', (warning: Error & { code?: string }) => {
38
+ if (warning.code && SUPPRESSED_WARNING_CODES.has(warning.code)) return;
39
+ debug.warn('server', warning.stack || `${warning.name}: ${warning.message}`);
40
+ });
41
+ }