hive-swarm 2.0.0 → 2.1.1

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/hive-graph.js CHANGED
@@ -1,466 +1,1039 @@
1
1
  (() => {
2
2
  'use strict';
3
3
 
4
+ const SQRT3 = Math.sqrt(3);
5
+ const STOP_WORDS = new Set([
6
+ 'for', 'in', 'on', 'to', 'with', 'of', 'by', 'at', 'from', 'into', 'onto',
7
+ 'about', 'as', 'and', 'or', 'the', 'a', 'an', 'via', 'per', 'within',
8
+ ]);
9
+
4
10
  function isPost(event) {
5
11
  return event.kind === 'brief' || event.kind === 'message' ||
6
12
  (!event.kind && event.author !== 'system');
7
13
  }
8
14
 
9
- function elapsedSpan(posts,{live=false,now=Date.now()}={}) {
10
- const times=posts.map(post=>Date.parse(post.time)).filter(Number.isFinite);
15
+ function elapsedSpan(posts, { live = false, now = Date.now() } = {}) {
16
+ const times = posts.map(post => Date.parse(post.time)).filter(Number.isFinite);
11
17
  if (!times.length) return '<1m';
12
- const minutes=Math.max(0,Math.floor(((live?now:times.at(-1))-times[0])/60000));
18
+ const minutes = Math.max(0, Math.floor(((live ? now : times.at(-1)) - times[0]) / 60000));
13
19
  if (!minutes) return '<1m';
14
- if (minutes<60) return minutes+'m';
15
- return Math.floor(minutes/60)+'h'+(minutes%60?' '+minutes%60+'m':'');
20
+ if (minutes < 60) return minutes + 'm';
21
+ return Math.floor(minutes / 60) + 'h' + (minutes % 60 ? ' ' + (minutes % 60) + 'm' : '');
22
+ }
23
+
24
+ function unmentionedNode(node) {
25
+ return Boolean(node.unmentioned && !node.mentions && !node.broadcasts);
26
+ }
27
+
28
+ function smartTaskLabel(member) {
29
+ const isObj = member && typeof member === 'object';
30
+ const explicit = isObj ? String(member.taskLabel ?? '').trim() : '';
31
+ if (explicit) return explicit;
32
+
33
+ const raw = isObj ? String(member.brief ?? member.task ?? '') : String(member ?? '');
34
+ const fallbackName = isObj && member.name ? String(member.name).trim() : '';
35
+ if (!raw.trim()) return fallbackName || 'Swarm task';
36
+
37
+ // Strip fenced code blocks, markdown links, formatting symbols, and list prefixes.
38
+ let text = raw
39
+ .replace(/```[\s\S]*?```/g, ' ')
40
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
41
+ .replace(/[`*_~>#]/g, ' ')
42
+ .replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm, '');
43
+
44
+ const skipLine = /^(?:strict\s+file\s+ownership|do\s+not\s+touch|reference\s+screenshots|requirements?|first\s*\(|deliverables?)\b/i;
45
+ const lines = text
46
+ .split(/\r?\n+/)
47
+ .map(line => line.trim())
48
+ .filter(line => line && !skipLine.test(line));
49
+
50
+ let cleaned = (lines.slice(0, 8).join(' ') || text).replace(/\s+/g, ' ').trim();
51
+
52
+ const leadingPatterns = [
53
+ /^you\s+have\s+just\s+started[.:!]*\s*/i,
54
+ /^your\s+assignment(?:\s*\([^)]*\))?[:.\s-]*/i,
55
+ /^you\s+are(?:\s+(?:a|an|the))?\s+(?:hive\s+swarm\s+)?(?:member|agent|worker|owner)(?:\s+['"]?@?[a-z0-9_-]+['"]?)?(?:\s+(?:for|on|in)\s+hive\s+swarm(?:\s+\d+(?:\.\d+)*)?)?[.,:;\s-]*/i,
56
+ /^as(?:\s+(?:a|an|the))?\s+[a-z0-9 _-]+,\s*/i,
57
+ /^(?:your\s+)?(?:task|goal|role|mission|assignment)\s*(?:is\s+to|is|:)\s*/i,
58
+ /^you\s+(?:own|will\s+own|are\s+responsible\s+for|need\s+to|should|must)\s+(?:the\s+)?/i,
59
+ /^please\s+/i,
60
+ /^for\s+hive\s+swarm(?:\s+\d+(?:\.\d+)*)?[.,:;\s-]*/i,
61
+ ];
62
+ for (let pass = 0; pass < 3; pass++) {
63
+ let changed = false;
64
+ for (const pattern of leadingPatterns) {
65
+ const next = cleaned.replace(pattern, '').trim();
66
+ if (next !== cleaned) {
67
+ cleaned = next;
68
+ changed = true;
69
+ }
70
+ }
71
+ if (!changed) break;
72
+ }
73
+
74
+ cleaned = cleaned
75
+ .replace(/\s+(?:in|on)\s+(?:your|the)\s+(?:shared\s+)?worktree.*$/i, '')
76
+ .replace(/\s+for\s+hive\s+swarm(?:\s+\d+(?:\.\d+)*)?\.?$/i, '')
77
+ .replace(/\s+/g, ' ')
78
+ .trim();
79
+
80
+ if (cleaned.length > 64) {
81
+ const sentenceMatch = /^(.{18,64}?)[.!?](?:\s|$)/.exec(cleaned);
82
+ if (sentenceMatch) cleaned = sentenceMatch[1];
83
+ }
84
+
85
+ // Remove trailing unmatched open parentheses if sliced mid-phrase.
86
+ let words = cleaned.replace(/[.,:;!?-]+$/g, '').split(/\s+/).filter(Boolean);
87
+ if (words.length > 10) words = words.slice(0, 10);
88
+
89
+ let result = words.join(' ');
90
+ while (result.length > 64 && words.length > 1) {
91
+ words.pop();
92
+ result = words.join(' ');
93
+ }
94
+
95
+ // Drop dangling unclosed parenthesis chunk if needed.
96
+ const openIdx = result.lastIndexOf('(');
97
+ const closeIdx = result.lastIndexOf(')');
98
+ if (openIdx !== -1 && openIdx > closeIdx) {
99
+ const beforeParen = result.slice(0, openIdx).replace(/[,:;-\s]+$/, '').trim();
100
+ if (beforeParen.split(/\s+/).length >= 2) {
101
+ result = beforeParen;
102
+ words = result.split(/\s+/).filter(Boolean);
103
+ } else {
104
+ result = result.replace(/\(/g, '');
105
+ words = result.split(/\s+/).filter(Boolean);
106
+ }
107
+ }
108
+
109
+ while (words.length > 2 && STOP_WORDS.has(words.at(-1).replace(/[,:;!?-]+$/g, '').toLowerCase())) {
110
+ words.pop();
111
+ }
112
+
113
+ result = words.join(' ').replace(/[,:;!?-]+$/g, '').trim();
114
+ if (result.length > 64) {
115
+ result = result.slice(0, 64).replace(/\s+\S*$/, '').replace(/[,:;!?-]+$/g, '').trim();
116
+ }
117
+ if (!result) return fallbackName || 'Swarm task';
118
+ return result[0].toUpperCase() + result.slice(1);
16
119
  }
17
120
 
18
- function unmentionedNode(node) {return Boolean(node.unmentioned&&!node.mentions&&!node.broadcasts);}
121
+ function shouldMergeUserToCoordinator(members) {
122
+ const list = members ?? [];
123
+ const hasDedicatedCoordinator = list.some(m => (m.role === 'coordinator' || m.name === 'coordinator') && !m.external);
124
+ const hasExplicitUserMember = list.some(m => m.name === 'user');
125
+ return !hasDedicatedCoordinator && !hasExplicitUserMember;
126
+ }
19
127
 
20
- function project(posts, members, cursor, {hideInactive=false,expandBroadcast=false}={}) {
21
- const names = new Map([['coordinator',{name:'coordinator',role:'coordinator',status:'waiting'}]]);
22
- for (const member of members) names.set(member.name,member);
128
+ function project(posts, members, cursor, { hideInactive = false, expandBroadcast = false } = {}) {
129
+ const mergeUser = shouldMergeUserToCoordinator(members);
130
+ const resolveActor = name => (mergeUser && name === 'user') ? 'coordinator' : name;
131
+ const names = new Map([['coordinator', { name: 'coordinator', role: 'coordinator', status: 'waiting' }]]);
132
+ for (const member of members) names.set(member.name, member);
23
133
  const seen = new Set();
24
134
  const counts = new Map();
25
135
  const links = new Map();
26
136
  let broadcasts = 0;
27
137
  function addName(name) {
28
- if (!names.has(name)) names.set(name,{name,status:'observer'});
138
+ if (!names.has(name)) names.set(name, { name, status: 'observer' });
29
139
  seen.add(name);
30
140
  }
31
141
  for (const event of posts) {
32
142
  if (event.seq > cursor || !isPost(event)) continue;
33
- const {author} = event;
34
- const targets=[...new Set([...(event.targets??[]),...(event.coordinatorMention?['coordinator']:[])])];
143
+ const author = resolveActor(event.author);
144
+ const targets = [...new Set([...(event.targets ?? []).map(resolveActor), ...(event.coordinatorMention ? ['coordinator'] : [])])];
35
145
  addName(author);
36
- const outgoing = counts.get(author) ?? {posts:0,mentions:0,broadcasts:0,unmentioned:0,lastSeq:0};
146
+ const outgoing = counts.get(author) ?? { posts: 0, mentions: 0, broadcasts: 0, unmentioned: 0, lastSeq: 0 };
37
147
  outgoing.posts++;
38
- outgoing.lastSeq=event.seq;
39
- counts.set(author,outgoing);
148
+ outgoing.lastSeq = event.seq;
149
+ counts.set(author, outgoing);
40
150
  const all = event.broadcast ?? /(?:^|[^a-z0-9_])@all(?![a-z0-9_-])/i.test(event.text ?? '');
41
151
  if (all) {
42
152
  outgoing.broadcasts++;
43
153
  broadcasts++;
44
154
  }
45
- if (!all&&!event.coordinatorMention&&!targets.some(to=>to!==author)) outgoing.unmentioned++;
155
+ if (!all && !targets.some(to => to !== author)) outgoing.unmentioned++;
46
156
  for (const to of new Set(targets)) {
47
157
  if (to === author) continue;
48
158
  addName(to);
49
159
  if (all && !expandBroadcast) continue;
50
- const key=author+'>'+to;
51
- const link=links.get(key) ?? {from:author,to,count:0,direct:0,broadcast:0,lastSeq:0};
160
+ const key = author + '>' + to;
161
+ const link = links.get(key) ?? { from: author, to, count: 0, direct: 0, broadcast: 0, lastSeq: 0 };
52
162
  link.count++;
53
163
  if (all) link.broadcast++; else link.direct++;
54
- link.lastSeq=event.seq;
164
+ link.lastSeq = event.seq;
55
165
  outgoing.mentions++;
56
- links.set(key,link);
166
+ links.set(key, link);
57
167
  }
58
168
  }
59
169
  return {
60
- nodes:[...names.values()].filter(node => !hideInactive || seen.has(node.name))
61
- .map(node => ({...node,...counts.get(node.name)})),
62
- links:[...links.values()],broadcasts,
170
+ nodes: [...names.values()].filter(node => !hideInactive || seen.has(node.name))
171
+ .map(node => ({ ...node, ...counts.get(node.name) })),
172
+ links: [...links.values()],
173
+ broadcasts,
63
174
  };
64
175
  }
65
176
 
66
- function gridLayout(count,width) {return count>6||(count>3&&width<440);}
67
- function columns(width) {return Math.max(1,Math.floor(width/120));}
68
- function minimumHeight(count,width) {
69
- if (gridLayout(count,width)) {
70
- const rows=Math.ceil(count/columns(width));
71
- return Math.max(340,rows*124+44);
177
+ function gridLayout(count, width) { return count > 6 || (count > 3 && width < 440); }
178
+ function columns(width) { return Math.max(1, Math.floor(width / 120)); }
179
+ function minimumHeight(count, width) {
180
+ if (gridLayout(count, width)) {
181
+ const rows = Math.ceil(count / columns(width));
182
+ return Math.max(340, rows * 124 + 44);
72
183
  }
73
- if (count>=6) return 470;
74
- if (count===5) return 450;
75
- if (count===4) return 400;
184
+ if (count >= 6) return 470;
185
+ if (count === 5) return 450;
186
+ if (count === 4) return 400;
76
187
  return 0;
77
188
  }
78
189
 
79
- function layout(nodes,width,height) {
80
- const result=new Map();
190
+ function layout(nodes, width, height) {
191
+ const result = new Map();
81
192
  if (!nodes.length) return result;
82
- if (gridLayout(nodes.length,width)) {
83
- const count=columns(width);
84
- const rows=Math.ceil(nodes.length/count);
85
- const columnWidth=width/count;
86
- const topPad=56;
87
- const bottomPad=66;
88
- const usable=Math.max(0,height-topPad-bottomPad);
89
- nodes.forEach((node,index) => {
90
- const row=Math.floor(index/count);
91
- const inRow=Math.min(count,nodes.length-row*count);
92
- const y=rows===1?Math.max(topPad,Math.min(height-bottomPad,height/2-8)):topPad+(row/(rows-1))*usable;
93
- result.set(node.name,{x:columnWidth*(index%count+0.5+(count-inRow)/2),y});
193
+ if (gridLayout(nodes.length, width)) {
194
+ const count = columns(width);
195
+ const rows = Math.ceil(nodes.length / count);
196
+ const columnWidth = width / count;
197
+ const topPad = 56;
198
+ const bottomPad = 66;
199
+ const usable = Math.max(0, height - topPad - bottomPad);
200
+ nodes.forEach((node, index) => {
201
+ const row = Math.floor(index / count);
202
+ const inRow = Math.min(count, nodes.length - row * count);
203
+ const y = rows === 1 ? Math.max(topPad, Math.min(height - bottomPad, height / 2 - 8)) : topPad + (row / (rows - 1)) * usable;
204
+ result.set(node.name, { x: columnWidth * (index % count + 0.5 + (count - inRow) / 2), y });
94
205
  });
95
206
  return result;
96
207
  }
97
- const center=nodes.find(node=>node.role==='coordinator') ?? nodes[0];
208
+ const center = nodes.find(node => node.role === 'coordinator') ?? nodes[0];
98
209
  if (!center) return result;
99
- const outer=nodes.filter(node=>node!==center);
100
- const topPad=56;
101
- const bottomPad=66;
102
- const centerY=(topPad+(height-bottomPad))/2;
103
- const radiusY=Math.max(48,(height-topPad-bottomPad)/2);
104
- const sidePad=Math.min(68,Math.max(54,width*0.1));
105
- const radiusX=Math.max(44,Math.min(width*0.4,width/2-sidePad));
210
+ const outer = nodes.filter(node => node !== center);
211
+ const topPad = 56;
212
+ const bottomPad = 66;
213
+ const centerY = (topPad + (height - bottomPad)) / 2;
214
+ const radiusY = Math.max(48, (height - topPad - bottomPad) / 2);
215
+ const sidePad = Math.min(68, Math.max(54, width * 0.1));
216
+ const radiusX = Math.max(44, Math.min(width * 0.4, width / 2 - sidePad));
106
217
  if (!outer.length) {
107
- result.set(center.name,{x:width/2,y:centerY});
218
+ result.set(center.name, { x: width / 2, y: centerY });
108
219
  return result;
109
220
  }
110
- if (outer.length===1) {
111
- const spread=Math.max(54,Math.min(radiusX*0.72,width/2-sidePad));
112
- result.set(center.name,{x:width/2-spread,y:centerY});
113
- result.set(outer[0].name,{x:width/2+spread,y:centerY});
221
+ if (outer.length === 1) {
222
+ const spread = Math.max(54, Math.min(radiusX * 0.72, width / 2 - sidePad));
223
+ result.set(center.name, { x: width / 2 - spread, y: centerY });
224
+ result.set(outer[0].name, { x: width / 2 + spread, y: centerY });
114
225
  return result;
115
226
  }
116
- if (outer.length===2) {
117
- const topY=Math.max(topPad,centerY-radiusY*0.78);
118
- const bottomY=Math.min(height-bottomPad,centerY+radiusY*0.72);
119
- const spread=Math.max(54,Math.min(radiusX*0.85,width/2-sidePad));
120
- result.set(center.name,{x:width/2,y:topY});
121
- result.set(outer[0].name,{x:width/2-spread,y:bottomY});
122
- result.set(outer[1].name,{x:width/2+spread,y:bottomY});
227
+ if (outer.length === 2) {
228
+ const topY = Math.max(topPad, centerY - radiusY * 0.78);
229
+ const bottomY = Math.min(height - bottomPad, centerY + radiusY * 0.72);
230
+ const spread = Math.max(54, Math.min(radiusX * 0.85, width / 2 - sidePad));
231
+ result.set(center.name, { x: width / 2, y: topY });
232
+ result.set(outer[0].name, { x: width / 2 - spread, y: bottomY });
233
+ result.set(outer[1].name, { x: width / 2 + spread, y: bottomY });
123
234
  return result;
124
235
  }
125
- result.set(center.name,{x:width/2,y:centerY});
126
- outer.forEach((node,index)=>{
127
- const angle=-Math.PI/2+index*Math.PI*2/outer.length;
128
- result.set(node.name,{x:width/2+Math.cos(angle)*radiusX,y:centerY+Math.sin(angle)*radiusY});
236
+ result.set(center.name, { x: width / 2, y: centerY });
237
+ outer.forEach((node, index) => {
238
+ const angle = -Math.PI / 2 + index * Math.PI * 2 / outer.length;
239
+ result.set(node.name, { x: width / 2 + Math.cos(angle) * radiusX, y: centerY + Math.sin(angle) * radiusY });
129
240
  });
130
241
  return result;
131
242
  }
132
243
 
133
- function estimateNameLines(name,charsPerLine) {
134
- const text=String(name??'').trim();
244
+ function mentionsGridLayout(count, width) {
245
+ return count > 12 || (count > 5 && width < 380) || (count > 8 && width < 465);
246
+ }
247
+
248
+ function mentionsMinimumHeight(count, width) {
249
+ if (mentionsGridLayout(count, width)) {
250
+ const cols = Math.max(1, Math.floor(Math.max(width - 24, 140) / 145));
251
+ const rows = Math.ceil(count / cols);
252
+ return Math.max(360, rows * 68 + 80);
253
+ }
254
+ if (count >= 11) return 680;
255
+ if (count >= 9) return 560;
256
+ if (count >= 7) return 470;
257
+ if (count >= 5) return 400;
258
+ return 360;
259
+ }
260
+
261
+ function layoutMentions(nodes, width, height) {
262
+ const result = new Map();
263
+ if (!nodes?.length) return result;
264
+ const narrow = width < 465;
265
+ const ordered = [];
266
+ const coord = nodes.find(node => node.role === 'coordinator' || node.name === 'coordinator');
267
+ if (coord) ordered.push(coord);
268
+ for (const node of nodes) if (node !== coord) ordered.push(node);
269
+
270
+ if (mentionsGridLayout(ordered.length, width)) {
271
+ const maxPillW = Math.max(...ordered.map(n => nodeBox(n, { variant: 'pill', narrow }).halfW * 2), 116);
272
+ const cols = Math.max(1, Math.floor((width - 24) / (maxPillW + 14)));
273
+ const rows = Math.ceil(ordered.length / cols);
274
+ const colW = width / cols;
275
+ const topPad = 42;
276
+ const bottomPad = 46;
277
+ const usableH = Math.max(40, height - topPad - bottomPad);
278
+ ordered.forEach((node, index) => {
279
+ const row = Math.floor(index / cols);
280
+ const inRow = Math.min(cols, ordered.length - row * cols);
281
+ const y = rows === 1 ? height / 2 : topPad + (row / (rows - 1)) * usableH;
282
+ const x = colW * ((index % cols) + 0.5 + (cols - inRow) / 2);
283
+ result.set(node.name, { x, y });
284
+ });
285
+ return result;
286
+ }
287
+
288
+ if (ordered.length === 1) {
289
+ result.set(ordered[0].name, { x: width / 2, y: height / 2 });
290
+ return result;
291
+ }
292
+
293
+ const maxHalfW = Math.max(...ordered.map(n => nodeBox(n, { variant: 'pill', narrow }).halfW), 56);
294
+ const maxHalfH = Math.max(...ordered.map(n => nodeBox(n, { variant: 'pill', narrow }).halfH), 17);
295
+ const topPad = maxHalfH + 18;
296
+ const bottomPad = maxHalfH + 22;
297
+ const sidePad = Math.min(width * 0.28, maxHalfW + 18);
298
+ const centerX = width / 2;
299
+ const centerY = (topPad + (height - bottomPad)) / 2;
300
+ const radiusX = Math.max(48, Math.min(width * 0.42, width / 2 - sidePad));
301
+ const radiusY = Math.max(44, (height - topPad - bottomPad) / 2);
302
+
303
+ ordered.forEach((node, index) => {
304
+ const angle = -Math.PI / 2 + (index * Math.PI * 2) / ordered.length;
305
+ result.set(node.name, {
306
+ x: centerX + Math.cos(angle) * radiusX,
307
+ y: centerY + Math.sin(angle) * radiusY,
308
+ });
309
+ });
310
+ return result;
311
+ }
312
+
313
+ function estimateNameLines(name, charsPerLine) {
314
+ const text = String(name ?? '').trim();
135
315
  if (!text) return 1;
136
- const limit=Math.max(6,charsPerLine);
137
- const tokens=text.match(/[^-\s_/]+[-\s_/]*|[-\s_/]+/g) ?? [text];
138
- let lines=1,used=0;
316
+ const limit = Math.max(6, charsPerLine);
317
+ const tokens = text.match(/[^-\s_/]+[-\s_/]*|[-\s_/]+/g) ?? [text];
318
+ let lines = 1, used = 0;
139
319
  for (const token of tokens) {
140
- let remaining=token;
141
- while (remaining.length>limit) {
142
- if (used>0) {lines++;used=0;}
143
- remaining=remaining.slice(limit);
320
+ let remaining = token;
321
+ while (remaining.length > limit) {
322
+ if (used > 0) { lines++; used = 0; }
323
+ remaining = remaining.slice(limit);
144
324
  lines++;
145
325
  }
146
- if (used>0 && used+remaining.length>limit) {
326
+ if (used > 0 && used + remaining.length > limit) {
147
327
  lines++;
148
- used=remaining.length;
149
- } else used+=remaining.length;
150
- }
151
- return Math.max(1,lines);
152
- }
153
-
154
- function nodeBox(node,{variant='card',cardWidth,narrow=false}={}) {
155
- if (variant==='hex') {
156
- const maxLabelW=narrow?84:128;
157
- const raw=String(node?.name??'');
158
- const labelText=raw==='user'?'You':raw==='system'?'System':'@'+raw;
159
- const charsPerLine=Math.max(8,Math.floor((maxLabelW-12)/6.3));
160
- const lines=estimateNameLines(labelText,charsPerLine);
161
- const labelW=Math.min(maxLabelW,Math.max(38,12+labelText.length*6.3));
162
- const unmentioned=unmentionedNode(node??{});
163
- const halfW=Math.max(unmentioned?32:28,labelW/2);
164
- const top=unmentioned?32:(node?.broadcasts?29:24);
165
- const bottom=29+lines*15+4;
166
- return {halfW,halfH:(top+bottom)/2,offsetX:0,offsetY:(bottom-top)/2,radius:10};
167
- }
168
- const width=cardWidth??(narrow?92:112);
169
- const charsPerLine=Math.max(7,Math.floor((width-20)/7.4));
170
- const lines=estimateNameLines(node?.name??'',charsPerLine);
171
- const height=64+lines*16;
172
- return {halfW:width/2,halfH:height/2,offsetX:0,offsetY:0,radius:10};
173
- }
174
-
175
- function normalizeBox(point,box) {
176
- if (!box) return {cx:point.x,cy:point.y,halfW:26,halfH:26,radius:10};
177
- if (Number.isFinite(box.left)&&Number.isFinite(box.right)&&Number.isFinite(box.top)&&Number.isFinite(box.bottom)) {
328
+ used = remaining.length;
329
+ } else used += remaining.length;
330
+ }
331
+ return Math.max(1, lines);
332
+ }
333
+
334
+ function nodeBox(node, { variant = 'card', cardWidth, narrow = false } = {}) {
335
+ if (variant === 'pill') {
336
+ const raw = String(node?.name ?? '');
337
+ const labelText = raw === 'user' ? 'You' : raw === 'system' ? 'System' : raw;
338
+ const halfH = narrow ? 16 : 18;
339
+ const maxW = narrow ? 156 : 210;
340
+ const minW = narrow ? 88 : 104;
341
+ const charW = narrow ? 6.4 : 7.2;
342
+ const beeAndDot = narrow ? 38 : 46;
343
+ const width = Math.min(maxW, Math.max(minW, beeAndDot + labelText.length * charW));
344
+ return { halfW: width / 2, halfH, offsetX: 0, offsetY: 0, radius: halfH };
345
+ }
346
+ if (variant === 'hex') {
347
+ const maxLabelW = narrow ? 84 : 128;
348
+ const raw = String(node?.name ?? '');
349
+ const labelText = raw === 'user' ? 'You' : raw === 'system' ? 'System' : '@' + raw;
350
+ const charsPerLine = Math.max(8, Math.floor((maxLabelW - 12) / 6.3));
351
+ const lines = estimateNameLines(labelText, charsPerLine);
352
+ const labelW = Math.min(maxLabelW, Math.max(38, 12 + labelText.length * 6.3));
353
+ const unmentioned = unmentionedNode(node ?? {});
354
+ const halfW = Math.max(unmentioned ? 32 : 28, labelW / 2);
355
+ const top = unmentioned ? 32 : (node?.broadcasts ? 29 : 24);
356
+ const bottom = 29 + lines * 15 + 4;
357
+ return { halfW, halfH: (top + bottom) / 2, offsetX: 0, offsetY: (bottom - top) / 2, radius: 10 };
358
+ }
359
+ const width = cardWidth ?? (narrow ? 92 : 112);
360
+ const charsPerLine = Math.max(7, Math.floor((width - 20) / 7.4));
361
+ const lines = estimateNameLines(node?.name ?? '', charsPerLine);
362
+ const height = 64 + lines * 16;
363
+ return { halfW: width / 2, halfH: height / 2, offsetX: 0, offsetY: 0, radius: 10 };
364
+ }
365
+
366
+ function normalizeBox(point, box) {
367
+ if (!box) return { cx: point.x, cy: point.y, halfW: 26, halfH: 26, radius: 10 };
368
+ if (Number.isFinite(box.left) && Number.isFinite(box.right) && Number.isFinite(box.top) && Number.isFinite(box.bottom)) {
178
369
  return {
179
- cx:point.x+(box.right-box.left)/2,
180
- cy:point.y+(box.bottom-box.top)/2,
181
- halfW:(box.left+box.right)/2,
182
- halfH:(box.top+box.bottom)/2,
183
- radius:Math.max(0,box.radius??8),
370
+ cx: point.x + (box.right - box.left) / 2,
371
+ cy: point.y + (box.bottom - box.top) / 2,
372
+ halfW: (box.left + box.right) / 2,
373
+ halfH: (box.top + box.bottom) / 2,
374
+ radius: Math.max(0, box.radius ?? 8),
184
375
  };
185
376
  }
186
- const halfW=Number.isFinite(box.halfW)?box.halfW:(Number.isFinite(box.width)?box.width/2:26);
187
- const halfH=Number.isFinite(box.halfH)?box.halfH:(Number.isFinite(box.height)?box.height/2:26);
377
+ const halfW = Number.isFinite(box.halfW) ? box.halfW : (Number.isFinite(box.width) ? box.width / 2 : 26);
378
+ const halfH = Number.isFinite(box.halfH) ? box.halfH : (Number.isFinite(box.height) ? box.height / 2 : 26);
188
379
  return {
189
- cx:(Number.isFinite(box.cx)?box.cx:point.x+(box.offsetX??0)),
190
- cy:(Number.isFinite(box.cy)?box.cy:point.y+(box.offsetY??0)),
191
- halfW:Math.max(1,halfW),
192
- halfH:Math.max(1,halfH),
193
- radius:Math.max(0,box.radius??8),
380
+ cx: (Number.isFinite(box.cx) ? box.cx : point.x + (box.offsetX ?? 0)),
381
+ cy: (Number.isFinite(box.cy) ? box.cy : point.y + (box.offsetY ?? 0)),
382
+ halfW: Math.max(1, halfW),
383
+ halfH: Math.max(1, halfH),
384
+ radius: Math.max(0, box.radius ?? 8),
194
385
  };
195
386
  }
196
387
 
197
- function roundedRectSignedDistance(px,py,box) {
198
- const r=Math.max(0,Math.min(box.radius??0,box.halfW,box.halfH));
199
- const qx=Math.abs(px-box.cx)-(box.halfW-r);
200
- const qy=Math.abs(py-box.cy)-(box.halfH-r);
201
- return Math.hypot(Math.max(qx,0),Math.max(qy,0))+Math.min(Math.max(qx,qy),0)-r;
388
+ function roundedRectSignedDistance(px, py, box) {
389
+ const r = Math.max(0, Math.min(box.radius ?? 0, box.halfW, box.halfH));
390
+ const qx = Math.abs(px - box.cx) - (box.halfW - r);
391
+ const qy = Math.abs(py - box.cy) - (box.halfH - r);
392
+ return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;
202
393
  }
203
394
 
204
- function bezierPoint(p0,c,p1,t) {
205
- const u=1-t;
395
+ function bezierPoint(p0, c, p1, t) {
396
+ const u = 1 - t;
206
397
  return {
207
- x:u*u*p0.x+2*u*t*c.x+t*t*p1.x,
208
- y:u*u*p0.y+2*u*t*c.y+t*t*p1.y,
398
+ x: u * u * p0.x + 2 * u * t * c.x + t * t * p1.x,
399
+ y: u * u * p0.y + 2 * u * t * c.y + t * t * p1.y,
209
400
  };
210
401
  }
211
402
 
212
- function blossomControl(p0,c,p1,u,v) {
213
- const a=(1-u)*(1-v);
214
- const b=(1-u)*v+u*(1-v);
215
- const d=u*v;
403
+ function blossomControl(p0, c, p1, u, v) {
404
+ const a = (1 - u) * (1 - v);
405
+ const b = (1 - u) * v + u * (1 - v);
406
+ const d = u * v;
216
407
  return {
217
- x:a*p0.x+b*c.x+d*p1.x,
218
- y:a*p0.y+b*c.y+d*p1.y,
408
+ x: a * p0.x + b * c.x + d * p1.x,
409
+ y: a * p0.y + b * c.y + d * p1.y,
219
410
  };
220
411
  }
221
412
 
222
- function clipQuadratic(p0,c,p1,absFrom,absTo,marginStart,marginEnd,minLength) {
223
- const steps=32;
224
- let lastInFrom=-1;
225
- for (let i=0;i<=steps;i++) {
226
- const pt=bezierPoint(p0,c,p1,i/steps);
227
- if (roundedRectSignedDistance(pt.x,pt.y,absFrom)<=marginStart) lastInFrom=i;
228
- }
229
- if (lastInFrom>=steps) return null;
230
- let tStart=0;
231
- if (lastInFrom>=0) {
232
- let lo=lastInFrom/steps,hi=(lastInFrom+1)/steps;
233
- for (let iter=0;iter<22;iter++) {
234
- const mid=(lo+hi)/2;
235
- const pt=bezierPoint(p0,c,p1,mid);
236
- if (roundedRectSignedDistance(pt.x,pt.y,absFrom)<=marginStart) lo=mid; else hi=mid;
413
+ function clipQuadratic(p0, c, p1, absFrom, absTo, marginStart, marginEnd, minLength) {
414
+ const steps = 32;
415
+ let lastInFrom = -1;
416
+ for (let i = 0; i <= steps; i++) {
417
+ const pt = bezierPoint(p0, c, p1, i / steps);
418
+ if (roundedRectSignedDistance(pt.x, pt.y, absFrom) <= marginStart) lastInFrom = i;
419
+ }
420
+ if (lastInFrom >= steps) return null;
421
+ let tStart = 0;
422
+ if (lastInFrom >= 0) {
423
+ let lo = lastInFrom / steps, hi = (lastInFrom + 1) / steps;
424
+ for (let iter = 0; iter < 22; iter++) {
425
+ const mid = (lo + hi) / 2;
426
+ const pt = bezierPoint(p0, c, p1, mid);
427
+ if (roundedRectSignedDistance(pt.x, pt.y, absFrom) <= marginStart) lo = mid; else hi = mid;
237
428
  }
238
- tStart=hi;
239
- }
240
- let firstInTo=-1;
241
- const scanFrom=Math.max(0,lastInFrom+1);
242
- for (let i=scanFrom;i<=steps;i++) {
243
- const pt=bezierPoint(p0,c,p1,i/steps);
244
- if (roundedRectSignedDistance(pt.x,pt.y,absTo)<=marginEnd) {firstInTo=i;break;}
245
- }
246
- if (firstInTo<=0) return null;
247
- let lo=(firstInTo-1)/steps,hi=firstInTo/steps;
248
- for (let iter=0;iter<22;iter++) {
249
- const mid=(lo+hi)/2;
250
- const pt=bezierPoint(p0,c,p1,mid);
251
- if (roundedRectSignedDistance(pt.x,pt.y,absTo)<=marginEnd) hi=mid; else lo=mid;
252
- }
253
- const tEnd=lo;
254
- if (tEnd<=tStart+1e-4) return null;
255
- const start=bezierPoint(p0,c,p1,tStart);
256
- const end=bezierPoint(p0,c,p1,tEnd);
257
- const length=Math.hypot(end.x-start.x,end.y-start.y);
258
- if (length<minLength) return null;
259
- const control=blossomControl(p0,c,p1,tStart,tEnd);
260
- const mid=bezierPoint(p0,c,p1,(tStart+tEnd)/2);
261
- const endDx=end.x-control.x,endDy=end.y-control.y;
262
- const startDx=control.x-start.x,startDy=control.y-start.y;
263
- const endAngle=Math.hypot(endDx,endDy)>1e-4?Math.atan2(endDy,endDx):Math.atan2(end.y-start.y,end.x-start.x);
264
- const startAngle=Math.hypot(startDx,startDy)>1e-4?Math.atan2(startDy,startDx):Math.atan2(end.y-start.y,end.x-start.x);
265
- const d='M'+start.x.toFixed(1)+' '+start.y.toFixed(1)+' Q'+control.x.toFixed(1)+' '+control.y.toFixed(1)+' '+end.x.toFixed(1)+' '+end.y.toFixed(1);
266
- return {start,control,end,mid,startAngle,endAngle,length,tStart,tEnd,d};
267
- }
268
-
269
- function curveClearance(clipped,obstacles) {
429
+ tStart = hi;
430
+ }
431
+ let firstInTo = -1;
432
+ const scanFrom = Math.max(0, lastInFrom + 1);
433
+ for (let i = scanFrom; i <= steps; i++) {
434
+ const pt = bezierPoint(p0, c, p1, i / steps);
435
+ if (roundedRectSignedDistance(pt.x, pt.y, absTo) <= marginEnd) { firstInTo = i; break; }
436
+ }
437
+ if (firstInTo <= 0) return null;
438
+ let lo = (firstInTo - 1) / steps, hi = firstInTo / steps;
439
+ for (let iter = 0; iter < 22; iter++) {
440
+ const mid = (lo + hi) / 2;
441
+ const pt = bezierPoint(p0, c, p1, mid);
442
+ if (roundedRectSignedDistance(pt.x, pt.y, absTo) <= marginEnd) hi = mid; else lo = mid;
443
+ }
444
+ const tEnd = lo;
445
+ if (tEnd <= tStart + 1e-4) return null;
446
+ const start = bezierPoint(p0, c, p1, tStart);
447
+ const end = bezierPoint(p0, c, p1, tEnd);
448
+ const length = Math.hypot(end.x - start.x, end.y - start.y);
449
+ if (length < minLength) return null;
450
+ const control = blossomControl(p0, c, p1, tStart, tEnd);
451
+ const mid = bezierPoint(p0, c, p1, (tStart + tEnd) / 2);
452
+ const endDx = end.x - control.x, endDy = end.y - control.y;
453
+ const startDx = control.x - start.x, startDy = control.y - start.y;
454
+ const endAngle = Math.hypot(endDx, endDy) > 1e-4 ? Math.atan2(endDy, endDx) : Math.atan2(end.y - start.y, end.x - start.x);
455
+ const startAngle = Math.hypot(startDx, startDy) > 1e-4 ? Math.atan2(startDy, startDx) : Math.atan2(end.y - start.y, end.x - start.x);
456
+ const d = 'M' + start.x.toFixed(1) + ' ' + start.y.toFixed(1) + ' Q' + control.x.toFixed(1) + ' ' + control.y.toFixed(1) + ' ' + end.x.toFixed(1) + ' ' + end.y.toFixed(1);
457
+ return { start, control, end, mid, startAngle, endAngle, length, tStart, tEnd, d };
458
+ }
459
+
460
+ function curveClearance(clipped, obstacles) {
270
461
  if (!obstacles.length) return Infinity;
271
- let minClear=Infinity;
272
- for (let i=0;i<=24;i++) {
273
- const pt=bezierPoint(clipped.start,clipped.control,clipped.end,i/24);
462
+ let minClear = Infinity;
463
+ for (let i = 0; i <= 24; i++) {
464
+ const pt = bezierPoint(clipped.start, clipped.control, clipped.end, i / 24);
274
465
  for (const box of obstacles) {
275
- const dist=roundedRectSignedDistance(pt.x,pt.y,box);
276
- if (dist<minClear) minClear=dist;
466
+ const dist = roundedRectSignedDistance(pt.x, pt.y, box);
467
+ if (dist < minClear) minClear = dist;
277
468
  }
278
469
  }
279
470
  for (const box of obstacles) {
280
- const midDist=roundedRectSignedDistance(clipped.mid.x,clipped.mid.y,box)-10;
281
- if (midDist<minClear) minClear=midDist;
471
+ const midDist = roundedRectSignedDistance(clipped.mid.x, clipped.mid.y, box) - 10;
472
+ if (midDist < minClear) minClear = midDist;
282
473
  }
283
474
  return minClear;
284
475
  }
285
476
 
286
- function clipEdge(from,to,fromBox,toBox,{
287
- marginStart=6,
288
- marginEnd=7,
289
- bidirectional=false,
477
+ function clipEdge(from, to, fromBox, toBox, {
478
+ marginStart = 6,
479
+ marginEnd = 7,
480
+ bidirectional = false,
290
481
  bend,
291
- obstacles=[],
292
- obstacleMargin=8,
293
- minLength=8,
294
- }={}) {
295
- if (!from||!to) return null;
296
- const absFrom=normalizeBox(from,fromBox);
297
- const absTo=normalizeBox(to,toBox);
298
- const p0={x:absFrom.cx,y:absFrom.cy};
299
- const p1={x:absTo.cx,y:absTo.cy};
300
- const dx=p1.x-p0.x,dy=p1.y-p0.y;
301
- const distance=Math.hypot(dx,dy);
302
- if (distance<1) return null;
303
- const ux=dx/distance,uy=dy/distance;
304
- const nx=-uy,ny=ux;
305
- const absObstacles=obstacles.map(item=>item?.box?normalizeBox(item,item.box):normalizeBox(item,item));
306
- const candidates=[];
482
+ obstacles = [],
483
+ obstacleMargin = 8,
484
+ minLength = 8,
485
+ } = {}) {
486
+ if (!from || !to) return null;
487
+ const absFrom = normalizeBox(from, fromBox);
488
+ const absTo = normalizeBox(to, toBox);
489
+ const p0 = { x: absFrom.cx, y: absFrom.cy };
490
+ const p1 = { x: absTo.cx, y: absTo.cy };
491
+ const dx = p1.x - p0.x, dy = p1.y - p0.y;
492
+ const distance = Math.hypot(dx, dy);
493
+ if (distance < 1) return null;
494
+ const ux = dx / distance, uy = dy / distance;
495
+ const nx = -uy, ny = ux;
496
+ const absObstacles = obstacles.map(item => item?.box ? normalizeBox(item, item.box) : normalizeBox(item, item));
497
+ const candidates = [];
307
498
  if (Number.isFinite(bend)) {
308
499
  candidates.push(bend);
309
500
  } else if (bidirectional) {
310
- const base=Math.min(34,Math.max(18,distance*0.145));
501
+ const base = Math.min(34, Math.max(18, distance * 0.145));
311
502
  candidates.push(
312
503
  base,
313
- Math.min(54,base*1.45),
314
- Math.max(10,base*0.55),
315
- Math.min(72,distance*0.3),
316
- Math.max(6,base*0.3)
504
+ Math.min(54, base * 1.45),
505
+ Math.max(10, base * 0.55),
506
+ Math.min(72, distance * 0.3),
507
+ Math.max(6, base * 0.3)
317
508
  );
318
509
  } else {
319
- const base=Math.min(20,Math.max(8,distance*0.065));
320
- const maxBend=Math.min(82,distance*0.34);
510
+ const base = Math.min(20, Math.max(8, distance * 0.065));
511
+ const maxBend = Math.min(82, distance * 0.34);
321
512
  candidates.push(
322
513
  base,
323
514
  -base,
324
515
  0,
325
- Math.min(maxBend,base*2),
326
- -Math.min(maxBend,base*2),
327
- Math.min(maxBend,base*3.2),
328
- -Math.min(maxBend,base*3.2),
516
+ Math.min(maxBend, base * 2),
517
+ -Math.min(maxBend, base * 2),
518
+ Math.min(maxBend, base * 3.2),
519
+ -Math.min(maxBend, base * 3.2),
329
520
  maxBend,
330
521
  -maxBend
331
522
  );
332
523
  }
333
524
 
334
- const attempt=(mStart,mEnd,minLen)=>{
335
- let best=null,bestClear=-Infinity;
525
+ const attempt = (mStart, mEnd, minLen) => {
526
+ let best = null, bestClear = -Infinity;
336
527
  for (const offset of candidates) {
337
- const c={x:(p0.x+p1.x)/2+nx*offset,y:(p0.y+p1.y)/2+ny*offset};
338
- const clipped=clipQuadratic(p0,c,p1,absFrom,absTo,mStart,mEnd,minLen);
528
+ const c = { x: (p0.x + p1.x) / 2 + nx * offset, y: (p0.y + p1.y) / 2 + ny * offset };
529
+ const clipped = clipQuadratic(p0, c, p1, absFrom, absTo, mStart, mEnd, minLen);
339
530
  if (!clipped) continue;
340
- const clear=curveClearance(clipped,absObstacles);
341
- const result={...clipped,bend:offset,clearance:clear};
342
- if (clear>=obstacleMargin) return result;
343
- if (clear>bestClear) {bestClear=clear;best=result;}
531
+ const clear = curveClearance(clipped, absObstacles);
532
+ const result = { ...clipped, bend: offset, clearance: clear };
533
+ if (clear >= obstacleMargin) return result;
534
+ if (clear > bestClear) { bestClear = clear; best = result; }
344
535
  }
345
536
  return best;
346
537
  };
347
538
 
348
- return attempt(marginStart,marginEnd,minLength) ??
349
- attempt(Math.min(marginStart,2),Math.min(marginEnd,3),Math.min(minLength,4));
539
+ return attempt(marginStart, marginEnd, minLength) ??
540
+ attempt(Math.min(marginStart, 2), Math.min(marginEnd, 3), Math.min(minLength, 4));
350
541
  }
351
542
 
352
- function routeEdges(projection,points,{
353
- variant='card',
543
+ function routeEdges(projection, points, {
544
+ variant = 'card',
354
545
  boxes,
355
546
  cardWidth,
356
- narrow=false,
357
- marginStart=6,
358
- marginEnd=7,
359
- obstacleMargin=8,
360
- minLength=8,
361
- }={}) {
362
- const nodeBoxes=new Map();
363
- for (const node of projection.nodes??[]) {
364
- const custom=boxes?.get?.(node.name);
365
- nodeBoxes.set(node.name,custom ?? nodeBox(node,{variant,cardWidth,narrow}));
366
- }
367
- const keys=new Set((projection.links??[]).map(link=>link.from+'>'+link.to));
368
- const byKey=new Map();
369
- const routed=[];
370
- const obstaclesFor=(fromName,toName)=>{
371
- const list=[];
372
- for (const node of projection.nodes??[]) {
373
- if (node.name===fromName||node.name===toName) continue;
374
- const pt=points.get(node.name);
547
+ narrow = false,
548
+ marginStart = 6,
549
+ marginEnd = 7,
550
+ obstacleMargin = 8,
551
+ minLength = 8,
552
+ } = {}) {
553
+ const nodeBoxes = new Map();
554
+ for (const node of projection.nodes ?? []) {
555
+ const custom = boxes?.get?.(node.name);
556
+ nodeBoxes.set(node.name, custom ?? nodeBox(node, { variant, cardWidth, narrow }));
557
+ }
558
+ const keys = new Set((projection.links ?? []).map(link => link.from + '>' + link.to));
559
+ const byKey = new Map();
560
+ const routed = [];
561
+ const obstaclesFor = (fromName, toName) => {
562
+ const list = [];
563
+ for (const node of projection.nodes ?? []) {
564
+ if (node.name === fromName || node.name === toName) continue;
565
+ const pt = points.get(node.name);
375
566
  if (!pt) continue;
376
- list.push({x:pt.x,y:pt.y,box:nodeBoxes.get(node.name)});
567
+ list.push({ x: pt.x, y: pt.y, box: nodeBoxes.get(node.name) });
377
568
  }
378
569
  return list;
379
570
  };
380
- for (const link of projection.links??[]) {
381
- const start=points.get(link.from),end=points.get(link.to);
382
- if (!start||!end) continue;
383
- const fromBox=nodeBoxes.get(link.from) ?? nodeBox({name:link.from},{variant,cardWidth,narrow});
384
- const toBox=nodeBoxes.get(link.to) ?? nodeBox({name:link.to},{variant,cardWidth,narrow});
385
- const obstacles=obstaclesFor(link.from,link.to);
386
- const bidirectional=keys.has(link.to+'>'+link.from);
387
- const edge=clipEdge(start,end,fromBox,toBox,{
388
- marginStart,marginEnd,bidirectional,obstacles,obstacleMargin,minLength,
571
+ for (const link of projection.links ?? []) {
572
+ const start = points.get(link.from), end = points.get(link.to);
573
+ if (!start || !end) continue;
574
+ const fromBox = nodeBoxes.get(link.from) ?? nodeBox({ name: link.from }, { variant, cardWidth, narrow });
575
+ const toBox = nodeBoxes.get(link.to) ?? nodeBox({ name: link.to }, { variant, cardWidth, narrow });
576
+ const obstacles = obstaclesFor(link.from, link.to);
577
+ const bidirectional = keys.has(link.to + '>' + link.from);
578
+ const edge = clipEdge(start, end, fromBox, toBox, {
579
+ marginStart, marginEnd, bidirectional, obstacles, obstacleMargin, minLength,
389
580
  });
390
581
  if (edge) {
391
- const entry={link,edge,bidirectional,fromBox,toBox,obstacles};
582
+ const entry = { link, edge, bidirectional, fromBox, toBox, obstacles };
392
583
  routed.push(entry);
393
- byKey.set(link.from+'>'+link.to,entry);
584
+ byKey.set(link.from + '>' + link.to, entry);
394
585
  }
395
586
  }
396
587
  for (const entry of routed) {
397
- if (!entry.bidirectional || entry.edge.clearance>=Math.min(obstacleMargin,16)) continue;
398
- const twin=byKey.get(entry.link.to+'>'+entry.link.from);
399
- if (!twin || twin.edge.clearance<Math.min(obstacleMargin,16)) continue;
400
- const aPt=points.get(entry.link.from),bPt=points.get(entry.link.to);
401
- for (const innerBend of [-18,-26,-36,-48]) {
402
- const altInner=clipEdge(aPt,bPt,entry.fromBox,entry.toBox,{
403
- marginStart,marginEnd,bidirectional:true,bend:innerBend,obstacles:entry.obstacles,obstacleMargin,minLength,
588
+ if (!entry.bidirectional || entry.edge.clearance >= Math.min(obstacleMargin, 16)) continue;
589
+ const twin = byKey.get(entry.link.to + '>' + entry.link.from);
590
+ if (!twin || twin.edge.clearance < Math.min(obstacleMargin, 16)) continue;
591
+ const aPt = points.get(entry.link.from), bPt = points.get(entry.link.to);
592
+ for (const innerBend of [-18, -26, -36, -48]) {
593
+ const altInner = clipEdge(aPt, bPt, entry.fromBox, entry.toBox, {
594
+ marginStart, marginEnd, bidirectional: true, bend: innerBend, obstacles: entry.obstacles, obstacleMargin, minLength,
404
595
  });
405
- if (!altInner || altInner.clearance<10) continue;
406
- const outerBend=Math.max(twin.edge.bend,Math.abs(innerBend)+28);
407
- const altOuter=clipEdge(bPt,aPt,twin.fromBox,twin.toBox,{
408
- marginStart,marginEnd,bidirectional:true,bend:outerBend,obstacles:twin.obstacles,obstacleMargin,minLength,
596
+ if (!altInner || altInner.clearance < 10) continue;
597
+ const outerBend = Math.max(twin.edge.bend, Math.abs(innerBend) + 28);
598
+ const altOuter = clipEdge(bPt, aPt, twin.fromBox, twin.toBox, {
599
+ marginStart, marginEnd, bidirectional: true, bend: outerBend, obstacles: twin.obstacles, obstacleMargin, minLength,
409
600
  });
410
- if (altOuter && altOuter.clearance>=10 && Math.hypot(altInner.mid.x-altOuter.mid.x,altInner.mid.y-altOuter.mid.y)>=12) {
411
- entry.edge=altInner;
412
- twin.edge=altOuter;
601
+ if (altOuter && altOuter.clearance >= 10 && Math.hypot(altInner.mid.x - altOuter.mid.x, altInner.mid.y - altOuter.mid.y) >= 12) {
602
+ entry.edge = altInner;
603
+ twin.edge = altOuter;
413
604
  break;
414
605
  }
415
606
  }
416
607
  }
417
- const placedPills=[];
418
- const pillClear=(pt,obstacles,minObs)=> {
608
+ const placedPills = [];
609
+ const pillClear = (pt, obstacles, minObs) => {
419
610
  for (const item of obstacles) {
420
- const box=item?.box?normalizeBox(item,item.box):normalizeBox(item,item);
421
- if (roundedRectSignedDistance(pt.x,pt.y,box)<minObs) return false;
611
+ const box = item?.box ? normalizeBox(item, item.box) : normalizeBox(item, item);
612
+ if (roundedRectSignedDistance(pt.x, pt.y, box) < minObs) return false;
422
613
  }
423
614
  for (const other of placedPills) {
424
- if (Math.hypot(pt.x-other.x,pt.y-other.y)<26) return false;
615
+ if (Math.hypot(pt.x - other.x, pt.y - other.y) < 26) return false;
425
616
  }
426
617
  return true;
427
618
  };
428
- const allBoxes=[];
429
- for (const node of projection.nodes??[]) {
430
- const pt=points.get(node.name);
431
- if (pt) allBoxes.push({x:pt.x,y:pt.y,box:nodeBoxes.get(node.name)});
619
+ const allBoxes = [];
620
+ for (const node of projection.nodes ?? []) {
621
+ const pt = points.get(node.name);
622
+ if (pt) allBoxes.push({ x: pt.x, y: pt.y, box: nodeBoxes.get(node.name) });
432
623
  }
433
624
  for (const entry of routed) {
434
- const {edge,link}=entry;
435
- if (edge.length<40) continue;
436
- const p0=edge.start,c=edge.control,p1=edge.end;
437
- let chosen=edge.mid;
438
- if (!pillClear(chosen,allBoxes,12)) {
439
- for (const t of [0.38,0.62,0.32,0.68,0.44,0.56]) {
440
- const cand=bezierPoint(p0,c,p1,t);
441
- if (pillClear(cand,allBoxes,12)) {chosen=cand;break;}
625
+ const { edge, link } = entry;
626
+ if (edge.length < 40) continue;
627
+ const p0 = edge.start, c = edge.control, p1 = edge.end;
628
+ let chosen = edge.mid;
629
+ if (!pillClear(chosen, allBoxes, 12)) {
630
+ for (const t of [0.38, 0.62, 0.32, 0.68, 0.44, 0.56]) {
631
+ const cand = bezierPoint(p0, c, p1, t);
632
+ if (pillClear(cand, allBoxes, 12)) { chosen = cand; break; }
633
+ }
634
+ }
635
+ edge.mid = chosen;
636
+ if (link.count > 1) placedPills.push(chosen);
637
+ }
638
+ return routed.map(({ link, edge, bidirectional }) => ({ link, edge, bidirectional }));
639
+ }
640
+
641
+ function projectHive(posts, members, cursor) {
642
+ const mergeUser = shouldMergeUserToCoordinator(members);
643
+ const resolveActor = name => (mergeUser && name === 'user') ? 'coordinator' : name;
644
+ const effectiveCursor = (cursor === null || cursor === undefined) ? Infinity : Number(cursor);
645
+ const validPosts = (posts ?? []).filter(event => isPost(event) && Number.isFinite(event.seq))
646
+ .slice().sort((a, b) => a.seq - b.seq);
647
+ const maxSeq = validPosts.reduce((max, event) => Math.max(max, event.seq), 0);
648
+ const atHead = effectiveCursor >= maxSeq;
649
+ const activePosts = validPosts.filter(event => event.seq <= effectiveCursor);
650
+ const lastPost = activePosts.at(-1) ?? null;
651
+
652
+ const lastPostByAuthor = new Map();
653
+ const lastSeqByAuthor = new Map();
654
+ const briefSeqByMember = new Map();
655
+ const mentionSeqByMember = new Map();
656
+ for (const event of activePosts) {
657
+ const author = resolveActor(event.author);
658
+ lastSeqByAuthor.set(author, event.seq);
659
+ lastPostByAuthor.set(author, event);
660
+ const targets = new Set([...(event.targets ?? []).map(resolveActor), ...(event.coordinatorMention ? ['coordinator'] : [])]);
661
+ for (const target of targets) {
662
+ if (event.kind === 'brief') briefSeqByMember.set(target, event.seq);
663
+ mentionSeqByMember.set(target, event.seq);
664
+ }
665
+ }
666
+
667
+ const roster = members ?? [];
668
+ const coordSource = roster.find(m => m.role === 'coordinator' || m.name === 'coordinator') ??
669
+ { name: 'coordinator', role: 'coordinator', status: 'waiting' };
670
+ const workers = roster.filter(m => m.role !== 'coordinator' && m.name !== 'coordinator');
671
+
672
+ const bucketDefs = [
673
+ { id: 'working', label: 'Working', tone: 'working' },
674
+ { id: 'waiting', label: 'Waiting', tone: 'waiting' },
675
+ { id: 'needs', label: 'Needs you', tone: 'needs' },
676
+ { id: 'done', label: 'Done', tone: 'done' },
677
+ ];
678
+ const buckets = new Map(bucketDefs.map(def => [def.id, { ...def, count: 0, members: [] }]));
679
+ const clusterByMember = new Map([['coordinator', 'coordinator']]);
680
+
681
+ for (const worker of workers) {
682
+ const latestSeq = lastSeqByAuthor.get(worker.name) ?? 0;
683
+ let status;
684
+ let recoveryRequired = false;
685
+ let pendingWaitFor = [];
686
+
687
+ if (atHead) {
688
+ status = worker.status ?? 'waiting';
689
+ recoveryRequired = Boolean(worker.recoveryRequired);
690
+ pendingWaitFor = [...(worker.pendingWaitFor ?? worker.waitFor ?? [])];
691
+ } else {
692
+ const lastP = lastPostByAuthor.get(worker.name);
693
+ const briefSeq = briefSeqByMember.get(worker.name) ?? 0;
694
+ const mentionSeq = mentionSeqByMember.get(worker.name) ?? 0;
695
+ if (effectiveCursor <= 0) status = 'waiting';
696
+ else if (lastP && /\[done\]/i.test(String(lastP.text ?? ''))) status = 'done';
697
+ else if (resolveActor(lastPost?.author) === worker.name) status = 'working';
698
+ else if (Math.max(briefSeq, mentionSeq) > (lastP?.seq ?? 0)) status = 'working';
699
+ else status = 'waiting';
700
+ }
701
+
702
+ let bucketId;
703
+ if (recoveryRequired || status === 'failed' || status === 'quota') bucketId = 'needs';
704
+ else if (status === 'working') bucketId = 'working';
705
+ else if (status === 'done' || status === 'retired') bucketId = 'done';
706
+ else bucketId = 'waiting';
707
+
708
+ const muted = bucketId === 'done';
709
+ const entry = {
710
+ name: worker.name,
711
+ status,
712
+ role: worker.role ?? 'worker',
713
+ tint: worker.tint,
714
+ muted,
715
+ latestSeq,
716
+ pendingWaitFor,
717
+ };
718
+ const bucket = buckets.get(bucketId);
719
+ bucket.members.push(entry);
720
+ bucket.count = bucket.members.length;
721
+ clusterByMember.set(worker.name, bucketId);
722
+ }
723
+
724
+ const clusters = bucketDefs
725
+ .map(def => buckets.get(def.id))
726
+ .filter(cluster => cluster.count > 0);
727
+
728
+ const totalWorkers = workers.length;
729
+ const doneCount = buckets.get('done').count;
730
+ let phase;
731
+ if (buckets.get('needs').count > 0) phase = 'stalled';
732
+ else if (buckets.get('working').count > 0 || (atHead && coordSource.status === 'working')) phase = 'working';
733
+ else if (totalWorkers > 0 && doneCount === totalWorkers) phase = 'done';
734
+ else phase = 'waiting';
735
+
736
+ const coordinator = {
737
+ name: 'coordinator',
738
+ status: atHead ? (coordSource.status ?? phase) : (resolveActor(lastPost?.author) === 'coordinator' ? 'working' : phase),
739
+ role: 'coordinator',
740
+ doneCount,
741
+ totalWorkers,
742
+ phase,
743
+ latestSeq: lastSeqByAuthor.get('coordinator') ?? 0,
744
+ tint: coordSource.tint,
745
+ };
746
+
747
+ const connectors = [];
748
+ const seenConn = new Set();
749
+ const addConnector = conn => {
750
+ const key = `${conn.from}>${conn.to}>${conn.kind}`;
751
+ if (seenConn.has(key)) return;
752
+ seenConn.add(key);
753
+ connectors.push(conn);
754
+ };
755
+
756
+ if (buckets.get('done').count > 0) {
757
+ addConnector({ from: 'done', to: 'coordinator', kind: 'done', label: 'Tasks done' });
758
+ }
759
+
760
+ if (lastPost && (effectiveCursor === Infinity || lastPost.seq === effectiveCursor || !atHead)) {
761
+ const fromCell = clusterByMember.get(resolveActor(lastPost.author));
762
+ if (fromCell) {
763
+ const allFlag = lastPost.broadcast ?? /(?:^|[^a-z0-9_])@all(?![a-z0-9_-])/i.test(lastPost.text ?? '');
764
+ const rawTargets = [
765
+ ...(lastPost.targets ?? []).map(resolveActor),
766
+ ...(lastPost.coordinatorMention ? ['coordinator'] : []),
767
+ ];
768
+ if (allFlag) {
769
+ for (const cluster of clusters) {
770
+ if (cluster.id !== fromCell) {
771
+ addConnector({ from: fromCell, to: cluster.id, kind: 'message', label: 'Message just sent', seq: lastPost.seq });
772
+ }
773
+ }
774
+ if (fromCell !== 'coordinator') {
775
+ addConnector({ from: fromCell, to: 'coordinator', kind: 'message', label: 'Message just sent', seq: lastPost.seq });
776
+ }
777
+ } else {
778
+ for (const target of rawTargets) {
779
+ const toCell = clusterByMember.get(target);
780
+ if (toCell && toCell !== fromCell) {
781
+ addConnector({ from: fromCell, to: toCell, kind: 'message', label: 'Message just sent', seq: lastPost.seq });
782
+ }
783
+ }
784
+ }
785
+ }
786
+ }
787
+
788
+ for (const cluster of clusters) {
789
+ for (const member of cluster.members) {
790
+ for (const blocker of member.pendingWaitFor ?? []) {
791
+ const toCell = clusterByMember.get(blocker);
792
+ if (toCell) {
793
+ addConnector({ from: cluster.id, to: toCell, kind: 'waiting', label: 'Waiting on' });
794
+ }
442
795
  }
443
796
  }
444
- edge.mid=chosen;
445
- if (link.count>1) placedPills.push(chosen);
446
797
  }
447
- return routed.map(({link,edge,bidirectional})=>({link,edge,bidirectional}));
798
+
799
+ return {
800
+ currentSeq: lastPost?.seq ?? 0,
801
+ lastPost,
802
+ coordinator,
803
+ clusters,
804
+ connectors,
805
+ };
806
+ }
807
+
808
+ function hexVertices(cx, cy, radius) {
809
+ const vertices = [];
810
+ for (let i = 0; i < 6; i++) {
811
+ const angle = (i * Math.PI) / 3;
812
+ vertices.push({ x: cx + radius * Math.cos(angle), y: cy + radius * Math.sin(angle) });
813
+ }
814
+ return vertices;
448
815
  }
449
816
 
450
- function drawGrid(ctx,width,height,color) {
451
- const r=22;
452
- const h=Math.sqrt(3)*r;
453
- ctx.strokeStyle=color;
454
- ctx.lineWidth=0.8;
817
+ function hiveSlotRows(count) {
818
+ if (count <= 0) return [];
819
+ if (count <= 3) return [count];
820
+ if (count === 4) return [2, 2];
821
+ if (count === 5) return [3, 2];
822
+ if (count === 6) return [3, 3];
823
+ if (count === 7) return [4, 3];
824
+ if (count === 8) return [4, 4];
825
+ if (count === 9) return [3, 4, 2];
826
+ if (count === 10) return [4, 4, 2];
827
+ if (count === 11) return [4, 4, 3];
828
+ if (count === 12) return [4, 4, 4];
829
+ const rows = [];
830
+ let rem = count;
831
+ while (rem > 0) {
832
+ const take = Math.min(4, rem);
833
+ rows.push(take);
834
+ rem -= take;
835
+ }
836
+ return rows;
837
+ }
838
+
839
+ function computeClusterSlots(cx, cy, radius, members) {
840
+ const count = members.length;
841
+ if (!count) return [];
842
+ const halfH = (SQRT3 / 2) * radius;
843
+ const rows = hiveSlotRows(count);
844
+ const rowCount = rows.length;
845
+ const topBand = -halfH * 0.14;
846
+ const bottomBand = halfH * 0.50;
847
+ const bandCenter = rowCount === 1 ? halfH * 0.10 : (topBand + bottomBand) / 2;
848
+ const bandSpan = bottomBand - topBand;
849
+ const beeScale = count > 6
850
+ ? Math.max(0.7, Math.min(0.98, radius / 106))
851
+ : Math.max(0.82, Math.min(1.08, radius / 98));
852
+
853
+ const slots = [];
854
+ let idx = 0;
855
+ for (let r = 0; r < rowCount; r++) {
856
+ const cols = rows[r];
857
+ const ry = rowCount === 1
858
+ ? cy + bandCenter
859
+ : cy + topBand + (r / (rowCount - 1)) * bandSpan;
860
+ const dy = ry - cy;
861
+ // Exact horizontal half-span inside flat-top hexagon covering bee top (-15) and label bottom (+18).
862
+ const usableHalfW = Math.max(18, radius - Math.max(Math.abs(dy - 15), Math.abs(dy + 18)) / SQRT3 - 8);
863
+ const maxSpacing = count > 6 ? 42 : 52;
864
+ const stepX = cols === 1 ? 0 : Math.min(maxSpacing, (usableHalfW * 2 - 4) / cols);
865
+ const slotWidth = cols === 1 ? Math.min(88, usableHalfW * 1.85) : Math.max(30, stepX - 2);
866
+ for (let c = 0; c < cols; c++) {
867
+ const rx = cx + (c - (cols - 1) / 2) * stepX;
868
+ slots.push({
869
+ member: members[idx++],
870
+ x: rx,
871
+ y: ry,
872
+ slotWidth,
873
+ beeScale,
874
+ });
875
+ }
876
+ }
877
+ return slots;
878
+ }
879
+
880
+ function hiveMinimumHeight(clusterCount, width) {
881
+ if (clusterCount <= 1) return width < 420 ? 380 : 440;
882
+ if (clusterCount === 2) return width < 420 ? 440 : 430;
883
+ return 490;
884
+ }
885
+
886
+ function layoutHive(hiveModel, width = 680, height = 460) {
887
+ const clusters = hiveModel?.clusters ?? [];
888
+ const legendH = 34;
889
+ const topPad = 14;
890
+ const sidePad = 16;
891
+ const availW = Math.max(200, width - sidePad * 2);
892
+ const availH = Math.max(220, height - topPad - legendH);
893
+
894
+ let radius;
895
+ const specs = [];
896
+
897
+ if (clusters.length === 0) {
898
+ radius = Math.max(48, Math.min(availW / 2.2, availH / (SQRT3 * 1.15), 114));
899
+ specs.push({ id: 'coordinator', ux: 0, uy: 0, isCoord: true });
900
+ } else if (clusters.length === 1) {
901
+ const gap = Math.max(12, Math.min(20, availH * 0.036));
902
+ radius = Math.max(46, Math.min(availW / 2.15, (availH - gap) / (2 * SQRT3), 112));
903
+ const D = SQRT3 * radius + gap;
904
+ const centerX = width / 2;
905
+ const centerY = topPad + availH / 2;
906
+ const cellsById = new Map();
907
+ const topCenter = { x: centerX, y: centerY - D / 2 };
908
+ const botCenter = { x: centerX, y: centerY + D / 2 };
909
+
910
+ const c0 = clusters[0];
911
+ const clusterCell = {
912
+ id: c0.id,
913
+ label: c0.label,
914
+ tone: c0.tone,
915
+ count: c0.count,
916
+ x: topCenter.x,
917
+ y: topCenter.y,
918
+ radius,
919
+ vertices: hexVertices(topCenter.x, topCenter.y, radius),
920
+ slots: computeClusterSlots(topCenter.x, topCenter.y, radius, c0.members ?? []),
921
+ };
922
+ const coordCell = {
923
+ id: 'coordinator',
924
+ x: botCenter.x,
925
+ y: botCenter.y,
926
+ radius,
927
+ vertices: hexVertices(botCenter.x, botCenter.y, radius),
928
+ model: hiveModel.coordinator,
929
+ };
930
+ cellsById.set(clusterCell.id, clusterCell);
931
+ cellsById.set('coordinator', coordCell);
932
+ return { width, height, radius, coordinator: coordCell, clusters: [clusterCell], cellsById };
933
+ } else if (clusters.length === 2) {
934
+ specs.push({ id: 'coordinator', ux: 0, uy: 0.35, isCoord: true });
935
+ if (availW >= availH * 0.85) {
936
+ specs.push({ id: clusters[0].id, cluster: clusters[0], ux: -SQRT3 / 2, uy: -0.15 });
937
+ specs.push({ id: clusters[1].id, cluster: clusters[1], ux: SQRT3 / 2, uy: -0.15 });
938
+ } else {
939
+ specs.push({ id: clusters[0].id, cluster: clusters[0], ux: 0, uy: -0.65 });
940
+ specs.push({ id: clusters[1].id, cluster: clusters[1], ux: 0, uy: 1.35 });
941
+ }
942
+ } else if (clusters.length === 3) {
943
+ specs.push({ id: 'coordinator', ux: 0, uy: 0, isCoord: true });
944
+ specs.push({ id: clusters[0].id, cluster: clusters[0], ux: 0, uy: -1 });
945
+ specs.push({ id: clusters[1].id, cluster: clusters[1], ux: -SQRT3 / 2, uy: 0.5 });
946
+ specs.push({ id: clusters[2].id, cluster: clusters[2], ux: SQRT3 / 2, uy: 0.5 });
947
+ } else {
948
+ specs.push({ id: 'coordinator', ux: 0, uy: 0, isCoord: true });
949
+ specs.push({ id: clusters[0].id, cluster: clusters[0], ux: -SQRT3 / 2, uy: -0.5 });
950
+ specs.push({ id: clusters[1].id, cluster: clusters[1], ux: SQRT3 / 2, uy: -0.5 });
951
+ specs.push({ id: clusters[2].id, cluster: clusters[2], ux: -SQRT3 / 2, uy: 0.5 });
952
+ specs.push({ id: clusters[3].id, cluster: clusters[3], ux: SQRT3 / 2, uy: 0.5 });
953
+ for (let i = 4; i < clusters.length; i++) {
954
+ specs.push({ id: clusters[i].id, cluster: clusters[i], ux: 0, uy: i === 4 ? -1 : 1 });
955
+ }
956
+ }
957
+
958
+ const minUX = Math.min(...specs.map(s => s.ux));
959
+ const maxUX = Math.max(...specs.map(s => s.ux));
960
+ const minUY = Math.min(...specs.map(s => s.uy));
961
+ const maxUY = Math.max(...specs.map(s => s.uy));
962
+ const spanUX = maxUX - minUX;
963
+ const spanUY = maxUY - minUY;
964
+ const gap = Math.max(10, Math.min(18, availH * 0.03));
965
+
966
+ const maxRWidth = (availW - spanUX * gap) / (spanUX * SQRT3 + 2);
967
+ const maxRHeight = (availH - spanUY * gap) / (spanUY * SQRT3 + SQRT3);
968
+ radius = Math.max(40, Math.min(maxRWidth, maxRHeight, 108));
969
+
970
+ const D = SQRT3 * radius + gap;
971
+ const midUX = (minUX + maxUX) / 2;
972
+ const midUY = (minUY + maxUY) / 2;
973
+ const originX = width / 2 - midUX * D;
974
+ const originY = topPad + availH / 2 - midUY * D;
975
+
976
+ const cellsById = new Map();
977
+ let coordCell = null;
978
+ const clusterCells = [];
979
+
980
+ for (const spec of specs) {
981
+ const cx = originX + spec.ux * D;
982
+ const cy = originY + spec.uy * D;
983
+ const vertices = hexVertices(cx, cy, radius);
984
+ if (spec.isCoord) {
985
+ coordCell = { id: 'coordinator', x: cx, y: cy, radius, vertices, model: hiveModel?.coordinator };
986
+ cellsById.set('coordinator', coordCell);
987
+ } else {
988
+ const cl = spec.cluster;
989
+ const cell = {
990
+ id: cl.id,
991
+ label: cl.label,
992
+ tone: cl.tone,
993
+ count: cl.count,
994
+ x: cx,
995
+ y: cy,
996
+ radius,
997
+ vertices,
998
+ slots: computeClusterSlots(cx, cy, radius, cl.members ?? []),
999
+ };
1000
+ clusterCells.push(cell);
1001
+ cellsById.set(cell.id, cell);
1002
+ }
1003
+ }
1004
+
1005
+ return {
1006
+ width,
1007
+ height,
1008
+ radius,
1009
+ coordinator: coordCell,
1010
+ clusters: clusterCells,
1011
+ cellsById,
1012
+ };
1013
+ }
1014
+
1015
+ function hexRayExit(cell, ux, uy) {
1016
+ const apothem = (SQRT3 / 2) * cell.radius;
1017
+ const d1 = Math.abs(uy);
1018
+ const d2 = Math.abs(0.8660254037844386 * ux + 0.5 * uy);
1019
+ const d3 = Math.abs(0.8660254037844386 * ux - 0.5 * uy);
1020
+ return apothem / Math.max(d1, d2, d3, 1e-6);
1021
+ }
1022
+
1023
+ function drawGrid(ctx, width, height, color) {
1024
+ const r = 22;
1025
+ const h = Math.sqrt(3) * r;
1026
+ ctx.strokeStyle = color;
1027
+ ctx.lineWidth = 0.8;
455
1028
  ctx.beginPath();
456
- for (let col=-1;col<width/(r*1.5)+1;col++) {
457
- for (let row=-1;row<height/h+1;row++) {
458
- const x=col*1.5*r;
459
- const y=row*h+((col%2)*h/2);
460
- for (let side=0;side<6;side++) {
461
- const angle=side*Math.PI/3;
462
- const px=x+r*Math.cos(angle),py=y+r*Math.sin(angle);
463
- if (side===0) ctx.moveTo(px,py); else ctx.lineTo(px,py);
1029
+ for (let col = -1; col < width / (r * 1.5) + 1; col++) {
1030
+ for (let row = -1; row < height / h + 1; row++) {
1031
+ const x = col * 1.5 * r;
1032
+ const y = row * h + ((col % 2) * h / 2);
1033
+ for (let side = 0; side < 6; side++) {
1034
+ const angle = side * Math.PI / 3;
1035
+ const px = x + r * Math.cos(angle), py = y + r * Math.sin(angle);
1036
+ if (side === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);
464
1037
  }
465
1038
  ctx.closePath();
466
1039
  }
@@ -468,99 +1041,564 @@
468
1041
  ctx.stroke();
469
1042
  }
470
1043
 
471
- function pillPath(ctx,x,y,w,h,r) {
472
- const radius=Math.min(r,w/2,h/2);
473
- const x0=x-w/2,y0=y-h/2,x1=x+w/2,y1=y+h/2;
1044
+ function pillPath(ctx, x, y, w, h, r) {
1045
+ const radius = Math.min(r, w / 2, h / 2);
1046
+ const x0 = x - w / 2, y0 = y - h / 2, x1 = x + w / 2, y1 = y + h / 2;
474
1047
  ctx.beginPath();
475
- ctx.moveTo(x0+radius,y0);
476
- ctx.lineTo(x1-radius,y0);
477
- ctx.quadraticCurveTo(x1,y0,x1,y0+radius);
478
- ctx.lineTo(x1,y1-radius);
479
- ctx.quadraticCurveTo(x1,y1,x1-radius,y1);
480
- ctx.lineTo(x0+radius,y1);
481
- ctx.quadraticCurveTo(x0,y1,x0,y1-radius);
482
- ctx.lineTo(x0,y0+radius);
483
- ctx.quadraticCurveTo(x0,y0,x0+radius,y0);
1048
+ ctx.moveTo(x0 + radius, y0);
1049
+ ctx.lineTo(x1 - radius, y0);
1050
+ ctx.quadraticCurveTo(x1, y0, x1, y0 + radius);
1051
+ ctx.lineTo(x1, y1 - radius);
1052
+ ctx.quadraticCurveTo(x1, y1, x1 - radius, y1);
1053
+ ctx.lineTo(x0 + radius, y1);
1054
+ ctx.quadraticCurveTo(x0, y1, x0, y1 - radius);
1055
+ ctx.lineTo(x0, y0 + radius);
1056
+ ctx.quadraticCurveTo(x0, y0, x0 + radius, y0);
484
1057
  ctx.closePath();
485
1058
  }
486
1059
 
487
- function draw(canvas,projection,points,focus,highlight,color) {
488
- const width=canvas.clientWidth;
489
- const height=canvas.clientHeight;
1060
+ function draw(canvas, projection, points, focus, highlight, color) {
1061
+ const width = canvas.clientWidth;
1062
+ const height = canvas.clientHeight;
490
1063
  if (!width || !height) return;
491
- const scale=Math.min(devicePixelRatio || 1,2);
492
- const pixelsWide=Math.round(width*scale),pixelsHigh=Math.round(height*scale);
493
- if (canvas.width!==pixelsWide || canvas.height!==pixelsHigh) {
494
- canvas.width=pixelsWide;
495
- canvas.height=pixelsHigh;
496
- }
497
- const ctx=canvas.getContext('2d');
498
- ctx.setTransform(scale,0,0,scale,0,0);
499
- ctx.clearRect(0,0,width,height);
500
- drawGrid(ctx,width,height,color.grid);
501
- ctx.strokeStyle=color.accent;
502
- ctx.lineWidth=1.4;
503
- ctx.setLineDash([3,3]);
1064
+ const scale = Math.min(devicePixelRatio || 1, 2);
1065
+ const pixelsWide = Math.round(width * scale), pixelsHigh = Math.round(height * scale);
1066
+ if (canvas.width !== pixelsWide || canvas.height !== pixelsHigh) {
1067
+ canvas.width = pixelsWide;
1068
+ canvas.height = pixelsHigh;
1069
+ }
1070
+ const ctx = canvas.getContext('2d');
1071
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
1072
+ ctx.clearRect(0, 0, width, height);
1073
+ drawGrid(ctx, width, height, color.grid);
1074
+ ctx.strokeStyle = color.accent;
1075
+ ctx.lineWidth = 1.4;
1076
+ ctx.setLineDash([3, 3]);
504
1077
  for (const node of projection.nodes) {
505
- const point=points.get(node.name);
506
- if (!point||!unmentionedNode(node)) continue;
507
- ctx.globalAlpha=!focus||focus===node.name?0.85:0.2;
1078
+ const point = points.get(node.name);
1079
+ if (!point || !unmentionedNode(node)) continue;
1080
+ ctx.globalAlpha = !focus || focus === node.name ? 0.85 : 0.2;
508
1081
  ctx.beginPath();
509
- ctx.arc(point.x,point.y,31,0,Math.PI*2);
1082
+ ctx.arc(point.x, point.y, 31, 0, Math.PI * 2);
510
1083
  ctx.stroke();
511
1084
  }
512
1085
  ctx.setLineDash([]);
513
- ctx.font='600 10px ui-monospace, monospace';
514
- ctx.textAlign='center';
515
- ctx.textBaseline='middle';
516
- const routed=routeEdges(projection,points,{
517
- variant:'hex',narrow:width<465,marginStart:6,marginEnd:6,obstacleMargin:width<465?14:24,
1086
+ ctx.font = '600 10px ui-monospace, monospace';
1087
+ ctx.textAlign = 'center';
1088
+ ctx.textBaseline = 'middle';
1089
+ const routed = routeEdges(projection, points, {
1090
+ variant: 'hex', narrow: width < 465, marginStart: 6, marginEnd: 6, obstacleMargin: width < 465 ? 14 : 24,
518
1091
  });
519
- for (const {link,edge} of routed) {
520
- const {start:a,control:c,end:b,mid,endAngle:angle}=edge;
521
- const pulse=link.lastSeq===highlight;
522
- const related=!focus || link.from===focus || link.to===focus;
523
- const stroke=pulse && related ? color.accent : color.link;
524
- ctx.globalAlpha=related ? (pulse ? 1 : 0.78) : 0.16;
525
- ctx.strokeStyle=ctx.fillStyle=stroke;
526
- ctx.lineWidth=Math.min(3.8,1.1+Math.sqrt(link.count)*0.65);
527
- ctx.lineCap='round';
528
- ctx.setLineDash(link.direct ? [] : [4,4]);
529
- const shaftInset=Math.min(4.5,edge.length*0.25);
530
- const sx=b.x-Math.cos(angle)*shaftInset;
531
- const sy=b.y-Math.sin(angle)*shaftInset;
1092
+ for (const { link, edge } of routed) {
1093
+ const { start: a, control: c, end: b, mid, endAngle: angle } = edge;
1094
+ const pulse = link.lastSeq === highlight;
1095
+ const related = !focus || link.from === focus || link.to === focus;
1096
+ const stroke = pulse && related ? color.accent : color.link;
1097
+ ctx.globalAlpha = related ? (pulse ? 1 : 0.78) : 0.16;
1098
+ ctx.strokeStyle = ctx.fillStyle = stroke;
1099
+ ctx.lineWidth = Math.min(3.8, 1.1 + Math.sqrt(link.count) * 0.65);
1100
+ ctx.lineCap = 'round';
1101
+ ctx.setLineDash(link.direct ? [] : [4, 4]);
1102
+ const shaftInset = Math.min(4.5, edge.length * 0.25);
1103
+ const sx = b.x - Math.cos(angle) * shaftInset;
1104
+ const sy = b.y - Math.sin(angle) * shaftInset;
532
1105
  ctx.beginPath();
533
- ctx.moveTo(a.x,a.y);
534
- ctx.quadraticCurveTo(c.x,c.y,sx,sy);
1106
+ ctx.moveTo(a.x, a.y);
1107
+ ctx.quadraticCurveTo(c.x, c.y, sx, sy);
535
1108
  ctx.stroke();
536
1109
  ctx.setLineDash([]);
537
- const headLen=9;
1110
+ const headLen = 9;
538
1111
  ctx.beginPath();
539
- ctx.moveTo(b.x,b.y);
540
- ctx.lineTo(b.x-headLen*Math.cos(angle-0.44),b.y-headLen*Math.sin(angle-0.44));
541
- ctx.lineTo(b.x-(headLen*0.72)*Math.cos(angle),b.y-(headLen*0.72)*Math.sin(angle));
542
- ctx.lineTo(b.x-headLen*Math.cos(angle+0.44),b.y-headLen*Math.sin(angle+0.44));
1112
+ ctx.moveTo(b.x, b.y);
1113
+ ctx.lineTo(b.x - headLen * Math.cos(angle - 0.44), b.y - headLen * Math.sin(angle - 0.44));
1114
+ ctx.lineTo(b.x - (headLen * 0.72) * Math.cos(angle), b.y - (headLen * 0.72) * Math.sin(angle));
1115
+ ctx.lineTo(b.x - headLen * Math.cos(angle + 0.44), b.y - headLen * Math.sin(angle + 0.44));
543
1116
  ctx.closePath();
544
1117
  ctx.fill();
545
- if (related && edge.length>=40 && (link.count>1 || pulse || focus)) {
546
- const label=String(link.count);
547
- const pillW=Math.max(20,label.length*6.5+10);
548
- ctx.globalAlpha=0.98;
549
- pillPath(ctx,mid.x,mid.y,pillW,15,7.5);
550
- ctx.fillStyle=color.paper;
1118
+ if (related && edge.length >= 40 && (link.count > 1 || pulse || focus)) {
1119
+ const label = String(link.count);
1120
+ const pillW = Math.max(20, label.length * 6.5 + 10);
1121
+ ctx.globalAlpha = 0.98;
1122
+ pillPath(ctx, mid.x, mid.y, pillW, 15, 7.5);
1123
+ ctx.fillStyle = color.paper;
1124
+ ctx.fill();
1125
+ ctx.lineWidth = 1;
1126
+ ctx.strokeStyle = pulse ? color.accent : color.link;
1127
+ ctx.stroke();
1128
+ ctx.fillStyle = pulse ? color.accent : color.text;
1129
+ ctx.fillText(label, mid.x, mid.y + 0.25);
1130
+ }
1131
+ }
1132
+ ctx.globalAlpha = 1;
1133
+ }
1134
+
1135
+ function themePalette(theme) {
1136
+ if (theme === 'dark') {
1137
+ return {
1138
+ bg: '#17140f',
1139
+ surface: '#221d16',
1140
+ ink: '#f5eddd',
1141
+ muted: '#bdb19a',
1142
+ border: '#43392b',
1143
+ edge: '#8c785c',
1144
+ pulse: '#c297ff',
1145
+ accent: '#f0b84b',
1146
+ doneFill: '#18281c',
1147
+ doneStroke: '#6ac47e',
1148
+ workingFill: '#2a2213',
1149
+ workingStroke: '#f0b84b',
1150
+ waitingFill: '#192133',
1151
+ waitingStroke: '#7da3f0',
1152
+ needsFill: '#2d1919',
1153
+ needsStroke: '#ef766e',
1154
+ };
1155
+ }
1156
+ return {
1157
+ bg: '#f8f9fb',
1158
+ surface: '#ffffff',
1159
+ ink: '#24292f',
1160
+ muted: '#6e7781',
1161
+ border: '#d0d7de',
1162
+ edge: '#b4bcc6',
1163
+ pulse: '#8250df',
1164
+ accent: '#bf8700',
1165
+ doneFill: '#eef6ee',
1166
+ doneStroke: '#55943c',
1167
+ workingFill: '#fdf6e7',
1168
+ workingStroke: '#d18d22',
1169
+ waitingFill: '#eef3fc',
1170
+ waitingStroke: '#4d78cc',
1171
+ needsFill: '#fdf0ef',
1172
+ needsStroke: '#cf483f',
1173
+ };
1174
+ }
1175
+
1176
+ function toneStyle(tone, palette) {
1177
+ if (tone === 'done') return { fill: palette.doneFill, stroke: palette.doneStroke };
1178
+ if (tone === 'working') return { fill: palette.workingFill, stroke: palette.workingStroke };
1179
+ if (tone === 'needs' || tone === 'stalled') return { fill: palette.needsFill, stroke: palette.needsStroke };
1180
+ return { fill: palette.waitingFill, stroke: palette.waitingStroke };
1181
+ }
1182
+
1183
+ function statusDotColor(status, palette) {
1184
+ if (status === 'working') return palette.doneStroke;
1185
+ if (status === 'failed' || status === 'quota') return palette.needsStroke;
1186
+ if (status === 'waiting' || status === 'queued') return palette.waitingStroke;
1187
+ return palette.muted;
1188
+ }
1189
+
1190
+ function resolveBees(explicitBees) {
1191
+ if (explicitBees) return explicitBees;
1192
+ if (typeof window !== 'undefined' && window.HiveBee) return window.HiveBee;
1193
+ return globalThis.HiveBee;
1194
+ }
1195
+
1196
+ function drawBeeOnCtx(ctx, x, y, name, beeOpts, beesLib) {
1197
+ if (beesLib?.drawSprite) {
1198
+ beesLib.drawSprite(ctx, x, y, name, beeOpts);
1199
+ return;
1200
+ }
1201
+ if (beesLib?.sprite && typeof document !== 'undefined') {
1202
+ const sprite = beesLib.sprite(name, beeOpts);
1203
+ const scale = beeOpts?.scale ?? 1;
1204
+ ctx.drawImage?.(sprite, x, y, sprite.width * scale, sprite.height * scale);
1205
+ }
1206
+ }
1207
+
1208
+ function truncateFit(text, maxChars) {
1209
+ const str = String(text ?? '');
1210
+ if (str.length <= maxChars) return str;
1211
+ if (maxChars <= 3) return str.slice(0, maxChars);
1212
+ return str.slice(0, maxChars - 1) + '…';
1213
+ }
1214
+
1215
+ function drawArrowHead(ctx, x, y, angle, len = 8) {
1216
+ ctx.beginPath();
1217
+ ctx.moveTo(x, y);
1218
+ ctx.lineTo(x - len * Math.cos(angle - 0.44), y - len * Math.sin(angle - 0.44));
1219
+ ctx.lineTo(x - (len * 0.7) * Math.cos(angle), y - (len * 0.7) * Math.sin(angle));
1220
+ ctx.lineTo(x - len * Math.cos(angle + 0.44), y - len * Math.sin(angle + 0.44));
1221
+ ctx.closePath();
1222
+ ctx.fill();
1223
+ }
1224
+
1225
+ function drawHexPolygon(ctx, vertices) {
1226
+ ctx.beginPath();
1227
+ vertices.forEach((pt, idx) => {
1228
+ if (idx === 0) ctx.moveTo(pt.x, pt.y);
1229
+ else ctx.lineTo(pt.x, pt.y);
1230
+ });
1231
+ ctx.closePath();
1232
+ }
1233
+
1234
+ function renderHiveFrame(ctx, opts, palette, beesLib) {
1235
+ const { posts = [], members = [], cursor = null, phase, width = 680, height = 460, focus = null } = opts;
1236
+ const hiveModel = projectHive(posts, members, cursor);
1237
+ if (phase && (cursor === null || cursor === undefined)) {
1238
+ if (phase === 'done' && hiveModel.coordinator.totalWorkers > 0 && hiveModel.coordinator.doneCount === hiveModel.coordinator.totalWorkers) {
1239
+ hiveModel.coordinator.phase = 'done';
1240
+ } else if (phase === 'stalled' || phase === 'budget') {
1241
+ hiveModel.coordinator.phase = 'stalled';
1242
+ }
1243
+ }
1244
+ const hiveLayout = layoutHive(hiveModel, width, height);
1245
+
1246
+ // Draw connectors between hex borders.
1247
+ for (const conn of hiveModel.connectors) {
1248
+ const fromCell = hiveLayout.cellsById.get(conn.from);
1249
+ const toCell = hiveLayout.cellsById.get(conn.to);
1250
+ if (!fromCell || !toCell) continue;
1251
+ const stroke = conn.kind === 'message' ? palette.pulse
1252
+ : conn.kind === 'waiting' ? palette.workingStroke
1253
+ : palette.doneStroke;
1254
+ ctx.strokeStyle = stroke;
1255
+ ctx.fillStyle = stroke;
1256
+ ctx.lineWidth = conn.kind === 'message' ? 2.2 : 1.5;
1257
+ ctx.setLineDash?.(conn.kind === 'waiting' ? [4, 4] : []);
1258
+
1259
+ if (fromCell === toCell) {
1260
+ const vx = fromCell.x + fromCell.radius * 0.72;
1261
+ const vy = fromCell.y - (SQRT3 / 2) * fromCell.radius * 0.4;
1262
+ ctx.beginPath();
1263
+ ctx.arc(vx + 8, vy, 10, -Math.PI * 0.8, Math.PI * 0.8);
1264
+ ctx.stroke();
1265
+ ctx.setLineDash?.([]);
1266
+ continue;
1267
+ }
1268
+
1269
+ const dx = toCell.x - fromCell.x;
1270
+ const dy = toCell.y - fromCell.y;
1271
+ const dist = Math.hypot(dx, dy);
1272
+ if (dist < 1) continue;
1273
+ const ux = dx / dist, uy = dy / dist;
1274
+ const exitA = hexRayExit(fromCell, ux, uy);
1275
+ const exitB = hexRayExit(toCell, -ux, -uy);
1276
+ const lateral = conn.kind === 'message' ? 8 : conn.kind === 'waiting' ? -8 : 0;
1277
+ const nx = -uy, ny = ux;
1278
+ const ax = fromCell.x + ux * (exitA + 2) + nx * lateral;
1279
+ const ay = fromCell.y + uy * (exitA + 2) + ny * lateral;
1280
+ const bx = toCell.x - ux * (exitB + 2) + nx * lateral;
1281
+ const by = toCell.y - uy * (exitB + 2) + ny * lateral;
1282
+ ctx.beginPath();
1283
+ ctx.moveTo(ax, ay);
1284
+ ctx.lineTo(bx, by);
1285
+ ctx.stroke();
1286
+ ctx.setLineDash?.([]);
1287
+ if (conn.kind !== 'done') {
1288
+ drawArrowHead(ctx, bx, by, Math.atan2(by - ay, bx - ax), 7);
1289
+ }
1290
+ }
1291
+
1292
+ ctx.textAlign = 'center';
1293
+ ctx.textBaseline = 'middle';
1294
+
1295
+ // Draw state cluster hexagons.
1296
+ for (const cluster of hiveLayout.clusters) {
1297
+ const style = toneStyle(cluster.tone, palette);
1298
+ const hasFocus = Boolean(focus);
1299
+ const clusterFocused = !hasFocus || cluster.slots.some(s => s.member.name === focus);
1300
+ ctx.globalAlpha = clusterFocused ? 1 : 0.38;
1301
+ drawHexPolygon(ctx, cluster.vertices);
1302
+ ctx.fillStyle = style.fill;
1303
+ ctx.fill();
1304
+ ctx.lineWidth = 2;
1305
+ ctx.strokeStyle = style.stroke;
1306
+ ctx.stroke();
1307
+
1308
+ const halfH = (SQRT3 / 2) * cluster.radius;
1309
+ ctx.fillStyle = palette.ink;
1310
+ ctx.font = '600 12px "Segoe UI", system-ui, sans-serif';
1311
+ ctx.fillText(cluster.label, cluster.x, cluster.y - halfH * 0.68);
1312
+ ctx.fillStyle = palette.muted;
1313
+ ctx.font = '500 11px "Segoe UI", system-ui, sans-serif';
1314
+ ctx.fillText(String(cluster.count), cluster.x, cluster.y - halfH * 0.50);
1315
+
1316
+ for (const slot of cluster.slots) {
1317
+ const s = slot.beeScale;
1318
+ const beeW = 20 * s;
1319
+ const beeH = 18 * s;
1320
+ const slotDim = hasFocus && focus !== slot.member.name;
1321
+ ctx.globalAlpha = slotDim ? 0.35 : 1;
1322
+ if (hasFocus && focus === slot.member.name) {
1323
+ ctx.strokeStyle = palette.accent;
1324
+ ctx.lineWidth = 1.5;
1325
+ ctx.beginPath();
1326
+ ctx.arc(slot.x, slot.y - 2, Math.max(beeW, beeH) * 0.72, 0, Math.PI * 2);
1327
+ ctx.stroke();
1328
+ }
1329
+ drawBeeOnCtx(ctx, slot.x - beeW / 2, slot.y - beeH * 0.68, slot.member.name, {
1330
+ status: slot.member.status,
1331
+ coordinator: false,
1332
+ tint: slot.member.tint,
1333
+ muted: slot.member.muted,
1334
+ scale: s,
1335
+ }, beesLib);
1336
+ ctx.fillStyle = slot.member.muted ? palette.muted : palette.ink;
1337
+ ctx.font = '500 9.5px "Segoe UI", system-ui, sans-serif';
1338
+ const maxChars = Math.max(6, Math.floor(slot.slotWidth / 4.6));
1339
+ ctx.fillText(truncateFit(slot.member.name, maxChars), slot.x, slot.y + beeH * 0.62);
1340
+ }
1341
+ }
1342
+
1343
+ // Draw Coordinator hexagon.
1344
+ const coord = hiveLayout.coordinator;
1345
+ if (coord) {
1346
+ const coordTone = toneStyle(coord.model?.phase ?? 'waiting', palette);
1347
+ ctx.globalAlpha = !focus || focus === 'coordinator' ? 1 : 0.45;
1348
+ drawHexPolygon(ctx, coord.vertices);
1349
+ ctx.fillStyle = coordTone.fill;
1350
+ ctx.fill();
1351
+ ctx.lineWidth = 2;
1352
+ ctx.strokeStyle = coordTone.stroke;
1353
+ ctx.stroke();
1354
+
1355
+ const coordScale = Math.max(1.2, Math.min(2.1, coord.radius / 48));
1356
+ const cBeeW = 20 * coordScale;
1357
+ const cBeeH = 18 * coordScale;
1358
+ drawBeeOnCtx(ctx, coord.x - cBeeW / 2, coord.y - cBeeH * 0.78, 'coordinator', {
1359
+ status: coord.model?.status ?? 'waiting',
1360
+ coordinator: true,
1361
+ tint: coord.model?.tint,
1362
+ muted: false,
1363
+ scale: coordScale,
1364
+ }, beesLib);
1365
+
1366
+ const halfH = (SQRT3 / 2) * coord.radius;
1367
+ ctx.fillStyle = palette.ink;
1368
+ ctx.font = '650 12px "Segoe UI", system-ui, sans-serif';
1369
+ ctx.fillText('Coordinator', coord.x, coord.y + halfH * 0.34);
1370
+ ctx.fillStyle = palette.muted;
1371
+ ctx.font = '500 11px "Segoe UI", system-ui, sans-serif';
1372
+ ctx.fillText(`${coord.model?.doneCount ?? 0} of ${coord.model?.totalWorkers ?? 0} done`, coord.x, coord.y + halfH * 0.56);
1373
+ }
1374
+
1375
+ // Bottom legend matching Screenshot 1.
1376
+ ctx.globalAlpha = 1;
1377
+ const ly = height - 16;
1378
+ let lx = 24;
1379
+ ctx.textAlign = 'left';
1380
+ ctx.textBaseline = 'middle';
1381
+ ctx.font = '500 11px "Segoe UI", system-ui, sans-serif';
1382
+
1383
+ ctx.strokeStyle = palette.doneStroke;
1384
+ ctx.lineWidth = 1.6;
1385
+ ctx.beginPath(); ctx.moveTo(lx, ly); ctx.lineTo(lx + 16, ly); ctx.stroke();
1386
+ ctx.fillStyle = palette.muted;
1387
+ ctx.fillText('Tasks done', lx + 22, ly);
1388
+ lx += 102;
1389
+
1390
+ ctx.strokeStyle = palette.pulse;
1391
+ ctx.beginPath(); ctx.moveTo(lx, ly); ctx.lineTo(lx + 16, ly); ctx.stroke();
1392
+ ctx.fillText('Message just sent', lx + 22, ly);
1393
+ lx += 136;
1394
+
1395
+ ctx.strokeStyle = palette.workingStroke;
1396
+ ctx.fillStyle = palette.workingStroke;
1397
+ ctx.setLineDash?.([3, 3]);
1398
+ ctx.beginPath(); ctx.moveTo(lx, ly); ctx.lineTo(lx + 16, ly); ctx.stroke();
1399
+ ctx.setLineDash?.([]);
1400
+ drawArrowHead(ctx, lx + 20, ly, 0, 5);
1401
+ ctx.fillStyle = palette.muted;
1402
+ ctx.fillText('Waiting on', lx + 26, ly);
1403
+ }
1404
+
1405
+ function renderMentionsFrame(ctx, opts, palette, beesLib) {
1406
+ const {
1407
+ posts = [], members = [], cursor = null, width = 680, height = 460,
1408
+ hideInactive = false, expandBroadcast = false, focus = null,
1409
+ } = opts;
1410
+ const validPosts = (posts ?? []).filter(isPost).slice().sort((a, b) => a.seq - b.seq);
1411
+ const effectiveSeq = (cursor === null || cursor === undefined)
1412
+ ? (validPosts.at(-1)?.seq ?? Infinity)
1413
+ : Number(cursor);
1414
+ const currentPost = validPosts.filter(p => p.seq <= effectiveSeq).at(-1) ?? null;
1415
+ const projection = project(posts, members, effectiveSeq, { hideInactive, expandBroadcast });
1416
+ const stageH = Math.max(220, height - 42);
1417
+ const narrow = width < 465;
1418
+ const points = layoutMentions(projection.nodes, width, stageH);
1419
+
1420
+ const boxes = new Map();
1421
+ for (const node of projection.nodes) {
1422
+ boxes.set(node.name, nodeBox(node, { variant: 'pill', narrow }));
1423
+ }
1424
+ const routed = routeEdges(projection, points, {
1425
+ variant: 'pill', boxes, narrow, marginStart: 4, marginEnd: 6, obstacleMargin: 10,
1426
+ });
1427
+
1428
+ ctx.textAlign = 'center';
1429
+ ctx.textBaseline = 'middle';
1430
+
1431
+ // Draw routed Bézier mention edges.
1432
+ for (const { link, edge } of routed) {
1433
+ const { start: a, control: c, end: b, mid, endAngle: angle } = edge;
1434
+ const pulse = Boolean(currentPost && link.lastSeq === currentPost.seq);
1435
+ const related = !focus || link.from === focus || link.to === focus;
1436
+ const stroke = pulse && related ? palette.pulse : palette.edge;
1437
+ ctx.globalAlpha = related ? (pulse ? 0.96 : 0.72) : 0.16;
1438
+ ctx.strokeStyle = ctx.fillStyle = stroke;
1439
+ ctx.lineWidth = Math.min(4.2, 1.2 + Math.sqrt(link.count) * 0.72);
1440
+ ctx.setLineDash?.(link.direct ? [] : [4, 4]);
1441
+ const shaftInset = Math.min(4.5, edge.length * 0.25);
1442
+ const sx = b.x - Math.cos(angle) * shaftInset;
1443
+ const sy = b.y - Math.sin(angle) * shaftInset;
1444
+ ctx.beginPath();
1445
+ ctx.moveTo(a.x, a.y);
1446
+ ctx.quadraticCurveTo(c.x, c.y, sx, sy);
1447
+ ctx.stroke();
1448
+ ctx.setLineDash?.([]);
1449
+ drawArrowHead(ctx, b.x, b.y, angle, 8);
1450
+
1451
+ if (related && edge.length >= 36 && (link.count > 1 || pulse || focus)) {
1452
+ const label = String(link.count);
1453
+ const badgeW = Math.max(16, label.length * 6.5 + 8);
1454
+ ctx.globalAlpha = 0.96;
1455
+ pillPath(ctx, mid.x, mid.y, badgeW, 14, 7);
1456
+ ctx.fillStyle = palette.bg;
551
1457
  ctx.fill();
552
- ctx.lineWidth=1;
553
- ctx.strokeStyle=pulse ? color.accent : color.link;
1458
+ ctx.fillStyle = pulse ? palette.pulse : palette.ink;
1459
+ ctx.font = '600 10px ui-monospace, monospace';
1460
+ ctx.fillText(label, mid.x, mid.y + 0.5);
1461
+ }
1462
+ }
1463
+
1464
+ // Draw capsule pill nodes.
1465
+ for (const node of projection.nodes) {
1466
+ const pt = points.get(node.name);
1467
+ const box = boxes.get(node.name);
1468
+ if (!pt || !box) continue;
1469
+ const isCoord = node.role === 'coordinator' || node.name === 'coordinator';
1470
+ const isRetired = node.status === 'retired';
1471
+ const isDone = node.status === 'done' || isRetired;
1472
+ const related = !focus || focus === node.name ||
1473
+ projection.links.some(l => (l.from === focus && l.to === node.name) || (l.to === focus && l.from === node.name));
1474
+ ctx.globalAlpha = related ? (isRetired ? 0.56 : 1) : 0.24;
1475
+
1476
+ const unmentioned = unmentionedNode(node);
1477
+ pillPath(ctx, pt.x, pt.y, box.halfW * 2, box.halfH * 2, box.radius);
1478
+ ctx.fillStyle = palette.surface;
1479
+ ctx.fill();
1480
+ ctx.lineWidth = focus === node.name ? 1.8 : 1.1;
1481
+ ctx.strokeStyle = focus === node.name ? palette.pulse : palette.border;
1482
+ ctx.setLineDash?.(unmentioned ? [3, 3] : []);
1483
+ ctx.stroke();
1484
+ ctx.setLineDash?.([]);
1485
+
1486
+ const leftEdge = pt.x - box.halfW;
1487
+ const rightEdge = pt.x + box.halfW;
1488
+ const beeScale = narrow ? 0.85 : 0.92;
1489
+ const beeW = 20 * beeScale;
1490
+ const beeH = 18 * beeScale;
1491
+ drawBeeOnCtx(ctx, leftEdge + 10, pt.y - beeH / 2, node.name, {
1492
+ status: node.status ?? 'observer',
1493
+ coordinator: isCoord,
1494
+ tint: node.tint,
1495
+ muted: !isCoord && isDone,
1496
+ scale: beeScale,
1497
+ }, beesLib);
1498
+
1499
+ const labelText = node.name === 'user' ? 'You' : node.name === 'system' ? 'System' : node.name;
1500
+ const textX = (leftEdge + 10 + beeW + 6 + rightEdge - 14) / 2;
1501
+ ctx.fillStyle = isRetired ? palette.muted : palette.ink;
1502
+ ctx.font = '600 11px "Segoe UI", system-ui, sans-serif';
1503
+ const maxChars = Math.max(5, Math.floor((box.halfW * 2 - beeW - 28) / 6.2));
1504
+ const drawnLabel = truncateFit(labelText, maxChars);
1505
+ ctx.fillText(drawnLabel, textX, pt.y + 0.5);
1506
+
1507
+ if (isRetired) {
1508
+ const lineW = Math.min(box.halfW * 2 - beeW - 28, drawnLabel.length * 6.2);
1509
+ ctx.strokeStyle = palette.muted;
1510
+ ctx.lineWidth = 1;
1511
+ ctx.beginPath();
1512
+ ctx.moveTo(textX - lineW / 2, pt.y + 0.5);
1513
+ ctx.lineTo(textX + lineW / 2, pt.y + 0.5);
554
1514
  ctx.stroke();
555
- ctx.fillStyle=pulse ? color.accent : color.text;
556
- ctx.fillText(label,mid.x,mid.y+0.25);
557
1515
  }
1516
+
1517
+ // Status indicator dot at right end of pill.
1518
+ ctx.fillStyle = statusDotColor(node.status, palette);
1519
+ ctx.beginPath();
1520
+ ctx.arc(rightEdge - 10, pt.y, 3, 0, Math.PI * 2);
1521
+ ctx.fill();
1522
+ }
1523
+
1524
+ // Bottom legend matching Screenshot 2.
1525
+ ctx.globalAlpha = 1;
1526
+ const ly = height - 22;
1527
+ let lx = 24;
1528
+ ctx.textAlign = 'left';
1529
+ ctx.textBaseline = 'middle';
1530
+ ctx.font = '500 11px "Segoe UI", system-ui, sans-serif';
1531
+
1532
+ ctx.strokeStyle = palette.edge;
1533
+ ctx.fillStyle = palette.edge;
1534
+ ctx.lineWidth = 1.4;
1535
+ ctx.beginPath(); ctx.moveTo(lx, ly); ctx.lineTo(lx + 14, ly); ctx.stroke();
1536
+ drawArrowHead(ctx, lx + 18, ly, 0, 5);
1537
+ ctx.fillStyle = palette.muted;
1538
+ ctx.fillText('@mention, width = count', lx + 24, ly);
1539
+ lx += 168;
1540
+
1541
+ ctx.strokeStyle = palette.edge;
1542
+ ctx.fillStyle = palette.edge;
1543
+ ctx.setLineDash?.([3, 3]);
1544
+ ctx.beginPath(); ctx.moveTo(lx, ly); ctx.lineTo(lx + 14, ly); ctx.stroke();
1545
+ ctx.setLineDash?.([]);
1546
+ drawArrowHead(ctx, lx + 18, ly, 0, 5);
1547
+ ctx.fillStyle = palette.muted;
1548
+ ctx.fillText('via @all', lx + 24, ly);
1549
+ lx += 78;
1550
+
1551
+ ctx.strokeStyle = palette.border;
1552
+ ctx.setLineDash?.([2, 2]);
1553
+ pillPath(ctx, lx + 8, ly, 16, 10, 5);
1554
+ ctx.stroke();
1555
+ ctx.setLineDash?.([]);
1556
+ ctx.fillStyle = palette.muted;
1557
+ ctx.fillText('posted with no mention', lx + 22, ly);
1558
+
1559
+ if (projection.broadcasts > 0 && height >= 60) {
1560
+ const tag = '@all ' + projection.broadcasts;
1561
+ const by = height - 7;
1562
+ pillPath(ctx, 40, by - 1, 36, 14, 7);
1563
+ ctx.fillStyle = palette.border;
1564
+ ctx.fill();
1565
+ ctx.fillStyle = palette.ink;
1566
+ ctx.font = '600 9.5px ui-monospace, monospace';
1567
+ ctx.textAlign = 'center';
1568
+ ctx.fillText(tag, 40, by);
1569
+ ctx.textAlign = 'left';
1570
+ ctx.fillStyle = palette.muted;
1571
+ ctx.font = '500 10.5px "Segoe UI", system-ui, sans-serif';
1572
+ ctx.fillText('@all posts, drawn by Expand @all', 64, by);
1573
+ }
1574
+ }
1575
+
1576
+ function renderGraphFrame(ctx, opts = {}) {
1577
+ if (!ctx) return;
1578
+ const width = opts.width ?? 680;
1579
+ const height = opts.height ?? 460;
1580
+ const theme = opts.theme === 'dark' ? 'dark' : 'light';
1581
+ const mode = opts.mode === 'mentions' ? 'mentions' : 'hive';
1582
+ const palette = themePalette(theme);
1583
+ const beesLib = resolveBees(opts.bees);
1584
+
1585
+ ctx.save?.();
1586
+ ctx.clearRect?.(0, 0, width, height);
1587
+ ctx.fillStyle = palette.bg;
1588
+ ctx.fillRect(0, 0, width, height);
1589
+
1590
+ if (mode === 'mentions') {
1591
+ renderMentionsFrame(ctx, opts, palette, beesLib);
1592
+ } else {
1593
+ renderHiveFrame(ctx, opts, palette, beesLib);
558
1594
  }
559
- ctx.globalAlpha=1;
1595
+ ctx.restore?.();
560
1596
  }
561
1597
 
562
- globalThis.HiveGraph=Object.freeze({
563
- isPost,project,elapsedSpan,unmentionedNode,minimumHeight,layout,
564
- nodeBox,roundedRectSignedDistance,clipEdge,routeEdges,draw,
1598
+ globalThis.HiveGraph = Object.freeze({
1599
+ isPost, shouldMergeUserToCoordinator, project, elapsedSpan, unmentionedNode, minimumHeight, layout,
1600
+ nodeBox, roundedRectSignedDistance, clipEdge, routeEdges, draw,
1601
+ smartTaskLabel, mentionsMinimumHeight, layoutMentions,
1602
+ projectHive, hiveMinimumHeight, layoutHive, renderGraphFrame,
565
1603
  });
566
1604
  })();