create-pmos 0.388.0 → 0.390.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/package.json +25 -30
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-insights-test.js +22 -27
  8. package/workspace/changelog.json +24 -0
  9. package/workspace/guide/briefing-premium.md +38 -19
  10. package/workspace/lib/briefing-premium-agent.js +3 -0
  11. package/workspace/lib/insights-premium.js +10 -8
  12. package/workspace/lib/report-chat.js +37 -0
  13. package/workspace/lib/routes-insights-premium.js +3 -1
  14. package/workspace/package-lock.json +2 -2
  15. package/workspace/package.json +1 -1
  16. package/workspace/premium-chat-chart-tab-test.js +150 -0
  17. package/workspace/premium-chat-report-tab-test.js +127 -0
  18. package/workspace/premium-report-read-test.js +99 -59
  19. package/workspace/premium-vw-slides-test.js +17 -19
  20. package/workspace/public/pm/goal-chat.js +2 -1
  21. package/workspace/public/pm/premium-chart-draw.js +58 -0
  22. package/workspace/public/pm/premium-chart-tab.js +157 -0
  23. package/workspace/public/pm/premium-chat.js +8 -2
  24. package/workspace/public/pm/premium-insights.js +39 -85
  25. package/workspace/public/pm/premium-report-brief.js +132 -0
  26. package/workspace/public/pm/premium-report-read.js +276 -103
  27. package/workspace/public/pm/premium-report-tab.js +235 -0
  28. package/workspace/public/pm/premium-shell.js +35 -3
  29. package/workspace/public/pm/premium-vw-doc.js +9 -1
  30. package/workspace/public/pm/premium-vw-report.css +60 -0
  31. package/workspace/public/pm/premium-vw-slides.js +14 -5
  32. package/workspace/public/pm/premium.css +71 -122
  33. package/workspace/public/pm/report-chat.js +89 -0
  34. package/workspace/test-lists/premium-chat-chart-tab.json +12 -0
  35. package/workspace/test-lists/premium-chat-report-tab.json +12 -0
  36. package/workspace/premium-studio-chart-test.js +0 -193
  37. package/workspace/premium-studio-report-test.js +0 -277
  38. package/workspace/premium-studio-test.js +0 -185
  39. package/workspace/public/pm/premium-studio-design.js +0 -298
  40. package/workspace/public/pm/premium-studio-report.js +0 -291
  41. package/workspace/public/pm/premium-studio.js +0 -453
  42. package/workspace/test-lists/premium-studio-chart.json +0 -13
  43. package/workspace/test-lists/premium-studio-report.json +0 -9
  44. package/workspace/test-lists/premium-studio.json +0 -9
@@ -70,27 +70,27 @@ const disk = () => fs.readFileSync(path.join(dir, pNew), 'utf8');
70
70
  p.on('request', (r) => { if (r.method() === 'POST') posts.push(new URL(r.url()).pathname); });
71
71
  const shot = async (n) => { if (process.env.SLIDES_SHOTS) await p.screenshot({ path: path.join(process.env.SLIDES_SHOTS, n + '.png') }); };
72
72
  const tap = (sel) => p.$eval(sel, (b) => b.click());
73
- const V = '#dOut .obody.vw:not([hidden])';
73
+ const V = '#oMain #rdEd'; // Edit draws the slide editor inside the report dialog (PM 2026-10-22: one place to edit a report)
74
74
  const st = () => p.evaluate((pth) => { const S = window.__premiumSlides && window.__premiumSlides.state(pth); return S ? { i: S.i, n: S.deck.slides.length, theme: S.deck.theme, dirty: S.dirty, ro: S.ro, sel: S.sel, msg: S.msg, slides: JSON.parse(JSON.stringify(S.deck.slides)) } : null; }, pNew);
75
75
  const openReader = async (slot) => {
76
76
  await p.goto(BASE + '/premium-insights.html');
77
77
  await until(() => p.evaluate(() => !!document.querySelector('#listSeg [data-f="rep"]')));
78
78
  if (await p.locator('#listSeg').isHidden()) await tap('#listF'); await tap('#listSeg [data-f="rep"]'); // the one list (insights-one-list L5): the Reports filter holds the report files
79
- await until(() => p.evaluate(() => document.querySelectorAll('#listRows [data-rep]').length === 2));
80
- await tap(`#listRows [data-rep="rep:${CAD}:${slot}"]`);
79
+ await until(() => p.evaluate(() => document.querySelectorAll('#listRows [data-rpt]').length === 1)); // one row per report (PM 2026-10-22); it opens the latest cycle
80
+ await tap(`#listRows [data-rpt="${CAD}"]`);
81
+ await until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !!document.querySelector('#rdSlide')));
82
+ if (slot !== '2026-10-12') { await tap('#dSub [data-rr="cycm"]'); await tap(`#dSub [data-rr="cyc|${RDraft.draftPath(dir, CAD, slot)}"]`); await until(() => p.evaluate(() => /issued/.test(document.querySelector('#dEye').textContent))); }
81
83
  return until(() => p.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !!document.querySelector('#rdSlide')));
82
84
  };
83
85
  const openEditor = async () => {
84
- await tap('#oMain [data-rr="rm"]');
85
- await tap('#oMain [data-rr="slides"]');
86
- return until(() => p.evaluate(() => !!document.querySelector('#dOut .obody.vw:not([hidden]) .sl .sl-stage .sl-cv')));
86
+ await tap('#oMain [data-rr="edit"]');
87
+ return until(() => p.evaluate(() => !!document.querySelector('#oMain #rdEd .sl .sl-stage .sl-cv')));
87
88
  };
88
89
 
89
90
  /* O: opening */
90
91
  ok('O1 a draft report opens in the reader', await openReader('2026-10-12'));
91
- ok('O2 the Read menu offers Edit the slides', /Edit the slides/.test(await p.evaluate(() => { document.querySelector('#oMain [data-rr="rm"]').click(); return (document.querySelector('#oMain [data-rr="slides"]') || {}).textContent || ''; })));
92
- await tap('#oMain [data-rr="rm"]');
93
- ok('O3 Edit the slides opens the editor as a tab beside the report', await openEditor() && await p.evaluate((pth) => { const s = window.__premiumViewer.vwState(); return s.on === 'slides:' + pth && s.ids.length === 1 && document.querySelector('#oMain').hidden; }, pNew));
92
+ ok('O2 on Slides, the bar\'s Edit says it edits the slides, and there is no other Edit the slides', await p.evaluate(() => /slides/i.test(document.querySelector('#oMain [data-rr="edit"]').title) && !document.querySelector('#oMain [data-rr="slides"]')));
93
+ ok('O3 Edit opens the slide editor inside the report dialog: no viewer tab', await openEditor() && await p.evaluate(() => { const s = window.__premiumViewer.vwState(); return !s.ids.length && !document.querySelector('#oMain').hidden && !!document.querySelector('#rdEd [data-c="close"]'); }));
94
94
  let s = await st();
95
95
  ok('O4 the report reads as a title slide and one slide per section', s && s.n === 5 && s.slides[0].l === 'title' && s.slides.map((x) => x.els[0].html).join('|') === 'Partner review, 12 Oct|Headline|Initiatives|Partner note|Sources', s && s.slides.map((x) => x.els[0].html).join('|'));
96
96
  ok('O5 the view says the document has no slide layout yet', /no slide layout yet/.test(await p.textContent(V + ' .sl-msg')));
@@ -160,17 +160,17 @@ const disk = () => fs.readFileSync(path.join(dir, pNew), 'utf8');
160
160
 
161
161
  /* S: save, and read back from disk */
162
162
  posts.length = 0;
163
+ const wsNow = await p.evaluate((pth) => window.__premiumSlides.state(pth).ws, pNew);
163
164
  await tap(V + ' [data-c="save"]');
164
165
  await until(() => p.$(V + ' .sl-savef'));
165
166
  await p.fill(V + ' .sl-savef input[name="why"]', 'Slides for Thursday'); await tap(V + ' .sl-savef [type="submit"]');
166
- await until(() => p.evaluate((pth) => !window.__premiumSlides.state(pth).dirty, pNew));
167
+ await until(() => p.evaluate(() => !document.querySelector('#rdEd'))); // Save writes, then brings the report back
167
168
  const md = disk();
168
169
  ok('S1 Save writes once through the document sheet\'s edit route', JSON.stringify(posts) === '["/api/doc-sheet/edit"]', JSON.stringify(posts));
169
170
  ok('S2 the file is markdown with a slide block under each heading', (md.match(/^<!-- pmos:slide \{/gm) || []).length === 6 && /^# Partner review, 12 Oct\n<!-- pmos:slide/m.test(md) && /\ndeck_theme: sky\n/.test(md), md.slice(0, 300));
170
171
  ok('S3 the slide\'s text, its chart data and its image are written as markdown', md.includes('## Headline this week\n') && md.includes('| Sep | 30 |') && md.includes('![The setup screen](planning/design/screen.png)'));
171
172
  ok('S4 the speaker notes and the report note are in the file', md.includes('"notes":"Say the number first."') && md.includes('<!-- pmos:note partner-activation -->\nThe PM\'s words.\n<!-- /pmos:note -->'));
172
- ok('S5 the reason is kept in the document\'s revision log', await p.evaluate(async ([pth]) => { const S = window.__premiumSlides.state(pth); const r = await fetch('/api/doc-sheet/log?' + new URLSearchParams({ ...(S.ws ? { ws: S.ws } : {}), path: pth })).then((x) => x.json()); return JSON.stringify(r).includes('Slides for Thursday'); }, [pNew]));
173
- await tap('#vTabs .vtab[data-vw="main"]');
173
+ ok('S5 the reason is kept in the document\'s revision log', await p.evaluate(async ([pth, ws]) => { const r = await fetch('/api/doc-sheet/log?' + new URLSearchParams({ ...(ws ? { ws } : {}), path: pth })).then((x) => x.json()); return JSON.stringify(r).includes('Slides for Thursday'); }, [pNew, wsNow]));
174
174
  ok('S6 the report reader shows the saved words, without the slide blocks', await until(() => p.evaluate(() => { const t = document.querySelector('#oMain').textContent; return t.includes('Headline this week') && !t.includes('pmos:slide'); })));
175
175
  await openReader('2026-10-12'); await openEditor();
176
176
  s = await st();
@@ -228,9 +228,7 @@ const disk = () => fs.readFileSync(path.join(dir, pNew), 'utf8');
228
228
 
229
229
  /* I: an issued report */
230
230
  await openReader('2026-10-05');
231
- ok('I1 an issued report offers Open the slides', /Open the slides/.test(await p.evaluate(() => { document.querySelector('#oMain [data-rr="rm"]').click(); return (document.querySelector('#oMain [data-rr="slides"]') || {}).textContent || ''; })));
232
- await tap('#oMain [data-rr="rm"]'); await openEditor();
233
- ok('I2 its slides are read-only: no Save, no editing tools, and it says why', await p.evaluate((v) => !document.querySelector(v + ' [data-c="save"]') && !document.querySelector(v + ' [data-c="text"]') && !document.querySelector(v + ' .sl-cv.ed') && /issued, so its slides are read-only/.test(document.querySelector(v + ' .sl-msg').textContent), V));
231
+ ok('I1 an issued report has no Edit and no Issue: it reads as Slides or Page', await p.evaluate(() => !document.querySelector('#oMain [data-rr="edit"]') && !document.querySelector('#oMain [data-rr="issue"]') && !!document.querySelector('#oMain [data-rr="view|deck"]')));
234
232
  ok('I3 the issued file is not changed', fs.readFileSync(path.join(dir, pOld), 'utf8') === OLD);
235
233
  ok('X no page error', errs.length === 0, errs.join(' | '));
236
234
  await ctx.close();
@@ -242,11 +240,11 @@ const disk = () => fs.readFileSync(path.join(dir, pNew), 'utf8');
242
240
  await q.goto(BASE + '/premium-insights.html?theme=dark');
243
241
  await until(() => q.evaluate(() => !!document.querySelector('#listSeg [data-f="rep"]')));
244
242
  await q.$eval('#listSeg [data-f="rep"]', (x) => x.click());
245
- await until(() => q.evaluate(() => document.querySelectorAll('#listRows [data-rep]').length === 2));
246
- await q.$eval(`#listRows [data-rep="rep:${CAD}:2026-10-12"]`, (x) => x.click());
243
+ await until(() => q.evaluate(() => document.querySelectorAll('#listRows [data-rpt]').length === 1));
244
+ await q.$eval(`#listRows [data-rpt="${CAD}"]`, (x) => x.click());
247
245
  await until(() => q.evaluate(() => document.querySelector('#dlg').classList.contains('on') && !!document.querySelector('#rdSlide')));
248
- await q.$eval('#oMain [data-rr="rm"]', (x) => x.click()); await q.$eval('#oMain [data-rr="slides"]', (x) => x.click());
249
- await until(() => q.evaluate(() => !!document.querySelector('#dOut .obody.vw:not([hidden]) .sl .sl-stage .sl-cv')));
246
+ await q.$eval('#oMain [data-rr="edit"]', (x) => x.click());
247
+ await until(() => q.evaluate(() => !!document.querySelector('#oMain #rdEd .sl .sl-stage .sl-cv')));
250
248
  await sleep(300);
251
249
  const m = await q.evaluate((v) => {
252
250
  const r = (e) => e.getBoundingClientRect(), vis = (e) => e.offsetParent !== null && r(e).width > 0;
@@ -24,7 +24,7 @@ export function splitGoal(text) {
24
24
  }
25
25
 
26
26
  const MARK = { grill: '[PMOS /goal]', start: '[PMOS /goal start]', cancel: '[PMOS /goal cancel]' };
27
- const OPENING = 'The PM is talking to you from the chat panel';
27
+ const OPENING = 'The PM is talking to you from the '; // the chat panel of an item, or the Chat page (lib/briefing-premium-agent.js openingFor)
28
28
  /** The PM's turn as the PM typed it (G7): `/goal Ship X` for the grilling prompt, a short line for Start and Cancel, and only the PM's
29
29
  * words for the opening message that carries the row's context. Anything else is shown unchanged. */
30
30
  export function shownUser(text) {
@@ -35,6 +35,7 @@ export function shownUser(text) {
35
35
  const g = t.indexOf(MARK.grill + ' The PM set a goal: ');
36
36
  if (g >= 0) return '/goal ' + t.slice(g + (MARK.grill + ' The PM set a goal: ').length).split('\n')[0];
37
37
  if (t.startsWith(OPENING)) { const i = t.lastIndexOf('\nThe PM says: '); if (i >= 0) return t.slice(i + '\nThe PM says: '.length); }
38
+ if (t.startsWith('[PMOS report]')) { const i = t.lastIndexOf('\nThe PM says: '); if (i >= 0) return t.slice(i + '\nThe PM says: '.length); } // premium-reports-from-chat: lib/report-chat.js wrap
38
39
  return t;
39
40
  }
40
41
 
@@ -0,0 +1,58 @@
1
+ /* pm/premium-chart-draw.js — a chart tile in one of four forms: line, bars, number, meter (initiative premium-studio-chart C3). The Insights page and the
2
+ * Chart tab beside a chat (initiative premium-reports-from-chat, slice C) share this drawing. A KR metric's own chart is a line; a chart the PM saved
3
+ * carries its form. Bars and a meter start at zero, so a series with a value below zero is drawn as a line and says so. Pure strings: no DOM. */
4
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
5
+ export const W = 220, H = 60, P = 5;
6
+ export const X = (fx) => P + fx * (W - 2 * P), Y = (fy) => P + (1 - fy) * (H - 2 * P);
7
+ export const unitTxt = (c, v) => { const u = c.unit || '', s = String(Math.round(v * 100) / 100); return u ? (/^[A-Za-z]/.test(u) ? s + ' ' + u : s + u) : s; };
8
+ function chgHtml(c) {
9
+ return c.step === 0 ? '' : `<span class="mchg ${c.good === null ? '' : c.good ? 'good' : 'bad'}">${c.step > 0 ? '▲ ' : '▼ '}${esc(Math.abs(c.step) + (c.unit && /^[%°]/.test(c.unit) ? c.unit : c.unit ? ' ' + c.unit : ''))} since the last reading</span>`;
10
+ }
11
+ const chipOf = (c) => `<i class="mchip ${c.chipKind === 'bad' ? 'warn' : c.chipKind}">${esc(c.chip)}</i>`;
12
+ const capOf = (c) => 'on ' + c.at + (c.targetTxt ? ' · ' + c.targetTxt : '');
13
+ export function tileHtml(c) {
14
+ const f = c.form || 'line', neg = c.pts.some((p) => p.v < 0) || (c.target !== null && c.target < 0);
15
+ const h = f === 'number' ? numTile(c) : f === 'bars' && !neg ? barsTile(c) : f === 'meter' && !neg && c.target !== null ? meterTile(c) : lineTile(c, f !== 'line' && f !== 'number' ? (neg ? 'A value is below zero, so it is drawn as a line.' : 'No target is set, so it is drawn as a line.') : '');
16
+ return h + (c.note ? `<p class="mnote">${esc(c.note)}</p>` : '');
17
+ }
18
+ function lineTile(c, why) {
19
+ const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + Y(p.fy).toFixed(1)).join('');
20
+ const last = c.pts[c.pts.length - 1];
21
+ return `<div class="mt1 mch ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" tabindex="0" role="img" aria-label="${esc(c.title)}, ${c.pts.length} readings, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}. Use the arrow keys to read each reading."><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
22
+ + `<svg viewBox="0 0 ${W} ${H}"><path class="ar" d="${d}L${X(1)},${H}L${X(0)},${H}Z"/>${c.ty !== null ? `<line class="tg" x1="${P}" x2="${W - P}" y1="${Y(c.ty)}" y2="${Y(c.ty)}"/>` : ''}<path class="ln2" d="${d}"/><line class="cx" x1="0" x2="0" y1="0" y2="${H}"/><circle class="dt" cx="${X(last.fx)}" cy="${Y(last.fy)}" r="3.5"/></svg>`
23
+ + `<span class="mfoot"><i>${esc(c.ticks[0])}</i>${c.target !== null ? '<i class="tgl">dashed line is the target</i>' : ''}<i>${esc(c.ticks[1])}</i></span>${why ? `<span class="mwhy">${esc(why)}</span>` : ''}</div>`;
24
+ }
25
+ function barsTile(c) {
26
+ const n = c.pts.length, hi = Math.max(...c.pts.map((p) => p.v), c.target !== null ? c.target : 0) || 1, pc = (v) => (v / hi * 84).toFixed(1);
27
+ const cols = c.pts.map((p, i) => `<span class="bw" title="${esc(p.d + ': ' + p.txt)}">${i === n - 1 ? `<b class="bl">${esc(p.txt)}</b>` : ''}<i class="${i === n - 1 ? 'bk' : 'bg'}" style="height:${pc(p.v)}%"></i></span>`).join('');
28
+ return `<div class="mt1 mfm bars ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, ${n} readings as bars from zero, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
29
+ + `<div class="bplot">${cols}${c.target !== null ? `<i class="btg" style="bottom:${pc(c.target)}%"></i>` : ''}</div>`
30
+ + `<span class="mfoot"><i>${esc(c.ticks[0])}</i><i class="tgl">${c.target !== null ? 'dashed line is the target' : 'bars start at zero'}</i><i>${esc(c.ticks[1])}</i></span></div>`;
31
+ }
32
+ function numTile(c) {
33
+ const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + (2 + (1 - p.fy) * 26).toFixed(1)).join('');
34
+ return `<div class="mt1 mfm num ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval mhero">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
35
+ + `<svg class="nspk" viewBox="0 0 ${W} 30" aria-hidden="true"><path d="${d}"/></svg></div>`;
36
+ }
37
+ function meterTile(c) {
38
+ const v = c.pts[c.pts.length - 1].v, tg = c.target, hi = Math.max(v, tg) * 1.15 || 1, lower = c.dir < 0, ok = lower ? v <= tg : v >= tg;
39
+ return `<div class="mt1 mfm prg ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)} is ${esc(c.v)} against ${lower ? 'a limit' : 'a target'} of ${esc(unitTxt(c, tg))}. ${ok ? 'It is on the right side of it.' : 'It is not there yet.'}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(ok ? (lower ? 'Within the limit' : 'At or past the target') : (lower ? 'Over the limit' : 'Short of the target'))}</em>`
40
+ + `<div class="mtrk"><i class="mfil ${ok ? 'ok' : 'warn'}" style="width:${(v / hi * 100).toFixed(1)}%"></i><i class="mtgt" style="left:${(tg / hi * 100).toFixed(1)}%"></i></div>`
41
+ + `<span class="mfoot"><i>0</i><i class="tgl">${lower ? 'limit' : 'target'} ${esc(unitTxt(c, tg))}</i><i>${esc(unitTxt(c, hi))}</i></span></div>`;
42
+ }
43
+ /* A draft drawn from a measure's chart (premium-studio-chart C2, C7): the latest `range` readings, against the draft's target, as the server's
44
+ * lib/insights-premium.js mineOf draws a saved chart. Every point is a reading of the record. */
45
+ export function deriveChart(base, d) {
46
+ const all = base.pts, pts0 = d.range ? all.slice(-d.range) : all.slice();
47
+ if (pts0.length < 2) return null;
48
+ const tg = d.target === null || d.target === undefined || d.target === '' ? null : +d.target;
49
+ const day = (p) => Date.parse(String(p.at).slice(0, 10) + 'T00:00:00Z');
50
+ const t0 = day(pts0[0]), span = day(pts0[pts0.length - 1]) - t0 || 1;
51
+ const ys = pts0.map((p) => p.v).concat(tg !== null ? [tg] : []), lo = Math.min(...ys), hi = Math.max(...ys), range = hi - lo || 1;
52
+ const pts = pts0.map((p) => Object.assign({}, p, { fx: (day(p) - t0) / span, fy: (p.v - lo) / range }));
53
+ const now = pts[pts.length - 1], prev = pts[pts.length - 2], step = Math.round((now.v - prev.v) * 100) / 100, dir = d.better === 'lower' ? -1 : 1;
54
+ return Object.assign({}, base, {
55
+ key: 'draft', title: d.title || base.title, form: d.form, note: d.note || '', pts, v: now.txt, at: now.d, target: tg, targetTxt: tg !== null ? 'target ' + unitTxt(base, tg) : '',
56
+ ty: tg !== null ? (tg - lo) / range : null, step, dir, good: step ? step * dir > 0 : null, ticks: [pts[0].d, now.d],
57
+ });
58
+ }
@@ -0,0 +1,157 @@
1
+ /* pm/premium-chart-tab.js — the Chart tab beside a chat (initiative premium-reports-from-chat, slice C; PRD C1–C3). It replaces the Insight Studio's
2
+ * Chart and Dashboard modes: the PM asks in the chat, Claude ends its answer with a `pmos-report` block of kind chart or dashboard
3
+ * (public/pm/report-chat.js), and this tab draws it from the KR metric records, as the Insights page draws it (premium-chart-draw.js).
4
+ *
5
+ * A CHART (block.kind 'chart'): the measure's chart as proposed, with its four forms to pick from. Save chart posts POST /api/premium-charts/save.
6
+ * A saved chart (block.id) shows as saved; a change Claude proposes to it shows drawn, and Save the change posts the whole chart. Delete chart
7
+ * asks once, then posts { id, remove: true }.
8
+ * A DASHBOARD (block.kind 'dashboard'): its name, what it is for and its charts in order. Save dashboard posts POST /api/premium-dashboards/save;
9
+ * Delete dashboard asks once, then posts { id, remove: true }. Pinning stays on the Insights page.
10
+ *
11
+ * The model is GET /api/insights-premium (the board the page shows). Every value drawn is a reading of a record; a measure with fewer than two
12
+ * readings is named, not drawn. Every write is a press here, behind the launch nonce (http.js pmPost). Claude writes nothing: the routes refuse an
13
+ * agent session. Nothing is sent outward. */
14
+ import { pmGet, pmPost } from './http.js';
15
+ import { vwOpen, vwStyle, vwConfirm } from './premium-viewer.js';
16
+ import { tileHtml, deriveChart } from './premium-chart-draw.js';
17
+
18
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
19
+ const FORMS = [['line', 'Line'], ['bars', 'Bars'], ['number', 'Number'], ['meter', 'Meter']];
20
+ const ws = () => new URLSearchParams(location.search).get('ws') || '';
21
+ const post = (p, body) => pmPost(p, Object.assign(ws() ? { ws: ws() } : {}, body)).catch(() => null);
22
+ const btn = (a, label, o = {}) => `<button type="button" class="btn${o.sec ? ' sec' : ''}${o.cls ? ' ' + o.cls : ''}" data-ct="${esc(a)}"${o.off ? ' disabled' : ''}${o.pressed != null ? ` aria-pressed="${o.pressed}"` : ''}>${esc(label)}</button>`;
23
+
24
+ const T = new Map(); // tab id → its state
25
+ /** Open (or refresh) the Chart tab for a checked chart or dashboard block (report-chat.js cleanBlock). */
26
+ export function openChartTab(block) {
27
+ if (!block || (block.kind !== 'chart' && block.kind !== 'dashboard')) return null;
28
+ vwStyle('report');
29
+ const P = block.proposal || {};
30
+ const id = block.kind + ':' + String(block.id || P.measure || P.name || 'new').toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 60);
31
+ let t = T.get(id);
32
+ if (!t || JSON.stringify(t.block) !== JSON.stringify(block)) {
33
+ t = { id, block, M: null, loaded: false, busy: false, msg: '', d: null, gone: false, removed: false };
34
+ T.set(id, t);
35
+ load(t);
36
+ }
37
+ return vwOpen({ id, title: block.kind === 'chart' ? 'Chart' : 'Dashboard', icon: 'list', render: (el) => draw(t, el), wire: (el) => { el.onclick = (e) => press(t, e); } });
38
+ }
39
+ const paneOf = (t) => document.querySelector(`#dOut .obody.vw[data-vw="${CSS.escape(t.id)}"]`);
40
+ const redraw = (t) => { const el = paneOf(t); if (el) draw(t, el); };
41
+
42
+ async function load(t) {
43
+ const r = await pmGet('/api/insights-premium' + (ws() ? '?ws=' + encodeURIComponent(ws()) : '')).catch(() => null);
44
+ t.M = r && r.model ? r.model : null;
45
+ t.loaded = true;
46
+ if (t.M) {
47
+ const b = t.block, P = b.proposal;
48
+ if (b.kind === 'chart') {
49
+ const saved = b.id ? (t.M.mineSaved || []).find((x) => x.id === b.id) || null : null;
50
+ t.saved = saved;
51
+ t.d = saved || P ? Object.assign({}, saved || {}, P || {}) : null;
52
+ } else {
53
+ const saved = b.id ? (t.M.dashboards || []).find((x) => x.saved && x.id === b.id) || null : null;
54
+ t.saved = saved;
55
+ t.d = saved || P ? Object.assign({ purpose: '' }, saved ? { name: saved.name, purpose: saved.purpose, charts: saved.charts.slice(), main: saved.main } : {}, P || {}) : null;
56
+ }
57
+ t.gone = !t.d;
58
+ }
59
+ redraw(t);
60
+ }
61
+
62
+ /** A measure's or a saved chart's tile, as Insights draws it. */
63
+ function chartOf(M, ref) {
64
+ return (M.mine || []).find((c) => c.id === ref) || (M.charts || []).find((c) => c.id === ref) || null;
65
+ }
66
+ function draftTile(t) {
67
+ const d = t.d, base = (t.M.charts || []).find((c) => c.id === d.measure);
68
+ if (!base) {
69
+ const m = (t.M.measures || []).find((x) => x.id === d.measure);
70
+ return `<p class="rt-msg">${esc(m ? m.title + ' has fewer than two readings, so it has no chart yet.' : 'No KR metric record is called ' + d.measure + ' in this workspace.')}</p>`;
71
+ }
72
+ const c = deriveChart(base, { title: d.title || base.title, form: d.form || 'line', range: d.range || null, target: d.target, better: d.better || 'higher', note: d.note || '' });
73
+ return c ? `<div class="ntw ct-tile">${tileHtml(c)}</div>` : '<p class="rt-msg">The range holds fewer than two readings, so nothing is drawn.</p>';
74
+ }
75
+ const sameChart = (a, b) => ['measure', 'title', 'question', 'form', 'range', 'target', 'better', 'note'].every((k) => (a[k] == null ? '' : String(a[k])) === (b[k] == null ? '' : String(b[k])));
76
+
77
+ function chartHtml(t) {
78
+ const d = t.d, s = t.saved, base = (t.M.charts || []).find((c) => c.id === d.measure);
79
+ const changed = !s || !sameChart(s, d);
80
+ const eye = !s ? 'New chart · from this chat' : changed ? 'Chart change · from this chat' : 'Saved chart';
81
+ const forms = `<div class="rt-seg" role="group" aria-label="Form">${FORMS.map(([f, l]) => btn('form|' + f, l, { sec: (d.form || 'line') !== f, pressed: (d.form || 'line') === f })).join('')}</div>`;
82
+ const meter = d.form === 'meter' && (d.target === null || d.target === undefined) ? '<p class="rt-note">A meter needs a target. Say one in the chat, or pick another form.</p>' : '';
83
+ return `<p class="rt-eye">${esc(eye)}</p><h3 class="rt-h">${esc(d.title || (base ? base.title : d.measure))}</h3>${d.question ? `<p class="rt-sub">${esc(d.question)}</p>` : ''}`
84
+ + `<p class="rt-meta">${esc(base ? base.title : d.measure)}${d.range ? ' · last ' + d.range + ' readings' : ' · every reading'}${d.target != null ? ' · target ' + esc(d.target) : ''} · ${d.better === 'lower' ? 'lower is better' : 'higher is better'}</p>`
85
+ + forms + draftTile(t) + meter
86
+ + `<div class="rt-foot">${changed ? btn('save', t.busy ? 'Saving' : s ? 'Save the change' : 'Save chart', { off: t.busy || !base || !!meter }) : ''}</div>`
87
+ + `<p class="rt-note">${s ? 'It shows on Insights under Your charts.' : 'Saved, it shows on Insights under Your charts and can go on a dashboard.'} Ask in the chat to change it.</p>`
88
+ + (s ? `<div class="rt-foot rt-end">${btn('remove', 'Delete chart', { sec: true, cls: 'rt-del', off: t.busy })}</div>` : '');
89
+ }
90
+ function dashHtml(t) {
91
+ const d = t.d, s = t.saved, M = t.M;
92
+ const changed = !s || d.name !== s.name || d.purpose !== s.purpose || d.charts.join() !== s.charts.join();
93
+ const eye = !s ? 'New dashboard · from this chat' : changed ? 'Dashboard change · from this chat' : 'Saved dashboard';
94
+ const tiles = d.charts.map((ref) => {
95
+ const c = chartOf(M, ref);
96
+ if (c) return `<div class="ntw">${tileHtml(c)}</div>`;
97
+ const m = (M.measures || []).find((x) => x.id === ref);
98
+ return `<div class="nempty"><p><b>${esc(m ? m.title : ref)}</b><br>${esc(m ? 'It has fewer than two readings, so it has no chart yet.' : 'No KR metric record or saved chart is called ' + ref + '.')}</p></div>`;
99
+ }).join('');
100
+ const many = d.charts.length > 6 ? '<p class="rt-note">This dashboard holds more than six charts. A dashboard that serves one routine usually holds six or fewer.</p>' : '';
101
+ return `<p class="rt-eye">${esc(eye)}</p><h3 class="rt-h">${esc(d.name)}</h3>${d.purpose ? `<p class="rt-sub">${esc(d.purpose)}</p>` : ''}`
102
+ + `<p class="rt-meta">${d.charts.length} ${d.charts.length === 1 ? 'chart' : 'charts'}${s && s.main ? ' · pinned on Insights' : ''}</p>`
103
+ + `<div class="ngrid ct-grid">${tiles}</div>${many}`
104
+ + `<div class="rt-foot">${changed ? btn('save', t.busy ? 'Saving' : s ? 'Save the change' : 'Save dashboard', { off: t.busy }) : ''}</div>`
105
+ + `<p class="rt-note">${s ? 'It is in the list on Insights.' : 'Saved, it is in the list on Insights, where you can pin it.'} Ask in the chat to change it.</p>`
106
+ + (s ? `<div class="rt-foot rt-end">${btn('remove', 'Delete dashboard', { sec: true, cls: 'rt-del', off: t.busy })}</div>` : '');
107
+ }
108
+ function bodyHtml(t) {
109
+ const noun = t.block.kind;
110
+ if (!t.loaded) return `<p class="rt-note" role="status">Reading the ${noun}.</p>`;
111
+ if (!t.M) return `<p class="rt-note">The Insights records could not be read, so the ${noun} cannot be drawn. Try again in a moment.</p>`;
112
+ if (t.removed) return `<p class="rt-eye">${noun === 'chart' ? 'Chart' : 'Dashboard'}</p><p class="rt-note">Deleted. Ask in the chat for a new one.</p>`;
113
+ if (t.gone) return `<p class="rt-eye">${noun === 'chart' ? 'Chart' : 'Dashboard'}</p><h3 class="rt-h">${esc(t.block.id)}</h3><p class="rt-note">This ${noun} is deleted, or it is not saved on this board.</p>`;
114
+ if (!t.M.board.id) return '<p class="rt-note">This workspace has no board to save on, so nothing can be saved here.</p>';
115
+ return noun === 'chart' ? chartHtml(t) : dashHtml(t);
116
+ }
117
+ function draw(t, el) {
118
+ const ask = el.querySelector(':scope > .vcf'); // an open confirm card outlives a redraw, so its answer still lands
119
+ el.innerHTML = `<div class="rt">${bodyHtml(t)}${t.msg ? `<p class="rt-msg" role="status">${esc(t.msg)}</p>` : ''}</div>`;
120
+ if (ask) el.prepend(ask);
121
+ }
122
+
123
+ async function act(t, fn) { t.busy = true; t.msg = ''; redraw(t); const m = await fn(); t.busy = false; if (m != null) t.msg = m; redraw(t); }
124
+ const why = (r, d) => (r && r.error) || d;
125
+ async function press(t, e) {
126
+ const b = e.target.closest('[data-ct]'); if (!b || b.disabled) return;
127
+ const [a, v] = [b.dataset.ct.split('|')[0], b.dataset.ct.slice(b.dataset.ct.indexOf('|') + 1)];
128
+ const board = t.M && t.M.board.id, kind = t.block.kind;
129
+ if (a === 'form') { t.d = Object.assign({}, t.d, { form: v }); t.msg = ''; redraw(t); return; }
130
+ if (a === 'save') {
131
+ await act(t, async () => {
132
+ if (kind === 'chart') {
133
+ const d = t.d, base = (t.M.charts || []).find((c) => c.id === d.measure);
134
+ const r = await post('/api/premium-charts/save', { board, id: t.saved ? t.saved.id : undefined, measure: d.measure, title: d.title || (base ? base.title.slice(0, 60) : d.measure),
135
+ question: d.question || '', form: d.form || 'line', range: d.range || null, target: d.target == null ? null : d.target, better: d.better || 'higher', note: d.note || '' });
136
+ if (!r || !r.ok) return 'It was not saved: ' + why(r, 'the page could not reach PMOS') + '.';
137
+ t.block = { kind, id: r.chart.id }; await load(t);
138
+ return 'Saved. It shows on Insights under Your charts.';
139
+ }
140
+ const d = t.d;
141
+ const r = await post('/api/premium-dashboards/save', { board, id: t.saved ? t.saved.id : undefined, name: d.name, purpose: d.purpose || d.name, charts: d.charts, main: !!(t.saved && t.saved.main) });
142
+ if (!r || !r.ok) return 'It was not saved: ' + why(r, 'the page could not reach PMOS') + '.';
143
+ t.block = { kind, id: r.dashboard.id }; await load(t);
144
+ return 'Saved. It is in the list on Insights.';
145
+ });
146
+ return;
147
+ }
148
+ if (a === 'remove') {
149
+ const noun = kind === 'chart' ? 'chart' : 'dashboard';
150
+ if (!(await vwConfirm(paneOf(t), { text: kind === 'chart' ? 'Delete this chart? A dashboard that holds it shows it as removed.' : 'Delete this dashboard? Its charts and records stay.', yes: 'Delete ' + noun, no: 'Keep it' }))) return;
151
+ await act(t, async () => {
152
+ const r = await post(kind === 'chart' ? '/api/premium-charts/save' : '/api/premium-dashboards/save', { board, id: t.saved.id, remove: true });
153
+ if (!r || !r.ok) return 'It was not deleted: ' + why(r, 'the page could not reach PMOS') + '.';
154
+ t.removed = true; return null;
155
+ });
156
+ }
157
+ }
@@ -1,9 +1,15 @@
1
1
  /* pm/premium-chat.js — the Chat page (initiative premium-chat-page). The rail's middle place: the session list, the conversation and the viewer
2
- * as a page of their own. ?about=<key>&label=<name> is the page the PM came from (the rail's Chat carries it); without it, the PM's own chat. */
3
- import { wireRail, openChatPage } from './premium-shell.js';
2
+ * as a page of their own. ?about=<key>&label=<name> is the page the PM came from (the rail's Chat carries it); without it, the PM's own chat.
3
+ * premium-reports-from-chat (slice C): ?open=report:<id> | chart:<id> | dashboard:<id> opens that one in its tab beside the chat, and ?say=<words>
4
+ * puts a first message in the box for the PM to send. Insights links here for New, Edit and Shape it, now that the Insight Studio is removed. */
5
+ import { wireRail, openChatPage, openBlockTab, growAsk } from './premium-shell.js';
4
6
 
5
7
  wireRail('chat');
6
8
  const q = new URLSearchParams(location.search);
7
9
  // a conversation key as the ask route takes it (lib/briefing-premium-agent.js KEY_RE); anything else is the PM's own chat
8
10
  const about = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/.test(q.get('about') || '') ? q.get('about') : null;
9
11
  openChatPage(about || 'chat:main', about ? (q.get('label') || '').slice(0, 80) : '');
12
+ const open = /^(report|chart|dashboard):([A-Za-z0-9][A-Za-z0-9._:-]{0,119})$/.exec(q.get('open') || '');
13
+ if (open) openBlockTab({ kind: open[1], id: open[2] });
14
+ const say = (q.get('say') || '').slice(0, 500);
15
+ if (say) { const inp = document.querySelector('#askIn'); if (inp) { inp.value = say; growAsk(); inp.focus(); inp.setSelectionRange(say.length, say.length); } }
@@ -3,15 +3,14 @@
3
3
  * line, what stands out), the Reports card, the dock and the standard dialog.
4
4
  * briefing-premium-reports adds the PM's presses, each through pmPost and so behind the launch nonce: a saved dashboard (POST /api/premium-dashboards/save,
5
5
  * PRD D2 to D6) and the report presses of the console's Reports workspace (POST /api/report-setups/ask | change | cancel | setup | dismiss | pause | resume |
6
- * draft, PRD R2 to R4). premium-studio-chart adds a saved chart (POST /api/premium-charts/save, PRD C1, C10) and its four forms (C3). premium-studio-report
7
- * adds New report and Shape it in the Studio, whose presses are POST /api/report-setups/setup | from-dashboard and POST /api/report-structure/turn | remove |
8
- * revert | accept (PRD R5 to R8). insights-one-list puts the insight first, the pinned dashboard on top and one paged list of dashboards and reports below
6
+ * draft, PRD R2 to R4). premium-studio-chart's saved charts are drawn in their four forms (premium-chart-draw.js). premium-reports-from-chat removed the
7
+ * Insight Studio: New, Edit and Shape it open the Chat page, where Claude proposes and the PM saves in the tab beside the chat. insights-one-list puts the insight first, the pinned dashboard on top and one paged list of dashboards and reports below
9
8
  * (PRD L1 to L6); its one new press is Pin, POST /api/premium-dashboards/pin. Nothing else posts, and nothing is sent outward. */
10
9
  import { $, $$, esc, openDlg, popKey, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps, infoBtn, growAsk } from './premium-shell.js';
11
- import { pmPost, pmGet } from './http.js';
12
- import { openStudio } from './premium-studio.js';
10
+ import { pmPost } from './http.js';
13
11
  import { openReport } from './premium-report-read.js';
14
12
  import * as MT from './premium-metric-tiles.js';
13
+ import { W, P, X, Y, tileHtml } from './premium-chart-draw.js';
15
14
 
16
15
  let M = null; // the model
17
16
  let dash = null; // the dashboard in the top card: the pinned one until a list row opens another
@@ -63,62 +62,6 @@ $('#insHero').addEventListener('click', (e) => {
63
62
  });
64
63
 
65
64
  /* ── charts ───────────────────────────────────────────────────────────────────────────────────────────────────── */
66
- const W = 220, H = 60, P = 5;
67
- const X = (fx) => P + fx * (W - 2 * P), Y = (fy) => P + (1 - fy) * (H - 2 * P);
68
- /* A chart is drawn in one of four forms (initiative premium-studio-chart C3). The page and the Insight Studio share this drawing. A KR metric's own chart
69
- * is a line; a chart the PM saved carries its form. Bars and a meter start at zero, so a series with a value below zero is drawn as a line and says so. */
70
- const unitTxt = (c, v) => { const u = c.unit || '', s = String(Math.round(v * 100) / 100); return u ? (/^[A-Za-z]/.test(u) ? s + ' ' + u : s + u) : s; };
71
- function chgHtml(c) {
72
- return c.step === 0 ? '' : `<span class="mchg ${c.good === null ? '' : c.good ? 'good' : 'bad'}">${c.step > 0 ? '▲ ' : '▼ '}${esc(Math.abs(c.step) + (c.unit && /^[%°]/.test(c.unit) ? c.unit : c.unit ? ' ' + c.unit : ''))} since the last reading</span>`;
73
- }
74
- const chipOf = (c) => `<i class="mchip ${c.chipKind === 'bad' ? 'warn' : c.chipKind}">${esc(c.chip)}</i>`;
75
- const capOf = (c) => 'on ' + c.at + (c.targetTxt ? ' · ' + c.targetTxt : '');
76
- function tileHtml(c) {
77
- const f = c.form || 'line', neg = c.pts.some((p) => p.v < 0) || (c.target !== null && c.target < 0);
78
- const h = f === 'number' ? numTile(c) : f === 'bars' && !neg ? barsTile(c) : f === 'meter' && !neg && c.target !== null ? meterTile(c) : lineTile(c, f !== 'line' && f !== 'number' ? (neg ? 'A value is below zero, so it is drawn as a line.' : 'No target is set, so it is drawn as a line.') : '');
79
- return h + (c.note ? `<p class="mnote">${esc(c.note)}</p>` : '');
80
- }
81
- function lineTile(c, why) {
82
- const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + Y(p.fy).toFixed(1)).join('');
83
- const last = c.pts[c.pts.length - 1];
84
- return `<div class="mt1 mch ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" tabindex="0" role="img" aria-label="${esc(c.title)}, ${c.pts.length} readings, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}. Use the arrow keys to read each reading."><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
85
- + `<svg viewBox="0 0 ${W} ${H}"><path class="ar" d="${d}L${X(1)},${H}L${X(0)},${H}Z"/>${c.ty !== null ? `<line class="tg" x1="${P}" x2="${W - P}" y1="${Y(c.ty)}" y2="${Y(c.ty)}"/>` : ''}<path class="ln2" d="${d}"/><line class="cx" x1="0" x2="0" y1="0" y2="${H}"/><circle class="dt" cx="${X(last.fx)}" cy="${Y(last.fy)}" r="3.5"/></svg>`
86
- + `<span class="mfoot"><i>${esc(c.ticks[0])}</i>${c.target !== null ? '<i class="tgl">dashed line is the target</i>' : ''}<i>${esc(c.ticks[1])}</i></span>${why ? `<span class="mwhy">${esc(why)}</span>` : ''}</div>`;
87
- }
88
- function barsTile(c) {
89
- const n = c.pts.length, hi = Math.max(...c.pts.map((p) => p.v), c.target !== null ? c.target : 0) || 1, pc = (v) => (v / hi * 84).toFixed(1);
90
- const cols = c.pts.map((p, i) => `<span class="bw" title="${esc(p.d + ': ' + p.txt)}">${i === n - 1 ? `<b class="bl">${esc(p.txt)}</b>` : ''}<i class="${i === n - 1 ? 'bk' : 'bg'}" style="height:${pc(p.v)}%"></i></span>`).join('');
91
- return `<div class="mt1 mfm bars ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, ${n} readings as bars from zero, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
92
- + `<div class="bplot">${cols}${c.target !== null ? `<i class="btg" style="bottom:${pc(c.target)}%"></i>` : ''}</div>`
93
- + `<span class="mfoot"><i>${esc(c.ticks[0])}</i><i class="tgl">${c.target !== null ? 'dashed line is the target' : 'bars start at zero'}</i><i>${esc(c.ticks[1])}</i></span></div>`;
94
- }
95
- function numTile(c) {
96
- const d = c.pts.map((p, i) => (i ? 'L' : 'M') + X(p.fx).toFixed(1) + ',' + (2 + (1 - p.fy) * 26).toFixed(1)).join('');
97
- return `<div class="mt1 mfm num ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)}, now ${esc(c.v)}${c.targetTxt ? ', ' + esc(c.targetTxt) : ''}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval mhero">${esc(c.v)}</b><em class="mwk">${esc(capOf(c))}</em>${chgHtml(c)}`
98
- + `<svg class="nspk" viewBox="0 0 ${W} 30" aria-hidden="true"><path d="${d}"/></svg></div>`;
99
- }
100
- function meterTile(c) {
101
- const v = c.pts[c.pts.length - 1].v, tg = c.target, hi = Math.max(v, tg) * 1.15 || 1, lower = c.dir < 0, ok = lower ? v <= tg : v >= tg;
102
- return `<div class="mt1 mfm prg ${c.chipKind}${c.off ? ' off' : ''}" data-key="${esc(c.key)}" role="img" aria-label="${esc(c.title)} is ${esc(c.v)} against ${lower ? 'a limit' : 'a target'} of ${esc(unitTxt(c, tg))}. ${ok ? 'It is on the right side of it.' : 'It is not there yet.'}"><span class="mlab">${esc(c.title)}${chipOf(c)}</span><b class="mval">${esc(c.v)}</b><em class="mwk">${esc(ok ? (lower ? 'Within the limit' : 'At or past the target') : (lower ? 'Over the limit' : 'Short of the target'))}</em>`
103
- + `<div class="mtrk"><i class="mfil ${ok ? 'ok' : 'warn'}" style="width:${(v / hi * 100).toFixed(1)}%"></i><i class="mtgt" style="left:${(tg / hi * 100).toFixed(1)}%"></i></div>`
104
- + `<span class="mfoot"><i>0</i><i class="tgl">${lower ? 'limit' : 'target'} ${esc(unitTxt(c, tg))}</i><i>${esc(unitTxt(c, hi))}</i></span></div>`;
105
- }
106
- /* The Studio's draft drawn from a measure's chart (premium-studio-chart C2, C7): the latest `range` readings, against the draft's target, as the server's
107
- * lib/insights-premium.js mineOf draws a saved chart. Every point is a reading of the record. */
108
- function deriveChart(base, d) {
109
- const all = base.pts, pts0 = d.range ? all.slice(-d.range) : all.slice();
110
- if (pts0.length < 2) return null;
111
- const tg = d.target === null || d.target === undefined || d.target === '' ? null : +d.target;
112
- const day = (p) => Date.parse(String(p.at).slice(0, 10) + 'T00:00:00Z');
113
- const t0 = day(pts0[0]), span = day(pts0[pts0.length - 1]) - t0 || 1;
114
- const ys = pts0.map((p) => p.v).concat(tg !== null ? [tg] : []), lo = Math.min(...ys), hi = Math.max(...ys), range = hi - lo || 1;
115
- const pts = pts0.map((p) => Object.assign({}, p, { fx: (day(p) - t0) / span, fy: (p.v - lo) / range }));
116
- const now = pts[pts.length - 1], prev = pts[pts.length - 2], step = Math.round((now.v - prev.v) * 100) / 100, dir = d.better === 'lower' ? -1 : 1;
117
- return Object.assign({}, base, {
118
- key: 'draft', title: d.title || base.title, form: d.form, note: d.note || '', pts, v: now.txt, at: now.d, target: tg, targetTxt: tg !== null ? 'target ' + unitTxt(base, tg) : '',
119
- ty: tg !== null ? (tg - lo) / range : null, step, dir, good: step ? step * dir > 0 : null, ticks: [pts[0].d, now.d],
120
- });
121
- }
122
65
  /* Point at reading j: the cursor line, the dot, the value and the date move to it. Without j the tile returns to the latest reading. */
123
66
  function chartAt(t, j) {
124
67
  const c = byKey(t.dataset.key); if (!c) return;
@@ -220,24 +163,19 @@ $('#dashBar').addEventListener('click', (e) => {
220
163
  if (e.target.closest('#pdEdit')) openDashEdit(curDash()); else if (e.target.closest('#pcNew')) openChartEdit(null);
221
164
  });
222
165
 
223
- /* ── a dashboard is made and edited in the Insight Studio (initiative premium-studio-dashboard). Its one press posts POST /api/premium-dashboards/save. ── */
166
+ /* ── dashboards, charts and reports are made and changed in a chat (initiative premium-reports-from-chat, slice C; the Insight Studio is removed).
167
+ * Edit, New chart, the + menu and Shape it open the Chat page: with ?open= it opens that one in the tab beside the chat, with ?say= it puts a first
168
+ * message in the box for the PM to send. Every save is still the PM's press in that tab. ── */
169
+ /* the switches under On your dashboards in a measure's dialog still save a dashboard here (POST /api/premium-dashboards/save) */
224
170
  async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
225
- async function saveChart(body) { return pmPost('/api/premium-charts/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
226
- const structure = {
227
- get: (id) => pmGet('/api/report-structure?ws=' + encodeURIComponent(M.board.ws || '') + '&id=' + encodeURIComponent(id)),
228
- post: (sub, id, body) => pmPost('/api/report-structure/' + sub, Object.assign({ ws: M.board.ws, id }, body)),
229
- };
230
- const design = {
231
- get: (id) => pmGet('/api/report-design?ws=' + encodeURIComponent(M.board.ws || '') + '&id=' + encodeURIComponent(id)),
232
- post: (sub, id, body) => pmPost('/api/report-design/' + sub, Object.assign({ ws: M.board.ws, id }, body)),
233
- };
234
- const studioOf = (o) => openStudio(Object.assign({ M, tile: tileHtml, derive: deriveChart, save: saveDash, saveChart, setup: (sub, body) => repPost(sub, body), structure, design, reportsChanged: () => load(),
235
- done: async (id) => { dash = id || dash; await load(); } }, o));
236
- function openDashEdit(D) { studioOf({ mode: 'dash', D, done: async (id) => { dash = id || null; await load(); } }); }
237
- /* A chart is made and edited in the Studio's Chart mode (initiative premium-studio-chart). Save posts POST /api/premium-charts/save. */
238
- function openChartEdit(id) { studioOf({ mode: 'chart', C: id ? (M.mineSaved || []).find((x) => x.id === id) || null : null }); }
239
- /* A report is set up and shaped in the Studio's Report mode (initiative premium-studio-report). */
240
- function openReportEdit(s) { studioOf({ mode: 'rep', R: s || null }); }
171
+ function toChat(o) {
172
+ const q = new URLSearchParams(); if (M.board.ws) q.set('ws', M.board.ws);
173
+ if (o.open) q.set('open', o.open); if (o.say) q.set('say', o.say);
174
+ location.href = '/premium-chat.html?' + q.toString();
175
+ }
176
+ const openDashEdit = (D) => toChat(D ? { open: 'dashboard:' + D.id } : { say: 'Make a dashboard of ' });
177
+ const openChartEdit = (id) => toChat(id ? { open: 'chart:' + id } : { say: 'Make a chart of ' });
178
+ const openReportEdit = (s) => toChat(s ? { open: 'report:' + s.id } : { say: 'Make a report of ' });
241
179
  $('#dashBody').addEventListener('click', (e) => { const o = e.target.closest('[data-open]'); if (o) { openChart(byKey(o.dataset.open)); return; } const ed = e.target.closest('[data-ced]'); if (ed) openChartEdit(ed.dataset.ced); });
242
180
  $('#dashBody').addEventListener('keydown', (e) => {
243
181
  const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
@@ -269,14 +207,30 @@ function setupRow(s) {
269
207
  const from = L ? (L.lead ? 'From the ' + L.date + ' file' : 'The ' + L.date + ' file has no sentence to quote') : 'No draft is written yet';
270
208
  return `<div class="dmr" role="listitem"><button class="dmo" data-setup="${esc(s.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(s.name)}</b>${line}<small>${esc([from, s.label, s.audience ? 'for ' + s.audience : ''].filter(Boolean).join(' · '))}</small><span class="dmm"><span class="t">Report</span><span class="s ${s.paused ? 'none' : 'issued'}">${s.paused ? 'Paused' : s.drafting ? 'Drafting' : 'Set up'}</span>${s.next && !s.paused ? `<span>Next draft ${esc(s.next)}</span>` : ''}</span></span></button></div>`;
271
209
  }
272
- function repRow(r) {
273
- return `<div class="dmr ${esc(r.state)}" role="listitem"><button class="dmo" data-rep="${esc(r.key)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(r.cadence)} · ${esc(r.date || r.slot)}</b>${r.lead ? insLine('“' + r.lead + '”', true) : ''}<small>${esc(r.path)}</small><span class="dmm"><span class="t">Report</span><span class="s ${esc(r.state === 'issued' ? 'issued' : 'draft')}">${esc(r.stateLabel)}</span><span>Deck, present, download, print</span></span></span></button></div>`;
210
+ /* One row per report (PM 2026-10-22: "Each report should have a list of issued/archived/draft report, so there's no duplication of the same report
211
+ * on the Insight page"): its name, the opening sentence of its latest cycle, and how many cycles are draft, issued and archived. The row opens the
212
+ * latest cycle in the reader, whose cycle chip lists the others. */
213
+ function repRow(g) {
214
+ const L = g.files[0], n = (f) => g.files.filter(f).length, d = n((x) => x.state !== 'issued'), i = n((x) => x.state === 'issued' && !x.archived), a = n((x) => x.archived), s = g.setup;
215
+ const pills = [d ? `<span class="s draft">${d} draft</span>` : '', i ? `<span class="s issued">${i} issued</span>` : '', a ? `<span class="s none">${a} archived</span>` : ''].join('');
216
+ const st = s ? (s.paused ? '<span>Paused</span>' : s.drafting ? '<span>Drafting</span>' : s.next ? `<span>Next draft ${esc(s.next)}</span>` : '') : '<span>No template</span>';
217
+ return `<div class="dmr" role="listitem"><button class="dmo" data-rpt="${esc(g.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(DOCI)}</span><span class="dmn"><b>${esc(g.name)}</b>${L.lead ? insLine('“' + L.lead + '”', true) : ''}<small>${esc('Latest: ' + (L.date || L.slot) + (s && s.label ? ' · ' + s.label : '') + (s && s.audience ? ' · for ' + s.audience : ''))}</small><span class="dmm"><span class="t">Report</span>${pills}${st}</span></span></button></div>`;
218
+ }
219
+ /** The report files grouped by report: a set-up report with files is one report row, one with none keeps its set-up row, and a cadence with
220
+ * files and no template is a report row of its own. Files keep their order (newest first, archived last). */
221
+ function reportGroups() {
222
+ const R = M.reports, by = new Map();
223
+ for (const f of R.missing ? [] : R.rows) { if (!by.has(f.cadence)) by.set(f.cadence, []); by.get(f.cadence).push(f); }
224
+ const out = [];
225
+ for (const s of R.setupsOk === false ? [] : (R.setups || [])) { const fs = by.get(s.id); by.delete(s.id); out.push(fs ? { kind: 'file', x: { id: s.id, name: s.name, setup: s, files: fs } } : { kind: 'setup', x: s }); }
226
+ for (const [id, fs] of by) out.push({ kind: 'file', x: { id, name: id, setup: null, files: fs } });
227
+ return out;
274
228
  }
275
229
  const foundRow = (f) => `<div class="dmr" role="listitem"><button class="dmo" data-found="${esc(f.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(AIC)}</span><span class="dmn"><b>${esc(f.name)}</b><small>${esc(f.why)}</small><span class="dmm">${f.confidence ? `<span>${esc(f.confidence)}</span>` : ''}<span>${f.evidence.length} ${f.evidence.length === 1 ? 'sign' : 'signs'} in your work</span></span></span></button></div>`;
276
230
  const askRow = (a) => `<div class="dmr" role="listitem"><button class="dmo" data-ask="${esc(a.id)}" aria-haspopup="dialog"><span class="dmi c-Board">${ICO(AIC)}</span><span class="dmn"><b>${esc(a.proposal && a.proposal.name ? a.proposal.name : a.text)}</b><small>You asked: ${esc(a.text)}</small><span class="dmm"><span class="s ${ASKST[a.state][1]}">${ASKST[a.state][0]}</span>${a.changed ? '<span>Changed once</span>' : ''}</span></span></button></div>`;
277
231
  function listItems() {
278
- const R = M.reports, d = M.dashboards.map((x) => ({ kind: 'dash', x }));
279
- const r = (R.setupsOk === false ? [] : (R.setups || []).map((x) => ({ kind: 'setup', x }))).concat(R.missing ? [] : R.rows.map((x) => ({ kind: 'file', x })));
232
+ const d = M.dashboards.map((x) => ({ kind: 'dash', x }));
233
+ const r = reportGroups();
280
234
  return { d, r, all: d.concat(r) };
281
235
  }
282
236
  function drawList() {
@@ -320,8 +274,8 @@ $('#repBody').addEventListener('click', (e) => {
320
274
  if (pin) { pin.disabled = true; pinDash(M.pinned === pin.dataset.pin ? null : pin.dataset.pin, 'list'); return; }
321
275
  const d = e.target.closest('[data-d]');
322
276
  if (d) { dash = d.dataset.d; drawDash(); drawList(); try { $('#cDash').scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch { /* no scroll */ } return; }
323
- const rp = e.target.closest('[data-rep]');
324
- if (rp) { const row = M.reports.rows.find((x) => x.key === rp.dataset.rep), su = row && (M.reports.setups || []).find((x) => x.id === row.cadence); openReport(row, { ws: M.board.ws, name: su ? su.name : null, onIssue: () => load() }); return; }
277
+ const rp = e.target.closest('[data-rpt]');
278
+ if (rp) { const g = reportGroups().find((x) => x.kind === 'file' && x.x.id === rp.dataset.rpt); if (g) openReport(g.x.files[0], { ws: M.board.ws, name: g.x.setup ? g.x.setup.name : null, cycles: g.x.files, onIssue: () => load(), onChange: () => load() }); return; }
325
279
  const f = e.target.closest('[data-found]'), a = e.target.closest('[data-ask]'), s = e.target.closest('[data-setup]');
326
280
  if (f) openFound((M.reports.found || []).find((x) => x.id === f.dataset.found));
327
281
  else if (a) openAsk((M.reports.asks || []).find((x) => x.id === a.dataset.ask));
@@ -409,7 +363,7 @@ function openSetup(s) {
409
363
  const rows = [['Schedule', s.label], ['Status', s.paused ? 'Paused' : 'Active'], ['Next draft', s.paused ? '' : s.next], ['Last issued cycle', s.lastIssued], ['Audience', s.audience], ['Output', s.output], ['Documents', String(s.cycles)], ['Purpose', s.purpose]];
410
364
  const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
411
365
  if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
412
- if (s.fromWork) acts.push(['studio', 'Shape it in the Studio', 1]);
366
+ if (s.fromWork) acts.push(['studio', 'Shape it in a chat', 1]);
413
367
  repDlg({ eye: 'Set-up report', title: s.name, facts: rows, say: s.paused ? 'This report is paused. Resume it to draft it on its schedule again.' : 'This report is drafted on its schedule. You can draft the next cycle now or pause it.',
414
368
  html: kv(rows) + `<p class="note">${s.fromWork ? (s.structured ? 'Draft it now starts a background run that follows the saved structure.' : 'Draft it now writes the next cycle as a file at once.') : 'This report is drafted from its dashboard on its day.'} Pause and Resume record a line in the report ledger. Nothing is sent.</p>`,
415
369
  acts, on: {