@anmol-srv/sigil 0.18.2 → 0.22.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 (47) hide show
  1. package/README.md +37 -25
  2. package/dist/cli.js +1191 -790
  3. package/dist/daemon.js +664 -302
  4. package/dist/hooks/post-tool-use.js +1 -69
  5. package/dist/hooks/session-end.js +13 -236
  6. package/dist/hooks/stop.js +36 -246
  7. package/dist/hooks/user-prompt-submit.js +25 -288
  8. package/dist/mcp/worker-server.js +6 -0
  9. package/dist/npm-entry.js +10 -0
  10. package/dist/server.js +64 -56
  11. package/install.sh +207 -0
  12. package/integrations/hermes/README.md +30 -24
  13. package/integrations/hermes/plugin/README.md +1 -1
  14. package/integrations/hermes/plugin/__init__.py +68 -24
  15. package/knexfile.js +19 -22
  16. package/package.json +9 -28
  17. package/prompts/audm-decision.md +26 -1
  18. package/prompts/entity-extraction.md +32 -30
  19. package/prompts/graph-extraction.md +20 -2
  20. package/src/db/drivers/index.js +38 -15
  21. package/src/db/migrations/20260629120000_add-trace-event-attribution.cjs +29 -0
  22. package/src/db/migrations/20260629120001_add-llm-log-session-correlation.cjs +29 -0
  23. package/src/db/migrations/20260806120000_add-document-content.cjs +27 -0
  24. package/src/db/migrations/20260806120001_llm-log-model-nullable.cjs +36 -0
  25. package/src/db/migrations/20260811120000_add-relation-provenance.cjs +42 -0
  26. package/src/db/migrations/20260811130000_add-fact-visibility.cjs +67 -0
  27. package/src/db/migrations/20260813090000_rescore-defaulted-vital.cjs +57 -0
  28. package/src/db/migrations/20260814120000_create-ingestion-job.cjs +52 -0
  29. package/src/db/migrations/20260814120100_add-llm-log-queued-ms.cjs +8 -0
  30. package/src/db/migrations/20260814120200_add-active-fact-content-hash-index.cjs +16 -0
  31. package/src/db/migrations/20260814120300_create-relation-candidate-judgment.cjs +25 -0
  32. package/src/gui/web/app.css +851 -84
  33. package/src/gui/web/app.js +796 -383
  34. package/src/gui/web/cmdk.js +238 -0
  35. package/src/gui/web/components.js +64 -0
  36. package/src/gui/web/design/colors_and_type.css +6 -1
  37. package/src/gui/web/graph/GraphIsland.jsx +450 -0
  38. package/src/gui/web/graph/cluster.js +305 -0
  39. package/src/gui/web/graph/cluster.test.js +219 -0
  40. package/src/gui/web/health.js +117 -0
  41. package/src/gui/web/health.test.js +159 -0
  42. package/src/gui/web/icons.js +65 -0
  43. package/src/gui/web/index.html +310 -115
  44. package/src/gui/web/settings.js +386 -0
  45. package/src/gui/web/setup.js +2 -2
  46. package/src/gui/web/toast.js +6 -3
  47. package/src/gui/web/vendor/graph-island.js +52 -0
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Community detection + anchor placement for the graph view.
3
+ *
4
+ * The graph was one dense glob for two separate reasons, and this fixes both:
5
+ *
6
+ * 1. Every connected component was pulled to the SAME origin by forceX(0)/
7
+ * forceY(0), so 78 components stacked on top of each other. Giving each
8
+ * community its own anchor is what un-stacks them.
9
+ * 2. The giant component (59% of nodes on a real store) had no internal
10
+ * structure to show. Louvain finds it from the link topology alone.
11
+ *
12
+ * Communities are expressed through SPACE first — each gets its own anchor —
13
+ * and colour second. Colour was reassigned from --etype-* to cluster because the
14
+ * type channel is near-constant on a real store (301 topics vs 1 person), so it
15
+ * spent the whole budget saying nothing. Only the top regions get a hue; minor
16
+ * and unconnected clusters stay neutral, which keeps the canvas from becoming
17
+ * the "multi-color" decoration DESIGN.md rules out.
18
+ *
19
+ * Deterministic by construction — nodes are visited in a canonical id order and
20
+ * there is no RNG anywhere, so the same store always lays out the same way even
21
+ * if the caller hands the nodes over in a different order. A graph that
22
+ * reshuffles itself on every reload is worse than one that is merely dense.
23
+ *
24
+ * ponytail: hand-rolled Louvain rather than graphology + graphology-communities-
25
+ * louvain, which would add ~80KB to a 382KB bundle to cluster ~500 nodes. If the
26
+ * communities ever come out unstable or poorly separated, swapping the library
27
+ * in behind clusterGraph()'s signature is the upgrade path.
28
+ */
29
+
30
+ import { schemeSet3 } from 'd3-scale-chromatic';
31
+
32
+ /** Cluster id for nodes with no edges at all — they share one parked bucket. */
33
+ export const UNCONNECTED = -1;
34
+
35
+ /**
36
+ * Cluster id for every community too small to deserve its own place on the
37
+ * canvas. Giving all 53 communities an anchor scattered 40-odd two-node
38
+ * fragments across the whole viewport at radius 1000+, which reads as noise:
39
+ * a 3-node fragment is not a region of your knowledge, it is a loose end.
40
+ * They all share one anchor and settle as a single outlying group.
41
+ */
42
+ export const MINOR = -2;
43
+
44
+ /**
45
+ * Region colour comes from d3-scale-chromatic, which force-graph already
46
+ * depends on — so this costs nothing and replaces ~30 lines of hand-rolled HSL.
47
+ *
48
+ * force-graph has `nodeAutoColorBy`, which does exactly this job. It is not
49
+ * used here for two specific reasons: its scale is hardcoded to schemePaired,
50
+ * a LIGHT-background ColorBrewer set whose #6a3d9a only reaches 2.56:1 on our
51
+ * near-black canvas, and it would colour the parked groups too, when grey is
52
+ * doing real work as "too few links to be a region".
53
+ *
54
+ * schemeSet3 instead: of the qualitative schemes shipped here it is the only
55
+ * one where all twelve clear 3:1 against --bg-1. Its own grey (#d9d9d9) is
56
+ * dropped, since grey is reserved.
57
+ *
58
+ * No qualitative palette separates every pair at eleven categories — the
59
+ * validator rejects all of them, ColorBrewer included. Spatial separation and
60
+ * the hub labels are what carry identity; colour marks the boundaries.
61
+ */
62
+ const REGION_SCHEME = schemeSet3.filter((c) => c !== '#d9d9d9');
63
+
64
+ /**
65
+ * Colours for n regions, by rank. Keyed to rank, not to n, so gaining a region
66
+ * never repaints the others. Cycles if a graph somehow exceeds the scheme.
67
+ */
68
+ export function regionShades(n) {
69
+ if (n <= 0) return [];
70
+ return Array.from({ length: n }, (_, i) => REGION_SCHEME[i % REGION_SCHEME.length]);
71
+ }
72
+
73
+ const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
74
+ const EPS = 1e-12;
75
+
76
+ /** Weighted adjacency + self-loop weights for one level of the hierarchy. */
77
+ function buildAdjacency(size, edges) {
78
+ const adj = Array.from({ length: size }, () => new Map());
79
+ const self = new Float64Array(size);
80
+ for (const [a, b, w] of edges) {
81
+ if (a === b) { self[a] += w; continue; }
82
+ adj[a].set(b, (adj[a].get(b) || 0) + w);
83
+ adj[b].set(a, (adj[b].get(a) || 0) + w);
84
+ }
85
+ return { adj, self };
86
+ }
87
+
88
+ /** k_i — weighted degree, self-loops counted twice as the modularity math wants. */
89
+ function weightedDegrees(adj, self) {
90
+ return adj.map((neighbours, i) => {
91
+ let k = 2 * self[i];
92
+ for (const w of neighbours.values()) k += w;
93
+ return k;
94
+ });
95
+ }
96
+
97
+ /**
98
+ * Louvain phase 1. Each node starts alone, then repeatedly moves to whichever
99
+ * neighbouring community yields the largest modularity gain:
100
+ *
101
+ * ΔQ ∝ k_i,in − (Σ_tot · k_i) / 2m
102
+ *
103
+ * Ties break toward the lower community index so the result cannot depend on
104
+ * Map iteration order.
105
+ */
106
+ function localMoving(adj, self, k, m2) {
107
+ const size = adj.length;
108
+ const community = new Int32Array(size);
109
+ const sigmaTot = Float64Array.from(k);
110
+ for (let i = 0; i < size; i++) community[i] = i;
111
+
112
+ for (let pass = 0; pass < 20; pass++) {
113
+ let moved = 0;
114
+ for (let i = 0; i < size; i++) {
115
+ const from = community[i];
116
+ const linksTo = new Map();
117
+ for (const [j, w] of adj[i]) {
118
+ const cj = community[j];
119
+ linksTo.set(cj, (linksTo.get(cj) || 0) + w);
120
+ }
121
+
122
+ // Pull i out of its community BEFORE scoring, so staying put is judged on
123
+ // the same footing as every alternative.
124
+ sigmaTot[from] -= k[i];
125
+ let best = from;
126
+ let bestGain = (linksTo.get(from) || 0) - (sigmaTot[from] * k[i]) / m2;
127
+ for (const [c, w] of linksTo) {
128
+ if (c === from) continue;
129
+ const gain = w - (sigmaTot[c] * k[i]) / m2;
130
+ if (gain > bestGain + EPS || (Math.abs(gain - bestGain) <= EPS && c < best)) {
131
+ best = c;
132
+ bestGain = gain;
133
+ }
134
+ }
135
+ sigmaTot[best] += k[i];
136
+ if (best !== from) { community[i] = best; moved++; }
137
+ }
138
+ if (!moved) break;
139
+ }
140
+ return community;
141
+ }
142
+
143
+ /** Compact community ids to 0..n-1, preserving first-seen order. */
144
+ function renumber(community) {
145
+ const seen = new Map();
146
+ const out = new Int32Array(community.length);
147
+ for (let i = 0; i < community.length; i++) {
148
+ const c = community[i];
149
+ if (!seen.has(c)) seen.set(c, seen.size);
150
+ out[i] = seen.get(c);
151
+ }
152
+ return { compact: out, count: seen.size };
153
+ }
154
+
155
+ /** Louvain phase 2 — collapse each community into a single node. */
156
+ function aggregate(edges, compact) {
157
+ const merged = new Map();
158
+ for (const [a, b, w] of edges) {
159
+ const ca = compact[a];
160
+ const cb = compact[b];
161
+ const key = ca < cb ? `${ca}|${cb}` : `${cb}|${ca}`;
162
+ merged.set(key, (merged.get(key) || 0) + w);
163
+ }
164
+ return [...merged].map(([key, w]) => {
165
+ const [a, b] = key.split('|');
166
+ return [Number(a), Number(b), w];
167
+ });
168
+ }
169
+
170
+ /** Full Louvain: local moving, then aggregate, until a level stops merging. */
171
+ function louvain(size, edges) {
172
+ let membership = Array.from({ length: size }, (_, i) => i);
173
+ let levelSize = size;
174
+ let levelEdges = edges;
175
+
176
+ for (let level = 0; level < 12; level++) {
177
+ const { adj, self } = buildAdjacency(levelSize, levelEdges);
178
+ const k = weightedDegrees(adj, self);
179
+ const m2 = k.reduce((a, b) => a + b, 0);
180
+ if (!m2) break;
181
+
182
+ const { compact, count } = renumber(localMoving(adj, self, k, m2));
183
+ if (count === levelSize) break; // nothing merged — modularity has converged
184
+
185
+ membership = membership.map((c) => compact[c]);
186
+ levelEdges = aggregate(levelEdges, compact);
187
+ levelSize = count;
188
+ }
189
+ return membership;
190
+ }
191
+
192
+ /**
193
+ * Cluster a node/edge set and hand back both the per-node assignment and the
194
+ * anchor each cluster should be pulled toward.
195
+ *
196
+ * Anchors sit on a phyllotaxis spiral: the largest cluster takes the origin and
197
+ * the rest fan outward, which keeps the mass centred (so zoomToFit still frames
198
+ * well) while guaranteeing no two clusters share a target. The unconnected
199
+ * bucket is forced outermost — 39 lonely nodes have no business competing for
200
+ * the middle with a real community.
201
+ */
202
+ export function clusterGraph(nodes, edges, opts = {}) {
203
+ const spread = opts.spread ?? 150;
204
+ // Louvain's result depends on the order nodes are visited, and the caller's
205
+ // order is NOT stable — graphSnapshot's entity query has no ORDER BY, so the
206
+ // DB may hand back rows differently between loads. Sorting by id here makes
207
+ // the clustering a function of the graph alone, so the same store lays out
208
+ // the same way every time regardless of who assembled the input.
209
+ const ordered = [...nodes].sort((a, b) => String(a.id).localeCompare(String(b.id)));
210
+ const index = new Map(ordered.map((n, i) => [n.id, i]));
211
+ const degree = new Array(ordered.length).fill(0);
212
+ const pairs = [];
213
+
214
+ for (const e of edges) {
215
+ // force-graph rewrites link.source/target from an id into the node object
216
+ // once the simulation starts, so accept either shape.
217
+ const a = index.get(e.source?.id ?? e.source);
218
+ const b = index.get(e.target?.id ?? e.target);
219
+ if (a === undefined || b === undefined || a === b) continue;
220
+ pairs.push([a, b, 1]);
221
+ degree[a] += 1;
222
+ degree[b] += 1;
223
+ }
224
+
225
+ const membership = pairs.length ? louvain(ordered.length, pairs) : [];
226
+
227
+ const assignment = new Map();
228
+ const members = new Map();
229
+ ordered.forEach((n, i) => {
230
+ const id = degree[i] === 0 ? UNCONNECTED : membership[i];
231
+ assignment.set(n.id, id);
232
+ if (!members.has(id)) members.set(id, []);
233
+ members.get(id).push(n);
234
+ });
235
+
236
+ // Biggest first so the densest community wins the centre; the parked buckets
237
+ // are last regardless of how many strays they hold.
238
+ const parked = (id) => id === UNCONNECTED || id === MINOR;
239
+ let ranked = [...members.entries()].sort((x, y) => {
240
+ if (parked(x[0]) && !parked(y[0])) return 1;
241
+ if (parked(y[0]) && !parked(x[0])) return -1;
242
+ return y[1].length - x[1].length || x[0] - y[0];
243
+ });
244
+
245
+ // Only communities that are actually substantial get their own anchor. The
246
+ // floor scales with the graph so a small store doesn't fold everything into
247
+ // one blob, and the cap stops a huge store from sprouting 30 regions.
248
+ const minMajor = opts.minMajorSize ?? Math.max(4, Math.round(ordered.length * 0.02));
249
+ const maxMajor = opts.maxMajors ?? 12;
250
+ const minors = [];
251
+ const majors = [];
252
+ for (const entry of ranked) {
253
+ const [id, group] = entry;
254
+ if (!parked(id) && group.length >= minMajor && majors.length < maxMajor) majors.push(entry);
255
+ else if (parked(id)) majors.push(entry);
256
+ else minors.push(entry);
257
+ }
258
+ if (minors.length) {
259
+ const folded = minors.flatMap(([, group]) => group);
260
+ for (const n of folded) assignment.set(n.id, MINOR);
261
+ // Re-rank with the folded group in place, keeping parked buckets last.
262
+ ranked = [...majors.filter(([id]) => !parked(id)),
263
+ [MINOR, folded],
264
+ ...majors.filter(([id]) => parked(id))];
265
+ } else {
266
+ ranked = majors;
267
+ }
268
+
269
+ const clusters = ranked.map(([id, group], i) => {
270
+ const radius = spread * Math.sqrt(i);
271
+ const angle = i * GOLDEN_ANGLE;
272
+ const label = id === MINOR || id === UNCONNECTED ? null : clusterLabel(group);
273
+ return {
274
+ id,
275
+ size: group.length,
276
+ unconnected: id === UNCONNECTED,
277
+ minor: id === MINOR,
278
+ x: Math.round(Math.cos(angle) * radius),
279
+ y: Math.round(Math.sin(angle) * radius),
280
+ label,
281
+ // Filled in from the shade ramp below. Grey is reserved for the two
282
+ // parked groups — it means "too few links to be a region", which is the
283
+ // only thing it should ever have meant.
284
+ color: null,
285
+ };
286
+ });
287
+ const regions = clusters.filter((c) => !c.minor && !c.unconnected);
288
+ const shades = regionShades(regions.length);
289
+ regions.forEach((c, i) => { c.color = shades[i]; });
290
+
291
+ return { assignment, clusters };
292
+ }
293
+
294
+ /**
295
+ * A cluster is named after its best-connected ENTITY. Facts are excluded: a
296
+ * fact's label is a whole sentence, which reads as noise at cluster scale.
297
+ */
298
+ function clusterLabel(group) {
299
+ let best = null;
300
+ for (const n of group) {
301
+ if (n.kind !== 'entity') continue;
302
+ if (!best || (n.degree || 0) > (best.degree || 0)) best = n;
303
+ }
304
+ return best?.label ?? null;
305
+ }
@@ -0,0 +1,219 @@
1
+ import { describe, it, expect } from 'vitest';
2
+
3
+ import { clusterGraph, UNCONNECTED, MINOR, regionShades } from './cluster.js';
4
+
5
+ const entity = (id, label) => ({ id, kind: 'entity', label, entityType: 'topic' });
6
+ const link = (source, target) => ({ source, target });
7
+
8
+ /** Two 4-cliques joined by a single bridge — the textbook community case. */
9
+ function twoCliques() {
10
+ const nodes = ['a1', 'a2', 'a3', 'a4', 'b1', 'b2', 'b3', 'b4'].map((id) => entity(id, id));
11
+ const edges = [];
12
+ for (const g of [['a1', 'a2', 'a3', 'a4'], ['b1', 'b2', 'b3', 'b4']]) {
13
+ for (let i = 0; i < g.length; i++) {
14
+ for (let j = i + 1; j < g.length; j++) edges.push(link(g[i], g[j]));
15
+ }
16
+ }
17
+ edges.push(link('a1', 'b1')); // the bridge
18
+ return { nodes, edges };
19
+ }
20
+
21
+ describe('clusterGraph', () => {
22
+ it('separates two cliques joined by one bridge', () => {
23
+ const { nodes, edges } = twoCliques();
24
+ const { assignment } = clusterGraph(nodes, edges);
25
+
26
+ const a = assignment.get('a1');
27
+ const b = assignment.get('b1');
28
+ expect(a).not.toBe(b);
29
+ for (const id of ['a2', 'a3', 'a4']) expect(assignment.get(id)).toBe(a);
30
+ for (const id of ['b2', 'b3', 'b4']) expect(assignment.get(id)).toBe(b);
31
+ });
32
+
33
+ it('buckets every isolated node into one shared cluster, not one each', () => {
34
+ const { nodes, edges } = twoCliques();
35
+ const lonely = ['x1', 'x2', 'x3'].map((id) => entity(id, id));
36
+ const { assignment, clusters } = clusterGraph([...nodes, ...lonely], edges);
37
+
38
+ for (const id of ['x1', 'x2', 'x3']) expect(assignment.get(id)).toBe(UNCONNECTED);
39
+ const bucket = clusters.find((c) => c.id === UNCONNECTED);
40
+ expect(bucket.size).toBe(3);
41
+ expect(bucket.unconnected).toBe(true);
42
+ });
43
+
44
+ it('is deterministic — a reload must not reshuffle the layout', () => {
45
+ const { nodes, edges } = twoCliques();
46
+ const a = clusterGraph(nodes, edges);
47
+ const b = clusterGraph(nodes, edges);
48
+
49
+ expect([...a.assignment.entries()]).toEqual([...b.assignment.entries()]);
50
+ expect(a.clusters).toEqual(b.clusters);
51
+ });
52
+
53
+ it('is invariant to node order — graphSnapshot does not ORDER BY its entities', () => {
54
+ const { nodes, edges } = twoCliques();
55
+ const forward = clusterGraph(nodes, edges);
56
+ const backward = clusterGraph([...nodes].reverse(), edges);
57
+
58
+ // Ids may differ; the PARTITION must not.
59
+ const partition = ({ assignment }) => {
60
+ const groups = new Map();
61
+ for (const [id, c] of assignment) {
62
+ if (!groups.has(c)) groups.set(c, []);
63
+ groups.get(c).push(id);
64
+ }
65
+ return [...groups.values()].map((g) => g.sort().join(',')).sort();
66
+ };
67
+ expect(partition(backward)).toEqual(partition(forward));
68
+ });
69
+
70
+ it('anchors the largest cluster at the origin and parks the unconnected outermost', () => {
71
+ const { nodes, edges } = twoCliques();
72
+ const lonely = ['x1', 'x2'].map((id) => entity(id, id));
73
+ const extra = [entity('a5', 'a5'), entity('a6', 'a6')];
74
+ const bigger = [...edges, link('a1', 'a5'), link('a2', 'a5'), link('a1', 'a6'), link('a2', 'a6')];
75
+ const { clusters } = clusterGraph([...nodes, ...extra, ...lonely], bigger);
76
+
77
+ const connected = clusters.filter((c) => !c.unconnected);
78
+ const dist = (c) => Math.hypot(c.x, c.y);
79
+ expect(dist(connected[0])).toBe(0);
80
+ expect(connected[0].size).toBeGreaterThanOrEqual(connected[1].size);
81
+
82
+ const bucket = clusters.find((c) => c.unconnected);
83
+ expect(dist(bucket)).toBeGreaterThan(Math.max(...connected.map(dist)));
84
+ });
85
+
86
+ it('every cluster gets a distinct anchor', () => {
87
+ const { nodes, edges } = twoCliques();
88
+ const { clusters } = clusterGraph(nodes, edges);
89
+ const seen = new Set(clusters.map((c) => `${c.x},${c.y}`));
90
+ expect(seen.size).toBe(clusters.length);
91
+ });
92
+
93
+ it('colours every region from the generated ramp — grey means few links', () => {
94
+ const nodes = [];
95
+ const edges = [];
96
+ for (let r = 0; r < 6; r++) {
97
+ for (let i = 0; i < 6; i++) nodes.push(entity(`r${r}n${i}`, `r${r}n${i}`));
98
+ for (let i = 0; i < 6; i++) {
99
+ for (let j = i + 1; j < 6; j++) edges.push(link(`r${r}n${i}`, `r${r}n${j}`));
100
+ }
101
+ if (r) edges.push(link(`r${r}n0`, `r${r - 1}n0`));
102
+ }
103
+ const { clusters } = clusterGraph(nodes, edges, { minMajorSize: 4 });
104
+
105
+ const regions = clusters.filter((c) => !c.minor && !c.unconnected);
106
+ // The ramp sizes itself to the region count — no fixed palette to run out of.
107
+ expect(regions.map((c) => c.color)).toEqual(regionShades(regions.length));
108
+ for (const parked of clusters.filter((c) => c.minor || c.unconnected)) {
109
+ expect(parked.color).toBeNull();
110
+ }
111
+ });
112
+
113
+ it('generates distinct colours, stable per rank rather than per count', () => {
114
+ const ramp = regionShades(11);
115
+ expect(new Set(ramp).size).toBe(11);
116
+ // A region keeps its colour as the graph grows — adding an 11th region must
117
+ // not repaint the other ten.
118
+ expect(regionShades(3)).toEqual(ramp.slice(0, 3));
119
+ expect(regionShades(1)).toHaveLength(1);
120
+ expect(regionShades(0)).toEqual([]);
121
+ });
122
+
123
+ it('never hands a region the grey reserved for "few links"', () => {
124
+ // schemeSet3 ships a grey (#d9d9d9). Grey is load-bearing in this view, so
125
+ // a region must never be painted in it.
126
+ for (const c of regionShades(12)) expect(c).not.toBe('#d9d9d9');
127
+ });
128
+
129
+ it('clears the 3:1 contrast floor against the near-black canvas', () => {
130
+ const lum = (hex) => [1, 3, 5]
131
+ .map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
132
+ .map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4))
133
+ .reduce((a, c, i) => a + [0.2126, 0.7152, 0.0722][i] * c, 0);
134
+ const surface = lum('#0b0c0e');
135
+
136
+ for (const c of regionShades(12)) {
137
+ expect((lum(c) + 0.05) / (surface + 0.05)).toBeGreaterThanOrEqual(3);
138
+ }
139
+ });
140
+
141
+ it('folds small communities into one parked group instead of scattering them', () => {
142
+ // One substantial community plus a spray of 2-node fragments — exactly the
143
+ // shape that flung 40 fragments across the viewport.
144
+ const nodes = [];
145
+ const edges = [];
146
+ for (let i = 0; i < 12; i++) nodes.push(entity(`big${i}`, `big${i}`));
147
+ for (let i = 0; i < 12; i++) {
148
+ for (let j = i + 1; j < 12; j++) edges.push(link(`big${i}`, `big${j}`));
149
+ }
150
+ for (let f = 0; f < 8; f++) {
151
+ nodes.push(entity(`p${f}a`, `p${f}a`), entity(`p${f}b`, `p${f}b`));
152
+ edges.push(link(`p${f}a`, `p${f}b`));
153
+ }
154
+ const { assignment, clusters } = clusterGraph(nodes, edges, { minMajorSize: 5 });
155
+
156
+ for (let f = 0; f < 8; f++) expect(assignment.get(`p${f}a`)).toBe(MINOR);
157
+ const minor = clusters.find((c) => c.id === MINOR);
158
+ expect(minor.size).toBe(16);
159
+ expect(minor.color).toBeNull();
160
+ // 1 real region + 1 parked group, not 9 anchors.
161
+ expect(clusters).toHaveLength(2);
162
+ });
163
+
164
+ it('keeps the parked groups out of the centre', () => {
165
+ const nodes = [];
166
+ const edges = [];
167
+ for (let i = 0; i < 12; i++) nodes.push(entity(`big${i}`, `big${i}`));
168
+ for (let i = 0; i < 12; i++) {
169
+ for (let j = i + 1; j < 12; j++) edges.push(link(`big${i}`, `big${j}`));
170
+ }
171
+ for (let f = 0; f < 6; f++) {
172
+ nodes.push(entity(`p${f}a`, `p${f}a`), entity(`p${f}b`, `p${f}b`));
173
+ edges.push(link(`p${f}a`, `p${f}b`));
174
+ }
175
+ nodes.push(entity('lonely', 'lonely'));
176
+ const { clusters } = clusterGraph(nodes, edges, { minMajorSize: 5 });
177
+
178
+ const dist = (c) => Math.hypot(c.x, c.y);
179
+ const real = clusters.filter((c) => !c.minor && !c.unconnected);
180
+ for (const parked of clusters.filter((c) => c.minor || c.unconnected)) {
181
+ expect(dist(parked)).toBeGreaterThan(Math.max(...real.map(dist)));
182
+ }
183
+ });
184
+
185
+ it('names a cluster after its highest-degree entity, ignoring facts', () => {
186
+ const nodes = [
187
+ entity('e1', 'hub'), entity('e2', 'spoke'),
188
+ { id: 'f1', kind: 'fact', label: 'a fact that mentions everything' },
189
+ ];
190
+ const edges = [link('e1', 'e2'), link('f1', 'e1'), link('f1', 'e2')];
191
+ // minMajorSize:1 — a 3-node graph is otherwise all "minor", which is right
192
+ // in the app and beside the point here.
193
+ const { clusters } = clusterGraph(nodes, edges, { minMajorSize: 1 });
194
+
195
+ expect(clusters[0].label).toBe('hub');
196
+ });
197
+
198
+ it('assigns every node exactly once, including on an edgeless graph', () => {
199
+ const nodes = ['n1', 'n2'].map((id) => entity(id, id));
200
+ const { assignment, clusters } = clusterGraph(nodes, []);
201
+
202
+ expect(assignment.size).toBe(2);
203
+ expect(clusters).toHaveLength(1);
204
+ expect(clusters[0].unconnected).toBe(true);
205
+ });
206
+
207
+ it('tolerates edges naming nodes that are not in the node set', () => {
208
+ const { nodes, edges } = twoCliques();
209
+ const { assignment } = clusterGraph(nodes, [...edges, link('a1', 'ghost')]);
210
+ expect(assignment.size).toBe(nodes.length);
211
+ });
212
+
213
+ it('resolves edges whose endpoints force-graph has already hydrated to objects', () => {
214
+ const { nodes, edges } = twoCliques();
215
+ const hydrated = edges.map((e) => ({ source: { id: e.source }, target: { id: e.target } }));
216
+ const { assignment } = clusterGraph(nodes, hydrated);
217
+ expect(assignment.get('a1')).not.toBe(assignment.get('b1'));
218
+ });
219
+ });
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Turning a `status` payload into what the dashboard says about itself.
3
+ *
4
+ * Pure on purpose: this is the "no soft failures" rule (DESIGN.md principle 1)
5
+ * expressed as data, and getting it wrong is the worst bug the dashboard can
6
+ * have — a dead store rendering as an empty memory. Keeping it out of the DOM
7
+ * code means it can be tested directly.
8
+ */
9
+
10
+ /**
11
+ * The one thing the user must act on right now, or null when nothing is wrong.
12
+ * Ordered by blast radius: an unreadable store beats a dead embedder beats a
13
+ * dead LLM, because each later failure is survivable while the earlier one is
14
+ * not. Only ever one banner — a stack of warnings is noise, not signal.
15
+ */
16
+ export function systemAlert(status = {}) {
17
+ const db = status.db || {};
18
+ const p = status.providers || {};
19
+
20
+ if (status.unavailable || db.healthy === false) {
21
+ if (db.schema === 'missing') {
22
+ return {
23
+ level: 'err',
24
+ title: 'Memory store has no schema.',
25
+ body: 'The database is reachable but Sigil’s tables don’t exist yet, so nothing can be stored or recalled.',
26
+ action: { label: 'Run migrations', route: 'setup' },
27
+ };
28
+ }
29
+ return {
30
+ level: 'err',
31
+ title: 'Memory store unreachable.',
32
+ body: db.error || 'Postgres did not answer. Stored facts are intact; nothing can be read or written until it is back.',
33
+ action: { label: 'Check database', route: 'setup' },
34
+ };
35
+ }
36
+
37
+ // Embedding before LLM: without vectors, new facts are written but never
38
+ // come back in search — silent data loss from the user's point of view.
39
+ if (p.embedding && p.embedding.ok === false) {
40
+ return {
41
+ level: 'warn',
42
+ title: 'Embedding provider is down.',
43
+ body: `${p.embedding.provider || 'No provider'} — ${condenseProviderError(p.embedding.error)}. New facts can’t be embedded, so they won’t come back in search.`,
44
+ action: { label: 'Change embedding', route: 'settings' },
45
+ };
46
+ }
47
+ if (p.llm && p.llm.ok === false) {
48
+ return {
49
+ level: 'warn',
50
+ title: 'LLM provider is down.',
51
+ body: `${p.llm.provider || 'No provider'} — ${condenseProviderError(p.llm.error)}. Fact extraction and query routing fall back to the simple path.`,
52
+ action: { label: 'Change LLM', route: 'settings' },
53
+ };
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * Reduce a provider error to one readable line.
60
+ *
61
+ * CLI providers hand back their whole transcript on failure — claude-cli's is a
62
+ * ~700-character JSON object (is_error, usage, cache_creation, modelUsage…),
63
+ * and interpolating it raw turned the health banner into eight lines of machine
64
+ * output with the actual cause, "claude CLI exited 1", buried at the front. The
65
+ * useful part is always the prose before the payload starts.
66
+ */
67
+ export function condenseProviderError(err) {
68
+ const raw = String(err ?? '').trim();
69
+ if (!raw) return 'unavailable';
70
+ // Cut at the first JSON/array payload; that boundary is where prose ends.
71
+ const cut = raw.search(/[{[]/);
72
+ let msg = (cut > 0 ? raw.slice(0, cut) : raw).trim().replace(/[:\s-]+$/, '');
73
+ // A message that IS the payload (no prose at all) still beats showing nothing.
74
+ if (!msg) msg = raw;
75
+ return msg.length > 160 ? `${msg.slice(0, 157)}…` : msg;
76
+ }
77
+
78
+ /** One cell of the Home system readout: `{ s: state, v: value, sub?: detail }`. */
79
+ export function systemCells(status = {}) {
80
+ const db = status.db || {};
81
+ const p = status.providers || {};
82
+ const q = status.writeQueue;
83
+ return [
84
+ { k: 'Store', ...(status.unavailable || db.healthy === false
85
+ ? { s: 'err', v: db.schema === 'missing' ? 'no schema' : 'unreachable' }
86
+ : { s: 'ok', v: 'connected' }) },
87
+ { k: 'Embedding', ...providerCell(p.embedding) },
88
+ { k: 'LLM', ...providerCell(p.llm) },
89
+ // A non-zero depth is the honest answer to "why is my save slow?"
90
+ { k: 'Write queue', ...(q == null ? { s: '', v: '—' }
91
+ : q === 0 ? { s: 'ok', v: 'idle' }
92
+ : { s: 'warn', v: `${q} waiting`, sub: 'a write is in flight' }) },
93
+ ];
94
+ }
95
+
96
+ /**
97
+ * Why the managed-session engine cannot be turned on from here, or null if it
98
+ * can. Same "no soft failures" rule applied to a control: this feature already
99
+ * spent a whole release flagged `enabled` while every worker died on boot, so a
100
+ * button that writes a flag the host cannot honour is worse than no button.
101
+ * Takes an `engine.status` payload.
102
+ */
103
+ export function engineBlocker(s = {}) {
104
+ if (!s.tmuxAvailable) return 'tmux was not found on PATH — warm workers need it.';
105
+ if (s.provider && s.provider !== 'claude-cli') {
106
+ return `LLM provider is "${s.provider}" — warm workers only apply to claude-cli.`;
107
+ }
108
+ return null;
109
+ }
110
+
111
+ function providerCell(h) {
112
+ if (!h) return { s: '', v: 'not probed', sub: 'daemon still starting' };
113
+ if (h.ok) return { s: 'ok', v: h.provider, sub: h.model || undefined };
114
+ // Same condensing as the banner: this sub-line is one row of a stat strip, so
115
+ // a raw CLI transcript here renders as a wall of truncated JSON.
116
+ return { s: 'err', v: h.provider ? `${h.provider} failing` : 'not configured', sub: h.error ? condenseProviderError(h.error) : undefined };
117
+ }