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