lampson 0.4.1 → 0.5.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.
Files changed (69) hide show
  1. package/README.md +19 -0
  2. package/chat.syn +1 -1
  3. package/hub.tpl.syn +55 -12
  4. package/lampson.ps1 +13 -6
  5. package/lampson.sh +11 -5
  6. package/lib/api.syn +224 -9
  7. package/lib/apikeys.syn +42 -9
  8. package/lib/apptools.syn +549 -0
  9. package/lib/diagnose.syn +142 -0
  10. package/lib/loop.syn +27 -0
  11. package/lib/mailbox.syn +24 -10
  12. package/lib/mcp_server.syn +6 -5
  13. package/lib/permission.syn +22 -1
  14. package/lib/plugins.syn +6 -4
  15. package/lib/provider.syn +16 -13
  16. package/lib/remotetools.syn +76 -0
  17. package/lib/runtime.syn +213 -9
  18. package/lib/schedule.syn +40 -2
  19. package/lib/sdktools.syn +73 -0
  20. package/lib/session.syn +8 -0
  21. package/lib/teamrun.syn +42 -5
  22. package/lib/teams.syn +397 -24
  23. package/lib/tools/common.syn +5 -0
  24. package/lib/tools/url.syn +82 -9
  25. package/lib/workspaces.syn +87 -3
  26. package/lib/worktree.syn +108 -0
  27. package/package.json +2 -2
  28. package/plugins/example-hello/plugin.json +1 -0
  29. package/public/css/chat.css +9 -8
  30. package/public/css/hub.css +69 -16
  31. package/public/css/layout.css +12 -4
  32. package/public/css/login.css +1 -1
  33. package/public/css/mobile.css +2 -2
  34. package/public/css/panel.css +18 -7
  35. package/public/css/sidebar.css +1 -1
  36. package/public/css/teams.css +701 -55
  37. package/public/css/tokens.css +36 -12
  38. package/public/css/views.css +124 -0
  39. package/public/hub.html +17 -9
  40. package/public/index.html +5 -2
  41. package/public/js/app.js +2 -2
  42. package/public/js/approvals.js +1 -1
  43. package/public/js/apptools.js +63 -0
  44. package/public/js/core.js +5 -2
  45. package/public/js/flow.js +187 -0
  46. package/public/js/hub.js +131 -31
  47. package/public/js/navtabs.js +23 -0
  48. package/public/js/objdiag.js +90 -0
  49. package/public/js/objlive.js +393 -0
  50. package/public/js/panel.js +3 -2
  51. package/public/js/plugins-home.js +59 -0
  52. package/public/js/plugins.js +40 -18
  53. package/public/js/schedules.js +5 -0
  54. package/public/js/sidebar.js +6 -4
  55. package/public/js/tasks-home.js +104 -0
  56. package/public/js/teams-home.js +64 -15
  57. package/public/js/teams.js +927 -202
  58. package/public/js/terminal.js +8 -2
  59. package/public/js/workspaces.js +6 -3
  60. package/public/plugins-home.html +32 -0
  61. package/public/tasks-home.html +31 -0
  62. package/public/teams-home.html +5 -2
  63. package/public/teams.html +33 -46
  64. package/public/vendor/xterm-addon-webgl.js +2 -0
  65. package/run.syn +87 -6
  66. package/sdk/index.d.ts +64 -3
  67. package/sdk/index.js +253 -11
  68. package/skills/lampson/SKILL.md +15 -0
  69. package/web.syn +91 -12
@@ -0,0 +1,187 @@
1
+ // flow.js — un lienzo de nodos al estilo React Flow, sin dependencias (lo usa la pantalla de equipos, js/teams.js).
2
+ // Fondo de puntos; arrastrar el fondo lo desplaza, la rueda hace zoom; los nodos se arrastran y su posición se guarda
3
+ // en el navegador (opts.storeKey). Editando, cada nodo tiene un punto abajo: arrastrado hasta otro nodo, ese nodo pasa
4
+ // a reportarle (la jerarquía); soltado en el vacío, crea uno nuevo ahí que le reporta. Una conexión se elige con un
5
+ // clic y se quita con su ✕ o con Supr.
6
+ //
7
+ // const f = Flow.create(elemento)
8
+ // f.render({ nodes: [{id, title, desc, meta, lead, loose, avatar, working, missing, at}], edges: [{kind:'reports'|'talk', from, to, hot}],
9
+ // editable, selected, storeKey, onSelect(id|null), onConnect(from, to), onConnectEmpty(from, pos), onDeleteEdge(edge) })
10
+ // f.fit() · f.center(id) · f.freeSpot() → una posición libre para un nodo nuevo
11
+ const Flow = (() => {
12
+ const NW = 232, NH = 118, GAPX = 44, ROWH = 170;
13
+ const load = (k) => { try { return JSON.parse(localStorage.getItem(k) || '{}'); } catch (e) { return {}; } };
14
+ const save = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} };
15
+ const escH = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
16
+
17
+ // orden automático: niveles por jefe (raíces arriba), cada nivel centrado
18
+ function autoLayout(nodes, edges) {
19
+ const boss = {}; edges.filter((e) => e.kind === 'reports').forEach((e) => (boss[e.to] = e.from));
20
+ const level = {};
21
+ const lv = (id, seen = new Set()) => { if (level[id] !== undefined) return level[id]; const b = boss[id]; if (!b || seen.has(id) || !nodes.some((n) => n.id === b)) return (level[id] = 0); seen.add(id); return (level[id] = lv(b, seen) + 1); };
22
+ nodes.forEach((n) => lv(n.id));
23
+ const rows = {}; nodes.forEach((n) => (rows[level[n.id]] = rows[level[n.id]] || []).push(n.id));
24
+ const pos = {};
25
+ Object.entries(rows).forEach(([l, ids]) => ids.forEach((id, i) => (pos[id] = { x: (i - (ids.length - 1) / 2) * (NW + GAPX) - NW / 2, y: Number(l) * ROWH })));
26
+ return pos;
27
+ }
28
+
29
+ function create(root) {
30
+ root.classList.add('flow');
31
+ root.innerHTML = `<div class="fl-pane"><svg class="fl-edges"><g class="fl-e"></g><g class="fl-fx"></g><path class="fl-ghost" d=""/></svg><div class="fl-nodes"></div><svg class="fl-edges fl-top"><g class="fl-fx2"></g></svg><div class="fl-tools"></div></div>
32
+ <div class="fl-ctrl"><button type="button" data-z="in" title="acercar">+</button><button type="button" data-z="out" title="alejar">−</button><button type="button" data-z="fit" title="encuadrar todo">⤢</button><button type="button" data-z="tidy" title="ordenar automáticamente">ordenar</button></div>`;
33
+ const pane = root.querySelector('.fl-pane'), eg = root.querySelector('.fl-e'), fx = root.querySelector('.fl-fx'), fxTop = root.querySelector('.fl-fx2'), ghost = root.querySelector('.fl-ghost'), nodesEl = root.querySelector('.fl-nodes'), tools = root.querySelector('.fl-tools');
34
+ const st = { x: 0, y: 0, k: 1, pos: {}, opts: null, fitted: false, selEdge: null, key: '' };
35
+ const apply = () => { pane.style.transform = `translate(${st.x}px,${st.y}px) scale(${st.k})`; root.style.backgroundPosition = `${st.x}px ${st.y}px`; root.style.backgroundSize = `${20 * st.k}px ${20 * st.k}px`; };
36
+ const toPane = (cx, cy) => { const r = root.getBoundingClientRect(); return { x: (cx - r.left - st.x) / st.k, y: (cy - r.top - st.y) / st.k }; };
37
+ function zoomAt(f, cx, cy) {
38
+ const r = root.getBoundingClientRect(); const px = cx ?? r.left + r.width / 2, py = cy ?? r.top + r.height / 2;
39
+ const k = Math.min(1.6, Math.max(0.35, st.k * f)), p = toPane(px, py);
40
+ st.x = px - r.left - p.x * k; st.y = py - r.top - p.y * k; st.k = k; apply();
41
+ }
42
+ // encuadrar: todo a la vista, sin agrandar de más un equipo chico (un asiento solo no ocupa media pantalla)
43
+ function fit() {
44
+ const ids = (st.opts?.nodes || []).map((n) => n.id).filter((i) => st.pos[i]); if (!ids.length) return;
45
+ const xs = ids.map((i) => st.pos[i].x), ys = ids.map((i) => st.pos[i].y);
46
+ const minX = Math.min(...xs), maxX = Math.max(...xs) + NW, minY = Math.min(...ys), maxY = Math.max(...ys) + NH;
47
+ const r = root.getBoundingClientRect(), pad = 80;
48
+ const k = Math.min(1, Math.max(0.35, Math.min((r.width - pad * 2) / (maxX - minX), (r.height - pad * 2) / (maxY - minY))));
49
+ st.k = k; st.x = r.width / 2 - ((minX + maxX) / 2) * k; st.y = r.height / 2 - ((minY + maxY) / 2) * k; apply();
50
+ }
51
+ const anchor = (id, side) => { const p = st.pos[id]; return side === 'top' ? { x: p.x + NW / 2, y: p.y } : side === 'bottom' ? { x: p.x + NW / 2, y: p.y + NH } : side === 'left' ? { x: p.x, y: p.y + NH / 2 } : { x: p.x + NW, y: p.y + NH / 2 }; };
52
+ function edgePath(e) {
53
+ if (e.kind === 'reports') {
54
+ const a = anchor(e.from, 'bottom'), b = anchor(e.to, 'top'), dy = Math.max(40, Math.abs(b.y - a.y) / 2);
55
+ return { d: `M${a.x},${a.y} C${a.x},${a.y + dy} ${b.x},${b.y - dy} ${b.x},${b.y}`, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
56
+ }
57
+ const A = st.pos[e.from], B = st.pos[e.to];
58
+ if (Math.abs(A.x - B.x) >= NW * 0.75) {
59
+ const left = A.x < B.x, a = anchor(e.from, left ? 'right' : 'left'), b = anchor(e.to, left ? 'left' : 'right'), dx = Math.max(30, Math.abs(b.x - a.x) / 2) * (left ? 1 : -1);
60
+ return { d: `M${a.x},${a.y} C${a.x + dx},${a.y} ${b.x - dx},${b.y} ${b.x},${b.y}`, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
61
+ }
62
+ const a = anchor(e.from, 'right'), b = anchor(e.to, 'right'), out = Math.max(a.x, b.x) + 50 + Math.abs(a.y - b.y) * 0.1;
63
+ return { d: `M${a.x},${a.y} C${out},${a.y} ${out},${b.y} ${b.x},${b.y}`, mx: out - 12, my: (a.y + b.y) / 2 };
64
+ }
65
+ const ekey = (e) => e.kind + ':' + e.from + '>' + e.to;
66
+ // una curva cúbica «M a C c1 c2 b» al revés (para que la partícula salga del que manda)
67
+ const reversePath = (d) => { const n = d.match(/-?[\d.]+/g).map(Number); return `M${n[6]},${n[7]} C${n[4]},${n[5]} ${n[2]},${n[3]} ${n[0]},${n[1]}`; };
68
+ function drawEdges() {
69
+ const o = st.opts; if (!o) return;
70
+ eg.innerHTML = o.edges.filter((e) => st.pos[e.from] && st.pos[e.to]).map((e) => { const p = edgePath(e), k = ekey(e);
71
+ return `<g class="fl-edge ${e.kind}${e.hot ? ' hot' : ''}${st.selEdge === k ? ' sel' : ''}" data-k="${escH(k)}"><path class="hit" d="${p.d}"/><path class="line" d="${p.d}"/></g>`; }).join('');
72
+ const sel = o.editable && o.edges.find((e) => ekey(e) === st.selEdge);
73
+ tools.innerHTML = sel ? (() => { const p = edgePath(sel); return `<button type="button" class="fl-del" style="left:${p.mx}px;top:${p.my}px" title="quitar la conexión (Supr)">✕</button>`; })() : '';
74
+ const del = tools.querySelector('.fl-del'); if (del) del.onclick = (ev) => { ev.stopPropagation(); removeSel(); };
75
+ if (o.editable) eg.querySelectorAll('.fl-edge').forEach((g) => (g.onpointerdown = (ev) => { ev.stopPropagation(); st.selEdge = g.dataset.k; drawEdges(); }));
76
+ }
77
+ function removeSel() { const o = st.opts; const e = o && o.edges.find((x) => ekey(x) === st.selEdge); st.selEdge = null; if (e && o.onDeleteEdge) o.onDeleteEdge(e); else drawEdges(); }
78
+ function placeNodes() { nodesEl.querySelectorAll('.fl-node').forEach((el) => { const p = st.pos[el.dataset.id]; el.style.transform = `translate(${p.x}px,${p.y}px)`; }); }
79
+
80
+ // fondo: desplazar; un clic suelto deselecciona
81
+ root.addEventListener('pointerdown', (ev) => {
82
+ if (ev.target !== root && !ev.target.closest('.fl-pane')) return;
83
+ if (ev.target.closest('.fl-node, .fl-del, .fl-edge')) return;
84
+ const sx = ev.clientX - st.x, sy = ev.clientY - st.y, x0 = ev.clientX, y0 = ev.clientY; root.setPointerCapture(ev.pointerId); root.classList.add('panning');
85
+ if (st.selEdge) { st.selEdge = null; drawEdges(); }
86
+ const mv = (e) => { st.x = e.clientX - sx; st.y = e.clientY - sy; apply(); };
87
+ const up = (e) => { root.classList.remove('panning'); root.removeEventListener('pointermove', mv); root.removeEventListener('pointerup', up);
88
+ if (Math.hypot(e.clientX - x0, e.clientY - y0) < 4 && st.opts.onSelect) st.opts.onSelect(null); };
89
+ root.addEventListener('pointermove', mv); root.addEventListener('pointerup', up);
90
+ });
91
+ root.addEventListener('wheel', (ev) => { if (!ev.target.closest('.fl-pane') && ev.target !== root) return; ev.preventDefault(); zoomAt(ev.deltaY < 0 ? 1.1 : 1 / 1.1, ev.clientX, ev.clientY); }, { passive: false });
92
+ root.querySelector('.fl-ctrl').onclick = (ev) => { const z = ev.target.dataset.z; if (z === 'in') zoomAt(1.2); if (z === 'out') zoomAt(1 / 1.2); if (z === 'fit') fit();
93
+ if (z === 'tidy') { st.pos = autoLayout(st.opts.nodes, st.opts.edges); if (st.key) save(st.key, st.pos); placeNodes(); drawEdges(); fit(); } };
94
+ root.tabIndex = 0;
95
+ root.addEventListener('keydown', (ev) => { if ((ev.key === 'Delete' || ev.key === 'Backspace') && st.selEdge && st.opts?.editable && !ev.target.closest('input, textarea, select')) { ev.preventDefault(); removeSel(); } });
96
+
97
+ function bindNode(el) {
98
+ const id = el.dataset.id;
99
+ el.addEventListener('pointerdown', (ev) => {
100
+ const h = ev.target.closest('.fl-h');
101
+ ev.stopPropagation();
102
+ if (h) { connect(ev, id); return; }
103
+ // arrastrar el nodo (un clic sin moverse = elegirlo)
104
+ const start = toPane(ev.clientX, ev.clientY), p0 = { ...st.pos[id] }; let moved = false;
105
+ el.setPointerCapture(ev.pointerId);
106
+ const mv = (e) => { const p = toPane(e.clientX, e.clientY); if (!moved && Math.hypot(p.x - start.x, p.y - start.y) < 4) return; moved = true; el.classList.add('dragging');
107
+ st.pos[id] = { x: p0.x + p.x - start.x, y: p0.y + p.y - start.y }; el.style.transform = `translate(${st.pos[id].x}px,${st.pos[id].y}px)`; drawEdges(); };
108
+ const up = () => { el.removeEventListener('pointermove', mv); el.removeEventListener('pointerup', up); el.classList.remove('dragging');
109
+ if (moved) { if (st.key) save(st.key, st.pos); } else if (st.opts.onSelect) st.opts.onSelect(id); };
110
+ el.addEventListener('pointermove', mv); el.addEventListener('pointerup', up);
111
+ });
112
+ }
113
+ // arrastrar desde el punto de abajo: hasta otro nodo (le reporta) o al vacío (uno nuevo ahí)
114
+ function connect(ev, from) {
115
+ const a = anchor(from, 'bottom'); root.classList.add('connecting');
116
+ const mv = (e) => { const p = toPane(e.clientX, e.clientY); const dy = Math.max(30, Math.abs(p.y - a.y) / 2);
117
+ ghost.setAttribute('d', `M${a.x},${a.y} C${a.x},${a.y + dy} ${p.x},${p.y - dy} ${p.x},${p.y}`);
118
+ const over = document.elementFromPoint(e.clientX, e.clientY)?.closest('.fl-node');
119
+ nodesEl.querySelectorAll('.fl-node').forEach((n) => n.classList.toggle('target', n.dataset.id !== from && n === over)); };
120
+ const up = (e) => { window.removeEventListener('pointermove', mv); window.removeEventListener('pointerup', up); ghost.setAttribute('d', ''); root.classList.remove('connecting');
121
+ nodesEl.querySelectorAll('.target').forEach((n) => n.classList.remove('target'));
122
+ const t = document.elementFromPoint(e.clientX, e.clientY)?.closest('.fl-node');
123
+ if (t && t.dataset.id !== from) { st.opts.onConnect && st.opts.onConnect(from, t.dataset.id); return; }
124
+ const p = toPane(e.clientX, e.clientY);
125
+ if (!t && Math.hypot(p.x - a.x, p.y - a.y) > 40 && e.target.closest && root.contains(e.target) && st.opts.onConnectEmpty) st.opts.onConnectEmpty(from, { x: p.x - NW / 2, y: p.y }); };
126
+ window.addEventListener('pointermove', mv); window.addEventListener('pointerup', up);
127
+ }
128
+ // un lugar libre para un nodo nuevo: debajo de todo, centrado en lo visible
129
+ function freeSpot(under) {
130
+ if (under && st.pos[under]) { const kids = Object.values(st.pos).filter((p) => p.y > st.pos[under].y + NH && Math.abs(p.y - (st.pos[under].y + ROWH)) < NH);
131
+ const x = kids.length ? Math.max(...kids.map((p) => p.x)) + NW + GAPX : st.pos[under].x; return { x, y: st.pos[under].y + ROWH }; }
132
+ // suelto: desde el centro de lo visible, el primer lugar que no pise otra tarjeta (en espiral)
133
+ const r = root.getBoundingClientRect(), c = toPane(r.left + r.width / 2 - NW / 2 * st.k, r.top + r.height / 2 - NH / 2 * st.k);
134
+ const busy = (p) => Object.values(st.pos).some((q) => Math.abs(q.x - p.x) < NW + 16 && Math.abs(q.y - p.y) < NH + 16);
135
+ for (let ring = 0; ring < 8; ring++) for (let i = -ring; i <= ring; i++) for (const p of [{ x: c.x + i * (NW + GAPX), y: c.y + ring * (NH + 30) }, { x: c.x + ring * (NW + GAPX), y: c.y + i * (NH + 30) }, { x: c.x - ring * (NW + GAPX), y: c.y + i * (NH + 30) }]) if (!busy(p)) return p;
136
+ return c;
137
+ }
138
+
139
+ return {
140
+ render(o) {
141
+ const keyChanged = o.storeKey !== st.key; st.opts = o;
142
+ if (keyChanged) { st.key = o.storeKey || ''; st.pos = st.key ? load(st.key) : {}; st.fitted = false; st.selEdge = null; }
143
+ const auto = autoLayout(o.nodes, o.edges), ids = new Set(o.nodes.map((n) => n.id));
144
+ Object.keys(st.pos).forEach((i) => { if (!ids.has(i)) delete st.pos[i]; });
145
+ o.nodes.forEach((n) => { if (!st.pos[n.id]) st.pos[n.id] = n.at || auto[n.id]; });
146
+ if (st.key) save(st.key, st.pos);
147
+ root.classList.toggle('editable', !!o.editable);
148
+ nodesEl.innerHTML = o.nodes.map((n) => `<div class="fl-node${n.working ? ' working' : ''}${n.missing ? ' missing' : ''}${n.lead ? ' lead' : ''}${n.loose ? ' loose' : ''}${n.cls ? ' ' + escH(n.cls) : ''}${o.selected === n.id ? ' sel' : ''}" data-id="${escH(n.id)}">
149
+ <div class="fl-top"><span class="fl-av">${escH(n.avatar || n.title.slice(0, 1))}</span><b>${escH(n.title)}</b>${n.lead ? '<span class="fl-lead">líder</span>' : ''}<span class="fl-pip"></span></div>
150
+ ${n.html !== undefined ? n.html : `<p class="fl-desc">${escH(n.desc || '')}</p><span class="fl-meta">${escH(n.meta || '')}</span>`}
151
+ ${o.editable ? '<span class="fl-h top" aria-hidden="true"></span><span class="fl-h bottom" title="arrastrá hasta otro asiento: te reporta · soltalo en el vacío: un asiento nuevo"></span>' : ''}</div>`).join('');
152
+ nodesEl.querySelectorAll('.fl-node').forEach(bindNode);
153
+ placeNodes(); drawEdges();
154
+ if (!st.fitted) { st.fitted = true; requestAnimationFrame(fit); }
155
+ apply();
156
+ },
157
+ fit,
158
+ freeSpot,
159
+ // algo que viaja de un nodo a otro (la vista en vivo de un objetivo): por la línea que los une, si la hay; si no,
160
+ // por una curva directa. La línea se enciende del color de quien manda y corre como un flujo mientras el sobre
161
+ // (glyph: SVG centrado en 0,0) la recorre; al llegar, una onda en el destino. Vive en su propia capa (fl-fx),
162
+ // que el repintado no borra. opts: {color, glyph, dur (s)}
163
+ particle(from, to, opts = {}) {
164
+ if (!st.pos[from] || !st.pos[to] || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
165
+ const e = (st.opts.edges || []).find((x) => (x.from === from && x.to === to) || (x.from === to && x.to === from));
166
+ let d;
167
+ if (e) { d = edgePath(e).d; if (e.from !== from) d = reversePath(d); }
168
+ else { const a = anchor(from, 'bottom'), b = anchor(to, 'top'); d = `M${a.x},${a.y} C${a.x},${(a.y + b.y) / 2} ${b.x},${(a.y + b.y) / 2} ${b.x},${b.y}`; }
169
+ const dur = opts.dur || 1.6, end = d.match(/-?[\d.]+/g).map(Number).slice(-2);
170
+ // la línea encendida va debajo de las tarjetas; el sobre y la onda, encima (si no, la tarjeta lo tapa a la mitad)
171
+ const ns = 'http://www.w3.org/2000/svg', g = document.createElementNS(ns, 'g'), top = document.createElementNS(ns, 'g');
172
+ [g, top].forEach((x) => { x.setAttribute('class', 'fl-particle'); if (opts.color) x.style.setProperty('--flow', opts.color); x.style.setProperty('--dur', dur + 's'); });
173
+ g.innerHTML = `<path class="glow" d="${d}"/><path class="trail" d="${d}"/>`;
174
+ top.innerHTML = `<circle class="ripple" cx="${end[0]}" cy="${end[1]}" r="4"/>
175
+ <g class="glyph">${opts.glyph || '<circle r="6"/>'}<animateMotion dur="${dur}s" fill="freeze" path="${d}" calcMode="spline" keyTimes="0;1" keySplines="0.45 0 0.25 1"/></g>`;
176
+ fx.appendChild(g); fxTop.appendChild(top); setTimeout(() => { g.remove(); top.remove(); }, dur * 1000 + 1200);
177
+ },
178
+ // al unir: si el que pasa a reportar quedó arriba (o a la par) de su jefe, va debajo de él — la línea no da vueltas
179
+ placeUnder(child, boss) {
180
+ const c = st.pos[child], b = st.pos[boss]; if (!c || !b || c.y >= b.y + NH + 20) return false;
181
+ delete st.pos[child]; st.pos[child] = freeSpot(boss); if (st.key) save(st.key, st.pos); return true;
182
+ },
183
+ center(id) { const p = st.pos[id]; if (!p) return; const r = root.getBoundingClientRect(); st.x = r.width / 2 - (p.x + NW / 2) * st.k; st.y = r.height / 2 - (p.y + NH / 2) * st.k; apply(); },
184
+ };
185
+ }
186
+ return { create };
187
+ })();
package/public/js/hub.js CHANGED
@@ -19,38 +19,138 @@ const MOON = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke
19
19
  function paintTheme() { const light = document.documentElement.getAttribute('data-theme') === 'light'; $('#theme').innerHTML = light ? MOON : SUN; }
20
20
  $('#theme').onclick = () => { const r = document.documentElement; r.setAttribute('data-theme', r.getAttribute('data-theme') === 'light' ? 'dark' : 'light'); try { localStorage.setItem('lampson.theme', r.getAttribute('data-theme')); } catch (e) {} paintTheme(); };
21
21
  paintTheme();
22
- // tarjetas
23
- async function paintGrid() {
24
- const grid = $('#wsGrid'); let r; try { r = await (await fetch(BASE + '/api/workspaces')).json(); } catch (e) { grid.innerHTML = '<div class="card"><p>el hub no responde</p></div>'; return; }
25
- grid.innerHTML = '';
26
- for (const w of (r.workspaces || [])) {
27
- const c = document.createElement('a'); c.className = 'card ws' + (w.alive ? ' on' : ' off'); c.href = w.url;
28
- const t = w.teams || {};
29
- const tline = (t.teams || t.active || t.waiting) ? `<p class="tm" data-href="${esc(w.url)}/equipos">${t.teams ? '◇ ' + t.teams + (t.teams === 1 ? ' equipo' : ' equipos') : '◇ objetivos'}${t.active ? ' · ' + t.active + ' trabajando' : ''}${t.waiting ? ' · <b>⚑ ' + t.waiting + ' te espera' + (t.waiting === 1 ? '' : 'n') + '</b>' : ''}</p>` : '';
30
- c.innerHTML = `<h3>${w.alive ? '● vivo' : '○ apagado'}${w.schedules_on ? ' · ⏰ ' + w.schedules_on : ''}</h3><p class="nm">${esc(w.name)}</p><p class="pth">${esc(w.path)}</p><p class="meta">último uso ${esc(fmtWhen(w.last_used))}</p>${tline}`;
31
- const tm = c.querySelector('.tm');
32
- if (tm) tm.onclick = (e) => { e.preventDefault(); e.stopPropagation(); location.href = tm.dataset.href; };
33
- // entrar = usarlo: si está apagado se enciende acá mismo (con aviso en la tarjeta) y después se abre. La ruta
34
- // /w/<slug> del hub también lo enciende sola, así que un link directo funciona igual; esto solo da feedback.
35
- if (!w.alive) c.onclick = async (e) => {
36
- e.preventDefault(); if (c.dataset.busy) return; c.dataset.busy = '1';
37
- const h = c.querySelector('h3'); h.textContent = '⟳ encendiendo…'; c.classList.add('busy');
38
- try { const r = await api('/api/workspaces/start', { slug: w.slug }); if (!r.ok || !r.data.ok) { h.textContent = '○ no arrancó · mirá .lampson/ws/' + w.slug + '/.lampson/web.log'; c.classList.remove('busy'); delete c.dataset.busy; return; } } catch (err) {}
39
- location.href = w.url;
40
- };
41
- grid.appendChild(c);
22
+ // tarjetas: «necesita tu atención» arriba, después activos, recientes y los más antiguos plegados
23
+ const OLD_DAYS = 14;
24
+ let wsData = null, teamsData = null, tasksData = null, pluginsData = null, oldOpen = false;
25
+ function escA(s) { return esc(s).replace(/"/g, '&quot;'); }
26
+ // «hace 3 h» se lee de un vistazo; la fecha exacta queda en el title
27
+ function fmtAgo(ts) {
28
+ if (!ts) return 'sin uso todavía';
29
+ const m = Math.floor((Date.now() / 1000 - ts) / 60), h = Math.floor(m / 60), d = Math.floor(h / 24);
30
+ if (m < 1) return 'usado recién'; if (m < 60) return `usado hace ${m} min`; if (h < 24) return `usado hace ${h} h`;
31
+ if (d < 2) return 'usado ayer'; if (d < 7) return `usado hace ${d} días`; if (d < 30) return `usado hace ${Math.floor(d / 7)} sem`;
32
+ return 'usado el ' + new Date(ts * 1000).toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
33
+ }
34
+ // la carpeta del usuario como ~ (la ruta completa queda en el title)
35
+ function shortPath(p) { return String(p || '').replace(/^[a-z]:\\users\\[^\\]+/i, '~').replace(/^\/(home|Users)\/[^/]+/, '~'); }
36
+ function wsCard(w) {
37
+ const c = document.createElement('a'); c.className = 'card ws' + (w.alive ? ' on' : ' off'); c.href = w.url;
38
+ const t = w.teams || {};
39
+ const tline = (t.teams || t.active || t.waiting) ? `<p class="tm" data-href="${escA(w.url)}/equipos">${t.teams ? '◇ ' + t.teams + (t.teams === 1 ? ' equipo' : ' equipos') : '◇ objetivos'}${t.active ? ' · ' + t.active + ' trabajando' : ''}${t.waiting ? ' · <b>⚑ ' + t.waiting + ' te espera' + (t.waiting === 1 ? '' : 'n') + '</b>' : ''}</p>` : '';
40
+ c.innerHTML = `<h3><span class="st">${w.alive ? '● activo' : '○ apagado'}${w.schedules_on ? ' · ⏰ ' + w.schedules_on : ''}</span><span class="more" role="button" tabindex="0" title="encender, apagar, política de vida, quitar" aria-label="opciones de ${escA(w.name)}">⋯</span></h3><p class="nm">${esc(w.name)}</p><p class="pth" title="${escA(w.path)}">${esc(shortPath(w.path))}</p><p class="meta" title="último uso ${escA(fmtWhen(w.last_used))}">${esc(fmtAgo(w.last_used))}</p>${tline}`;
41
+ const tm = c.querySelector('.tm');
42
+ if (tm) tm.onclick = (e) => { e.preventDefault(); e.stopPropagation(); location.href = tm.dataset.href; };
43
+ const more = c.querySelector('.more');
44
+ more.onclick = (e) => { e.preventDefault(); e.stopPropagation(); openWorkspaces(w.slug); };
45
+ more.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') more.onclick(e); };
46
+ // entrar = usarlo: si está apagado se enciende acá mismo (con aviso en la tarjeta) y después se abre. La ruta
47
+ // /w/<slug> del hub también lo enciende sola, así que un link directo funciona igual; esto solo da feedback.
48
+ if (!w.alive) c.onclick = async (e) => {
49
+ e.preventDefault(); if (c.dataset.busy) return; c.dataset.busy = '1';
50
+ const h = c.querySelector('.st'); h.textContent = '⟳ encendiendo…'; c.classList.add('busy');
51
+ try { const r = await api('/api/workspaces/start', { slug: w.slug }); if (!r.ok || !r.data.ok) { h.textContent = '○ no arrancó · mirá .lampson/ws/' + w.slug + '/.lampson/web.log'; c.classList.remove('busy'); delete c.dataset.busy; return; } } catch (err) {}
52
+ location.href = w.url;
53
+ };
54
+ return c;
55
+ }
56
+ function wsGroup(title, list) {
57
+ const sec = document.createElement('section'); sec.className = 'wsgroup';
58
+ sec.innerHTML = `<p class="ghead">${esc(title)} <span class="n">${list.length}</span></p><div class="wsgrid"></div>`;
59
+ const grid = sec.querySelector('.wsgrid'); for (const w of list) grid.appendChild(wsCard(w));
60
+ return sec;
61
+ }
62
+ // cuántas cosas te esperan en un proyecto: preguntas de objetivos y aprobaciones de sus agentes (/api/teams-home);
63
+ // sin ese resumen, el conteo de /api/workspaces
64
+ function waitingIn(w) {
65
+ const tw = teamsData && teamsData.find(x => x.slug === w.slug);
66
+ if (tw) return tw.objectives.filter(o => o.status === 'waiting').length + (tw.approvals || []).length;
67
+ return (w.teams || {}).waiting || 0;
68
+ }
69
+ // los productos de lampson en el inicio: un mosaico de alto fijo por producto (equipos, tareas, plugins) que lleva a
70
+ // su pestaña. No crece con la cantidad de equipos o tareas, así los proyectos siguen a la vista; sin uso todavía,
71
+ // el mosaico es la invitación.
72
+ function fmtNext(ts) {
73
+ if (!ts) return '';
74
+ const d = new Date(ts * 1000), now = new Date(), hm = d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
75
+ const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime(), diff = Math.round((day(d) - day(now)) / 86400000);
76
+ return diff === 0 ? 'hoy ' + hm : diff === 1 ? 'mañana ' + hm : d.toLocaleDateString(undefined, { weekday: 'short' }) + ' ' + hm;
77
+ }
78
+ function tile(ic, title, main, sub, href, cta, cls) {
79
+ return `<a class="tile${cls ? ' ' + cls : ''}" href="${escA(href)}"><p class="th"><span class="ic">${ic}</span>${esc(title)}</p><p class="tm1">${main}</p><p class="tm2">${sub}</p><p class="go">${esc(cta)} →</p></a>`;
80
+ }
81
+ function paintTiles(q) {
82
+ const box = $('#wsTiles');
83
+ if (q) { box.innerHTML = ''; return; }
84
+ const out = [];
85
+ // equipos
86
+ if (teamsData) {
87
+ const nT = teamsData.reduce((n, w) => n + w.teams.length, 0);
88
+ const act = teamsData.reduce((n, w) => n + w.objectives.filter(o => o.status === 'active').length, 0);
89
+ const wait = teamsData.reduce((n, w) => n + w.objectives.filter(o => o.status === 'waiting').length + (w.approvals || []).length, 0);
90
+ const solo = teamsData.reduce((n, w) => n + w.objectives.filter(o => !o.team && (o.status === 'active' || o.status === 'waiting')).length, 0);
91
+ out.push(nT || solo
92
+ ? tile('◇', 'Equipos', nT ? `${nT} equipo${nT === 1 ? '' : 's'}` : `${solo} agente${solo === 1 ? '' : 's'} con objetivo`, wait ? `<b class="warn">⚑ ${wait} te espera${wait === 1 ? '' : 'n'}</b>${act ? ' · ' + act + ' trabajando' : ''}` : act ? `${act} trabajando` : 'nada pendiente', '/equipos', 'ver equipos')
93
+ : tile('◇', 'Equipos', 'Agentes que trabajan solos', 'Armá un equipo con roles, dale un objetivo y avanza mientras hacés otra cosa.', '/equipos?new=1', 'armar un equipo', 'invite'));
42
94
  }
43
- // equipos y objetivos de todos los proyectos (/equipos): lo que te espera de un vistazo, y «+ equipo»
44
- const tot = (r.workspaces || []).reduce((acc, w) => { const t = w.teams || {}; acc.teams += t.teams || 0; acc.active += t.active || 0; acc.waiting += t.waiting || 0; return acc; }, { teams: 0, active: 0, waiting: 0 });
45
- const tc = document.createElement('a'); tc.className = 'card ws teamscard' + (tot.waiting ? ' wait' : ''); tc.href = '/equipos';
46
- tc.innerHTML = `<h3>◇ equipos y objetivos</h3><p class="nm">${tot.waiting ? '⚑ ' + tot.waiting + ' te espera' + (tot.waiting === 1 ? '' : 'n') : tot.active ? tot.active + ' trabajando' : 'agentes que trabajan solos'}</p><p class="pth">${tot.teams ? tot.teams + (tot.teams === 1 ? ' equipo' : ' equipos') + ' en tus proyectos' : 'armá un equipo con roles o dale un objetivo a un agente'}</p>`;
47
- grid.appendChild(tc);
48
- const add = document.createElement('a'); add.className = 'card ws new'; add.href = '#'; add.innerHTML = '<h3>+</h3><p class="nm">nuevo workspace</p><p class="pth">elegí una carpeta de tu disco</p>';
49
- add.onclick = (e) => { e.preventDefault(); openWorkspaces('__new'); };
50
- grid.appendChild(add);
51
- const all = document.createElement('a'); all.className = 'card ws'; all.href = '#'; all.innerHTML = '<h3>⌕</h3><p class="nm">gestionar</p><p class="pth">encender, apagar, política de vida, quitar</p>';
52
- all.onclick = (e) => { e.preventDefault(); openWorkspaces(); };
53
- grid.appendChild(all);
95
+ // tareas programadas
96
+ if (tasksData) {
97
+ const all = tasksData.flatMap(w => w.tasks.map(t => ({ ...t, ws: w })));
98
+ const on = all.filter(t => t.enabled), failed = on.filter(t => String(t.last_status || '').startsWith('error'));
99
+ const next = on.filter(t => t.next_run).sort((a, b) => a.next_run - b.next_run)[0];
100
+ const off = all.length - on.length, pl = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
101
+ out.push(!all.length
102
+ ? tile('◷', 'Tareas', 'El agente trabaja a su hora', '«Todos los días a las 9, corré los tests y avisame si algo se rompió.»', '/tareas', 'ver cómo', 'invite')
103
+ : !on.length
104
+ ? tile('◷', 'Tareas', `${pl(all.length, 'tarea')}, ${all.length === 1 ? 'apagada' : 'apagadas'}`, 'ninguna va a correr hasta que la enciendas', '/tareas', 'ver tareas')
105
+ : tile('◷', 'Tareas', `${pl(on.length, 'programada')}${off ? ` <span class="dim">· ${pl(off, 'apagada')}</span>` : ''}`, failed.length ? `<b class="warn">✕ ${failed.length} falló en la última corrida</b>` : next ? `próxima: ${esc(fmtNext(next.next_run))} · ${esc(next.ws.name)}` : 'ninguna por correr', '/tareas', 'ver tareas'));
106
+ }
107
+ // plugins: lo instalado y dónde se usa (encender es por proyecto, dentro del proyecto)
108
+ if (pluginsData) {
109
+ const names = new Set(pluginsData.global.filter(p => !p.example).map(p => p.name)); pluginsData.workspaces.forEach(w => w.local.filter(p => !p.example).forEach(p => names.add(p.name)));
110
+ const used = pluginsData.workspaces.filter(w => w.enabled.some(n => names.has(n))).length;
111
+ const shown = [...names], list = shown.slice(0, 3).join(', ') + (shown.length > 3 ? ` y ${shown.length - 3} más` : '');
112
+ out.push(used
113
+ ? tile('⧉', 'Plugins', `${names.size} instalado${names.size === 1 ? '' : 's'}`, `encendidos en ${used} de ${pluginsData.workspaces.length} proyectos`, '/plugins', 'ver plugins')
114
+ : tile('⧉', 'Plugins', 'Sumale cosas a tus agentes', shown.length ? `Conectá ${esc(list)} a un proyecto.` : 'Canales, herramientas y datos para tus agentes.', '/plugins', 'ver plugins', 'invite'));
115
+ }
116
+ box.innerHTML = out.join('');
117
+ }
118
+ function paintHome() {
119
+ const attn = $('#wsAttn'), box = $('#wsGroups');
120
+ if (!wsData) { attn.innerHTML = ''; $('#wsTiles').innerHTML = ''; box.innerHTML = '<p class="none">el hub no responde</p>'; return; }
121
+ const all = (wsData.workspaces || []).slice().sort((a, b) => (b.last_used || 0) - (a.last_used || 0));
122
+ // lo que te espera, de todos los proyectos (la búsqueda no lo esconde); el total va también en la pestaña equipos
123
+ const waiting = all.map(w => ({ w, n: waitingIn(w) })).filter(x => x.n);
124
+ attn.innerHTML = waiting.length ? `<p class="ghead warn">Necesita tu atención</p>` + waiting.map(({ w, n }) => `<a class="attn" href="/equipos"><span class="ic">⚑</span><span class="tx"><b>${esc(w.name)}</b> · ${n === 1 ? 'una cosa te espera' : n + ' cosas te esperan'}</span><span class="go">responder →</span></a>`).join('') : '';
125
+ const q = ($('#wsSearch').value || '').trim().toLowerCase();
126
+ paintTiles(q);
127
+ const list = q ? all.filter(w => (w.name + ' ' + w.path).toLowerCase().includes(q)) : all;
128
+ box.innerHTML = '';
129
+ if (!list.length) { box.innerHTML = q ? `<p class="none">ningún proyecto coincide con «${esc(q)}»</p>` : '<p class="none">Todavía no hay proyectos: creá uno con «+ nuevo proyecto».</p>'; return; }
130
+ const cut = Date.now() / 1000 - OLD_DAYS * 86400;
131
+ const active = list.filter(w => w.alive), recent = list.filter(w => !w.alive && (w.last_used || 0) >= cut), old = list.filter(w => !w.alive && (w.last_used || 0) < cut);
132
+ if (active.length) box.appendChild(wsGroup('Activos', active));
133
+ if (recent.length) box.appendChild(wsGroup('Recientes', recent));
134
+ if (old.length) {
135
+ const det = document.createElement('details'); det.className = 'wsgroup old'; det.open = oldOpen || !!q;
136
+ det.innerHTML = `<summary class="ghead">Más antiguos <span class="n">${old.length}</span></summary><div class="wsgrid"></div>`;
137
+ const grid = det.querySelector('.wsgrid'); for (const w of old) grid.appendChild(wsCard(w));
138
+ det.ontoggle = () => { if (!q) oldOpen = det.open; };
139
+ box.appendChild(det);
140
+ }
141
+ }
142
+ async function paintGrid() {
143
+ const get = (u) => fetch(BASE + u).then(r => r.ok ? r.json() : null).catch(() => null);
144
+ const [ws, th, ta, pl] = await Promise.all([get('/api/workspaces'), get('/api/teams-home'), get('/api/tasks-home'), get('/api/plugins-home')]);
145
+ wsData = ws; teamsData = th ? (th.workspaces || []) : null; tasksData = ta ? (ta.workspaces || []) : null; pluginsData = pl && pl.global ? pl : null;
146
+ paintHome();
54
147
  }
148
+ $('#wsSearch').oninput = paintHome;
149
+ $('#wsNew').onclick = () => openWorkspaces('__new');
150
+ $('#wsManage').onclick = () => openWorkspaces();
151
+ document.querySelectorAll('.cli .copy').forEach(el => {
152
+ const go = async () => { try { await navigator.clipboard.writeText(el.dataset.copy); el.textContent = 'copiado'; } catch (e) { el.textContent = 'no se pudo copiar'; } setTimeout(() => { el.textContent = 'copiar'; }, 1500); };
153
+ el.onclick = go; el.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } };
154
+ });
55
155
  paintGrid();
56
156
  setInterval(paintGrid, 10000);
@@ -0,0 +1,23 @@
1
+ // navtabs.js — las pestañas del hub (proyectos · equipos · tareas · plugins), iguales en las cuatro pantallas.
2
+ // Cada página pone <nav class="navtabs" data-on="<pestaña>"></nav>; esto las dibuja y les pone los contadores:
3
+ // ⚑ lo que te espera en equipos (preguntas y aprobaciones) y ✕ las tareas cuya última corrida falló.
4
+ (function () {
5
+ const nav = document.querySelector('nav.navtabs'); if (!nav) return;
6
+ const TABS = [['proyectos', '/', 'tus proyectos'], ['equipos', '/equipos', 'equipos y objetivos de todos tus proyectos'], ['tareas', '/tareas', 'tareas programadas de todos tus proyectos'], ['plugins', '/plugins', 'lo que podés sumarle a tus agentes']];
7
+ const on = nav.dataset.on;
8
+ nav.innerHTML = TABS.map(([id, href, title]) => `<a href="${href}" title="${title}"${id === on ? ' class="on" aria-current="page"' : ''}>${id}<span class="badge" data-badge="${id}" hidden></span></a>`).join('');
9
+ const badge = (id, text) => { const b = nav.querySelector(`[data-badge="${id}"]`); b.hidden = !text; b.textContent = text || ''; };
10
+ async function paint() {
11
+ try {
12
+ const t = await (await fetch('/api/teams-home')).json();
13
+ const n = (t.workspaces || []).reduce((s, w) => s + w.objectives.filter(o => o.status === 'waiting').length + (w.approvals || []).length, 0);
14
+ badge('equipos', n ? '⚑ ' + n : '');
15
+ } catch (e) {}
16
+ try {
17
+ const t = await (await fetch('/api/tasks-home')).json();
18
+ const n = (t.workspaces || []).reduce((s, w) => s + w.tasks.filter(x => x.enabled && String(x.last_status || '').startsWith('error')).length, 0);
19
+ badge('tareas', n ? '✕ ' + n : '');
20
+ } catch (e) {}
21
+ }
22
+ paint(); setInterval(paint, 15000);
23
+ })();
@@ -0,0 +1,90 @@
1
+ // objdiag.js — «Revisar qué pasa» en un objetivo de equipo (lo abre el botón de la cabecera, o el aviso «parece
2
+ // trabado» de la vista en vivo). Tres partes:
3
+ // · lo que se ve (api/objectives/:id/facts, lib/diagnose.syn → facts): quién está bloqueado y por qué, quién
4
+ // contestó en su respuesta final que nadie lee, quién se quedó sin pasos, si el equipo cree que alguien no tiene
5
+ // presupuesto — cada cosa con su arreglo a mano (desbloquear la tarea, escribirle al asiento)
6
+ // · el análisis con IA (api/objectives/:id/diagnose): qué pasó y qué hacer, con acciones que se aplican con un botón
7
+ // · escribirle a cualquier asiento: le llega como un mensaje tuyo y le da un turno
8
+ // done: lo que ya aplicaste (por objetivo), así un botón no manda dos veces ni reaparece al redibujar
9
+ const DIAG = { facts: {}, ai: {}, at: {}, drawn: null, busy: false, done: {} };
10
+ const diagDone = (o) => DIAG.done[o.id] || (DIAG.done[o.id] = new Set());
11
+ const DIAG_ICON = '<svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l5.5 5.5"/><path d="M8 10.5h5M10.5 8v5"/></svg>';
12
+
13
+ async function diagFacts(o, force) {
14
+ if (!o.team) return [];
15
+ if (!force && DIAG.facts[o.id] && Date.now() - (DIAG.at[o.id] || 0) < 15000) return DIAG.facts[o.id];
16
+ const r = await api(`objectives/${o.id}/facts`);
17
+ DIAG.facts[o.id] = r.ok ? r.data.facts : []; DIAG.at[o.id] = Date.now();
18
+ return DIAG.facts[o.id];
19
+ }
20
+ // cada hecho, en palabras de la persona, con su arreglo
21
+ function factView(o, f) {
22
+ const role = (a) => ((o.seats || []).find((s) => s.agent === a) || {}).role || a;
23
+ const quote = (String(f.text).match(/«([\s\S]*)»/) || [])[1] || '';
24
+ const after = String(f.text).replace(/^[^:]*:\s*/, '');
25
+ const msg = (agent, text) => `<button type="button" data-dmsg="${esc(agent)}" data-dtext="${esc(text)}">Escribirle a ${esc(role(agent))}</button>`;
26
+ const unblock = f.task ? `<button type="button" class="primary" data-dtask="${f.task}" data-dstatus="todo">Desbloquear #${f.task}</button>` : '';
27
+ if (f.kind === 'quiet') return { tone: 'warn', html: `Nadie trabaja y no se mueve nada hace ${esc((f.text.match(/(\d+) min/) || [])[1] || '?')} min.`, acts: msg(o.agent, 'El equipo está quieto. Mirá el tablero: ¿quién tiene que hacer qué ahora? Destrabalo y avisame si necesitás algo de mí.') };
28
+ if (f.kind === 'budget_belief') return { tone: 'bad', html: `#${f.task} espera que <b>${esc(role(f.agent))}</b> «tenga presupuesto», pero <b>sí puede trabajar</b>: mientras el objetivo tenga presupuesto, sigue recibiendo turnos aunque pase su tope diario.`,
29
+ acts: unblock + msg(f.agent, `Sí tenés presupuesto: mientras este objetivo tenga, seguís trabajando aunque pases tu tope diario. Retomá #${f.task} donde quedaste, terminalo, commiteá y avisale a tu jefe con send.`) };
30
+ if (f.kind === 'blocked') return { tone: '', html: `#${f.task} está bloqueada${after ? ': ' + esc(short(after, 220)) : '.'}`, acts: unblock };
31
+ if (f.kind === 'waits') return { tone: '', html: `#${f.task} espera a ${esc((f.text.match(/waits for (#\d+)/) || [])[1] || 'otra')}, que está bloqueada.`, acts: '' };
32
+ if (f.kind === 'unsent') return { tone: 'bad', html: `<b>${esc(role(f.agent))}</b> contestó en su respuesta final, que nadie lee: <q>${esc(short(quote, 260))}</q>`,
33
+ acts: msg(f.agent, 'Lo que contestaste en tu último turno no le llegó a nadie: la respuesta final no se entrega. Mandáselo a tu jefe con send y seguí con tu tarea.') };
34
+ if (f.kind === 'cut') return { tone: 'warn', html: `A <b>${esc(role(f.agent))}</b> se le cortó el último turno (${f.text.includes('budget') ? 'sin tokens del turno' : 'sin pasos'})${quote ? ': <q>' + esc(short(quote, 200)) + '</q>' : '.'}`,
35
+ acts: msg(f.agent, `Se te cortó el turno. Seguí donde quedaste${f.task ? ' con #' + f.task : ''}, sin empezar de nuevo, y avisale a tu jefe con send cuando termines.`) };
36
+ return { tone: '', html: esc(f.text), acts: '' };
37
+ }
38
+ function diagHtml(o, facts) {
39
+ const seats = o.seats || [], ai = DIAG.ai[o.id], done = diagDone(o);
40
+ const applied = (k, what) => `<p class="dg-done">✓ ${what}</p>`;
41
+ const fv = facts.map((f) => factView(o, f));
42
+ return `<section class="dg-sec"><h4>Lo que se ve</h4>${fv.length ? `<ul class="dg-facts">${fv.map((v) => `<li class="${v.tone}"><p>${v.html}</p>${v.acts ? `<div class="dg-acts">${v.acts}</div>` : ''}</li>`).join('')}</ul>` : '<p class="ihint">No se ve nada trabado: si igual no avanza, pedí el análisis.</p>'}</section>
43
+ <section class="dg-sec"><h4>Análisis con IA</h4>${ai ? (ai.error ? `<p class="ferr">${esc(ai.error)}</p>` : `<div class="dg-sum">${reportHtml(ai.summary)}</div>${(ai.actions || []).map((a, i) => done.has('ai' + i) ? `<div class="dg-act done"><p class="dg-why">${esc(a.why || '')}</p>${applied('ai' + i, a.kind === 'message' ? 'Mandado a ' + esc(((seats.find((s) => s.agent === a.agent) || {}).role) || a.agent) : 'Movida #' + esc(a.task))}</div>` : a.kind === 'message'
44
+ ? `<div class="dg-act"><p class="dg-why">${esc(a.why || '')}</p><label>Mensaje para <b>${esc(((seats.find((s) => s.agent === a.agent) || {}).role) || a.agent)}</b><textarea rows="3" data-aitext="${i}">${esc(a.text || '')}</textarea></label><button type="button" class="primary" data-aimsg="${i}">Mandárselo</button></div>`
45
+ : `<div class="dg-act"><p class="dg-why">${esc(a.why || '')}</p><button type="button" class="primary" data-ai="${i}" data-dtask="${esc(a.task)}" data-dstatus="${esc(a.status)}">Mover #${esc(a.task)} a «${esc(LANES.find(([st]) => st === a.status)?.[1] || a.status)}»</button></div>`).join('')}<p class="dg-model">${esc(ai.model || '')}</p>`) : ''}
46
+ <button type="button" id="dgAi" ${DIAG.busy ? 'disabled' : ''}>${DIAG.busy ? 'analizando… (puede tardar un minuto)' : ai ? 'Analizar de nuevo' : 'Analizar con IA'}</button>
47
+ <p class="ds">Le pasa al modelo el tablero, el registro y el último turno de cada asiento, y te dice qué pasó y qué conviene hacer.</p></section>
48
+ <section class="dg-sec"><h4>Escribirle a un asiento</h4>
49
+ <div class="dg-write"><select id="dgTo">${seats.map((s) => `<option value="${esc(s.agent)}" ${s.lead ? 'selected' : ''}>${esc(s.role || s.agent)}${s.lead ? ' (líder)' : ''}</option>`).join('')}</select>
50
+ <textarea id="dgText" rows="3" placeholder="Le llega como un mensaje tuyo y le da un turno"></textarea><button type="button" class="primary" id="dgSend">Mandar</button></div><p class="ferr" id="dgErr"></p></section>`;
51
+ }
52
+ async function renderDiag(o, force) {
53
+ const box = $('#odSeat');
54
+ if (!force && DIAG.drawn === o.id) return;
55
+ DIAG.drawn = o.id;
56
+ const facts = await diagFacts(o, force);
57
+ box.innerHTML = diagHtml(o, facts);
58
+ const finish = (btn, txt) => { btn.textContent = txt; setTimeout(() => { DIAG.at[o.id] = 0; renderDiag(o, true); }, 1200); };
59
+ // key: qué se aplicó (para no repetirlo); el botón queda desactivado desde el primer clic
60
+ const act = async (body, btn, okText, key) => {
61
+ if (btn.disabled || (key && diagDone(o).has(key))) return;
62
+ btn.disabled = true;
63
+ const r = await api(`objectives/${o.id}/act`, body);
64
+ if (!r.ok) { btn.disabled = false; $('#dgErr').textContent = (r.data && r.data.error) || 'no se pudo'; return; }
65
+ if (key) diagDone(o).add(key);
66
+ finish(btn, okText); refresh();
67
+ };
68
+ // escribirle: el botón llena el formulario de abajo (lo podés editar antes de mandarlo)
69
+ box.querySelectorAll('[data-dmsg]').forEach((b) => (b.onclick = () => { $('#dgTo').value = b.dataset.dmsg; $('#dgText').value = b.dataset.dtext; $('#dgText').focus(); $('#dgText').scrollIntoView({ block: 'center', behavior: 'smooth' }); }));
70
+ box.querySelectorAll('[data-dtask]').forEach((b) => (b.onclick = () => act({ kind: 'task', task: +b.dataset.dtask, status: b.dataset.dstatus }, b, 'listo ✓', b.dataset.ai ? 'ai' + b.dataset.ai : 'task' + b.dataset.dtask + b.dataset.dstatus)));
71
+ box.querySelectorAll('[data-aimsg]').forEach((b) => (b.onclick = () => { const a = DIAG.ai[o.id].actions[+b.dataset.aimsg]; act({ kind: 'message', agent: a.agent, text: box.querySelector(`[data-aitext="${b.dataset.aimsg}"]`).value }, b, 'mandado ✓', 'ai' + b.dataset.aimsg); }));
72
+ $('#dgSend').onclick = async () => { const t = $('#dgText').value.trim(); if (!t) { $('#dgText').focus(); return; } await act({ kind: 'message', agent: $('#dgTo').value, text: t }, $('#dgSend'), 'mandado ✓'); $('#dgText').value = ''; };
73
+ $('#dgAi').onclick = async () => {
74
+ DIAG.busy = true; renderDiag(o, true);
75
+ const r = await api(`objectives/${o.id}/diagnose`, {});
76
+ DIAG.busy = false; DIAG.done[o.id] = new Set(); DIAG.ai[o.id] = r.ok ? r.data : { error: 'No se pudo analizar: ' + ((r.data && r.data.error) || r.error || 'sin respuesta del modelo') };
77
+ if (r.ok) DIAG.facts[o.id] = r.data.facts;
78
+ if (state.drawer && state.drawer.kind === 'diag') renderDiag(o, true);
79
+ };
80
+ }
81
+ // en vivo: si se ve algo trabado, un aviso arriba del lienzo que abre el panel
82
+ async function diagBanner(o) {
83
+ const el = $('#lvDiag'); if (!el || !o.team || o.status !== 'active') { if (el) el.hidden = true; return; }
84
+ const facts = await diagFacts(o);
85
+ const bad = facts.filter((f) => ['quiet', 'budget_belief', 'unsent'].includes(f.kind));
86
+ el.hidden = !bad.length; if (!bad.length) return;
87
+ const v = factView(o, bad[0]);
88
+ const html = `${DIAG_ICON}<p><b>Parece trabado.</b> ${v.html}</p><button type="button" class="primary" data-diag>Revisar qué pasa</button>`;
89
+ if (el.dataset.h !== html) { el.dataset.h = html; el.innerHTML = html; el.querySelector('[data-diag]').onclick = () => openDrawer('diag'); }
90
+ }