create-pmos 0.479.0 → 0.481.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 (50) hide show
  1. package/package.json +26 -27
  2. package/payload/KIT-VERSION +1 -1
  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/workspace/briefing-premium-board-test.js +1 -3
  7. package/workspace/briefing-premium-insights-test.js +6 -6
  8. package/workspace/briefing-premium-metrics-test.js +5 -84
  9. package/workspace/briefing-premium-sources-test.js +6 -1
  10. package/workspace/changelog.json +25 -0
  11. package/workspace/guide/briefing-premium.md +11 -4
  12. package/workspace/guide/programs.md +4 -2
  13. package/workspace/lib/board-pack.js +1 -1
  14. package/workspace/lib/goal-chat.js +3 -0
  15. package/workspace/lib/metric-drafts.js +37 -6
  16. package/workspace/lib/ready-reports.js +6 -4
  17. package/workspace/lib/report-chat.js +8 -4
  18. package/workspace/lib/report-draft.js +14 -5
  19. package/workspace/lib/report-structure.js +35 -1
  20. package/workspace/lib/routes-metric-drafts.js +2 -1
  21. package/workspace/lib/routes-ready-reports.js +6 -2
  22. package/workspace/lib/routes-report-setups.js +24 -4
  23. package/workspace/package-lock.json +2 -2
  24. package/workspace/package.json +1 -1
  25. package/workspace/premium-html-viewer-test.js +2 -0
  26. package/workspace/public/pm/bd-acts.js +2 -20
  27. package/workspace/public/pm/bd-prog-panel.js +1 -2
  28. package/workspace/public/pm/cozy-board.css +0 -11
  29. package/workspace/public/pm/cozy-home.css +5 -0
  30. package/workspace/public/pm/cozy-insights.css +31 -0
  31. package/workspace/public/pm/cozy-vw-rp.css +5 -0
  32. package/workspace/public/pm/dash-view.css +19 -0
  33. package/workspace/public/pm/dash-view.js +49 -11
  34. package/workspace/public/pm/goal-chat.js +10 -3
  35. package/workspace/public/pm/home-app.js +31 -89
  36. package/workspace/public/pm/home-chat.js +19 -4
  37. package/workspace/public/pm/home-goal.js +1 -1
  38. package/workspace/public/pm/home-line.js +16 -1
  39. package/workspace/public/pm/home-list.js +1 -1
  40. package/workspace/public/pm/premium-board.js +2 -2
  41. package/workspace/public/pm/premium-insights.js +64 -11
  42. package/workspace/public/pm/premium-report-read.js +42 -5
  43. package/workspace/public/pm/premium-report-tab.js +89 -24
  44. package/workspace/public/pm/premium-vw-file.js +4 -0
  45. package/workspace/public/pm/prog-page.css +1 -1
  46. package/workspace/public/pm/prog-page.js +6 -3
  47. package/workspace/public/pm/report-chat.js +20 -3
  48. package/workspace/public/pm/trends-review.js +55 -0
  49. package/workspace/ready-dash-ui-test.js +1 -3
  50. package/workspace/test-files.json +1 -0
@@ -913,7 +913,6 @@ function openProductPage() {
913
913
  b.onclick = (e) => {
914
914
  const t = e.target.closest('[data-hp]'); if (!t) return;
915
915
  if (t.dataset.hp === 'update') { VW.drill(); openTarget(updateTarget()); openUpdateViewer(); }
916
- else if (t.dataset.hp === 'metrics') { VW.drill(); openMetrics(); }
917
916
  else if (t.dataset.hp === 'talk') talk();
918
917
  else if (t.dataset.hp === 'ini') goIni(t.dataset.k);
919
918
  else if (t.dataset.hp === 'prog') goProgram(t.dataset.k);
@@ -936,24 +935,35 @@ function productPageHtml(x, ws, vid, name, g) {
936
935
  const P = ((S.M && S.M.groups) || []).filter((y) => y.kind === 'program' && (own || ((y.program && y.program.members) || []).some((m) => m && m.ws === ws)));
937
936
  const progs = P.length ? `<section class="pv-card" aria-label="Programs"><div class="pv-ch"><h4>Programs</h4><small>${P.length}</small></div>${P.map((y) => row(`data-hp="prog" data-k="${esc(y.program.id)}"`, '', y.name, y.st && y.st.next ? 'Next: ' + y.st.next.name + (y.st.next.day ? ', ' + y.st.next.day : '') : y.closedLine || '')).join('')}</section>` : '';
938
937
  const budgets = B.length ? `<section class="pv-card" aria-label="Health budgets"><div class="pv-ch"><h4>Health budgets</h4></div>${B.map((y) => PV.goalRow(y)).join('')}</section>` : '';
939
- const props = d && (d.needsN || d.needs) ? { n: d.needsN || 1, sub: (d.needs && d.needs.q) + ((d.needsN || 1) > 1 ? ' and ' + ((d.needsN || 1) - 1) + ' more' : ''), html: DB.needsHtml(d) } : null;
938
+ // the goals Claude would reword join the folded proposals row (batch 22 item 5); the owner's own page only
939
+ const nk = DB.krOf(x.kr).length, nn = d && (d.needsN || d.needs) ? d.needsN || 1 : 0;
940
+ const props = nn || nk ? { n: nn + nk, sub: nn ? d.needs.q + (nn + nk > 1 ? ' and ' + (nn + nk - 1) + ' more' : '') : nk === 1 ? 'Reword ' + (x.kr.items[0].goal || 'a goal') : nk + ' goals would read better reworded',
941
+ html: (d ? DB.needsHtml(d) : '') + DB.krHtml(x.kr) } : null;
940
942
  // the initiatives and their tasks, as Home's list holds them; the launch range from the page model when it has one (Ships next)
941
- const inis = g ? (g.inis || []).concat(g.rest || []) : [];
943
+ const own0 = g ? (g.inis || []).concat(g.rest || []) : [];
944
+ // this product's initiatives that sit in a program: Home lists them once, under the program, and took them out of g; the product page still
945
+ // counts and lists them, one card per program (batch 22 item 1)
946
+ const mine = (sp) => (ws && sp.ws ? sp.ws === ws : sp.name === name);
947
+ const inProg = ((S.M && S.M.groups) || []).filter((y) => y.kind === 'program').map((y) => ({ y, inis: (y.subs || []).filter(mine).flatMap((sp) => sp.inis || []) })).filter((x) => x.inis.length);
948
+ const inis = own0.concat(...inProg.map((x) => x.inis));
942
949
  const ships = new Map((((d && d.stage && d.stage.kind === 'ships-next') ? d.stage.items.concat((d.stage.more && d.stage.more.items) || []) : [])).map((y) => [y.id, y]));
943
950
  const T = inis.flatMap((i) => (i.tasks || []).map((t) => ({ ...t, of: i.name })));
944
951
  const late = T.filter((t) => t.late);
945
- const iniRows = inis.map((i) => { const sh = ships.get(i.ini); const when = sh ? (sh.lo && sh.hi && sh.lo !== sh.hi ? sh.lo + ' to ' + sh.hi : sh.when) : '';
946
- return row(`data-hp="ini" data-k="${esc(i.ini)}"`, `<span class="db-dot ${sh && /behind|risk/.test(sh.dot) ? 'risk' : sh && sh.dot === 'on' ? 'ok' : 'q'}" aria-hidden="true"></span>`, i.name, [when ? 'Ships ' + when : '', i.right].filter(Boolean).join(' · '), i.stage ? `<span class="pv-pill">${esc(i.stage)}</span>` : ''); }).join('');
952
+ const iniRow = (i) => { const sh = ships.get(i.ini); const when = sh ? (sh.lo && sh.hi && sh.lo !== sh.hi ? sh.lo + ' to ' + sh.hi : sh.when) : '';
953
+ return row(`data-hp="ini" data-k="${esc(i.ini)}"`, `<span class="db-dot ${sh && /behind|risk/.test(sh.dot) ? 'risk' : sh && sh.dot === 'on' ? 'ok' : 'q'}" aria-hidden="true"></span>`, i.name, [when ? 'Ships ' + when : '', i.right].filter(Boolean).join(' · '), i.stage ? `<span class="pv-pill">${esc(i.stage)}</span>` : ''); };
954
+ const nIni = (n) => (n === 1 ? '1 initiative' : n + ' initiatives');
955
+ const iniCards = (own0.length ? `<section class="pv-card" aria-label="Initiatives"><div class="pv-ch"><h4>${esc(name)}</h4><small>${nIni(own0.length)}</small></div>${own0.map(iniRow).join('')}</section>` : '')
956
+ + inProg.map((x) => `<section class="pv-card" aria-label="${esc(x.y.name)}"><div class="pv-ch"><h4>${SVG(TD.P.layers, 15)}${esc(x.y.name)}</h4><small>${nIni(x.inis.length)}</small></div>${x.inis.map(iniRow).join('')}</section>`).join('');
947
957
  const tRow = (t) => row(`data-hp="ini" data-k="${esc(t.ini)}"`, '', t.name, t.of, t.late && t.due ? `<span class="pv-late">${esc(lateDays(t.due) + ' days late')}</span>` : '');
948
958
  const U = own ? H.weeklyUpdate(S.D, S.D.now) : null, sent = U && (U.sent || []).some((y) => y.week === U.week.iso);
949
959
  const R = d ? DB.reportsHtml(d, { open: x.open }) : '';
950
- const extra = own ? row('data-hp="metrics"', '', 'Metrics review', 'With Strategist') + (R ? '' : row('data-hp="update"', '', 'Weekly update', sent ? 'Sent this week' : 'Ready to send'))
951
- : `<a class="pv-row" href="${esc(ownHome)}" target="_blank" rel="noopener"><span class="pv-rt"><b>Weekly update and metrics review</b><small>In ${esc(name)}'s own Home, in a new tab</small></span></a>`;
960
+ const extra = own ? (R ? '' : row('data-hp="update"', '', 'Weekly update', sent ? 'Sent this week' : 'Ready to send'))
961
+ : `<a class="pv-row" href="${esc(ownHome)}" target="_blank" rel="noopener"><span class="pv-rt"><b>Weekly update</b><small>In ${esc(name)}'s own Home, in a new tab</small></span></a>`;
952
962
  const reps = ((d && d.reports) || []).filter((r) => r.kind !== 'heads-up');
953
963
  const tabs = [
954
964
  { id: 'tasks', label: 'Tasks', n: T.length, sig: late.length ? 'late' : '', html: () => (T.length ? (late.length ? `<section class="pv-card" aria-label="Late"><div class="pv-ch"><h4>Late first</h4><small>${late.length > 3 ? '3 shown · ' + (late.length - 3) + ' more below' : ''}</small></div>${late.slice(0, 3).map(tRow).join('')}</section>` : '')
955
965
  + `<section class="pv-card" aria-label="Open tasks"><div class="pv-ch"><h4>Open tasks</h4><small>${T.length}</small></div>${T.filter((t) => !late.slice(0, 3).includes(t)).map(tRow).join('')}</section>` : '<p class="pv-none">No open task on its initiatives.</p>') },
956
- { id: 'initiatives', label: 'Initiatives', n: inis.length, html: () => (inis.length ? `<section class="pv-card" aria-label="Initiatives"><div class="pv-ch"><h4>${esc(name)}</h4><small>${inis.length === 1 ? '1 initiative' : inis.length + ' initiatives'}</small></div>${iniRows}</section>` : '<p class="pv-none">Nothing is open. A new initiative shows here.</p>') },
966
+ { id: 'initiatives', label: 'Initiatives', n: inis.length, html: () => (inis.length ? iniCards : '<p class="pv-none">Nothing is open. A new initiative shows here.</p>') },
957
967
  { id: 'reports', label: 'Reports', n: reps.length, sig: reps.some((r) => r.state === 'drafted') ? 'ready' : '', html: () => `<div class="db" data-level="product">${d ? DB.trustHtml(d) : ''}${R}</div><section class="pv-card" aria-label="More reports">${extra}</section>` },
958
968
  { id: 'documents', label: 'Documents', html: () => '<p class="pv-none">Each initiative keeps its PRD, rubric and release notes on its own page. Open one from Initiatives.</p>' },
959
969
  ];
@@ -962,18 +972,17 @@ function productPageHtml(x, ws, vid, name, g) {
962
972
  tail: isPhone() ? `<button type="button" class="hi-talk" data-hp="talk">Message Claude about ${esc(name)}</button>` : '' });
963
973
  }
964
974
  function productDash(b, ws, vid, name, g) {
965
- const x = PDASH.get(ws) || { d: null, open: new Set() }; PDASH.set(ws, x);
975
+ const x = PDASH.get(ws) || { d: null, kr: null, open: new Set() }; PDASH.set(ws, x);
966
976
  const paint = () => {
967
977
  const c = VW.current(); if (!b.isConnected || !c || c.id !== vid) return;
968
978
  b.innerHTML = productPageHtml(x, ws, vid, name, g);
969
979
  if (!(x.d && (x.d.goals || []).some((y) => !y.budget))) fillGoals(b, ws); // no goal in the page model yet: the goals line of /api/goal-status
970
980
  };
971
981
  PV.wirePage(b, { redraw: paint });
972
- if (b.dataset.dbWired !== ws) {
973
- b.dataset.dbWired = ws;
974
- DB.wireDash(b, { d: () => x.d, open: x.open, ws, toast, redraw: paint,
975
- // the metrics review, as the page offered before it was the dashboard: here for the board's product, in its own Home for another
976
- metrics: () => { if (vid === 'product') { VW.drill(); openMetrics(); } else window.open('/premium.html?ws=' + encodeURIComponent(ws) + '&ini=product&view=metrics', '_blank', 'noopener'); }, reload: async () => { const d = await DB.readDash(ws, 'product', 'read'); if (d) x.d = d; paint(); },
982
+ {
983
+ DB.wireDash(b, { d: () => x.d, open: x.open, ws, toast, redraw: paint, kr: () => x.kr, reloadKr: async () => { x.kr = await DB.readKr(ws); },
984
+ // the chart icon at the Goals block's head: Intelligence › Delivery trends, of this product
985
+ metrics: () => openMetrics(ws), reload: async () => { const d = await DB.readDash(ws, 'product', 'read'); if (d) x.d = d; paint(); },
977
986
  openReport: async (row) => {
978
987
  // Home's own weekly update (desk: true, 1-A) opens its update flow, not a document
979
988
  if (row.desk) { if (vid === 'product') { VW.drill(); openTarget(updateTarget()); openUpdateViewer(); } else window.open('/premium.html?ws=' + encodeURIComponent(ws) + '&ini=product', '_blank', 'noopener'); return; }
@@ -981,6 +990,7 @@ function productDash(b, ws, vid, name, g) {
981
990
  }
982
991
  paint();
983
992
  DB.readDash(ws, 'product', 'read').then((d) => { if (d) { x.d = d; paint(); } });
993
+ DB.readKr(ws).then((k) => { x.kr = k; if (DB.krOf(k).length) paint(); });
984
994
  }
985
995
  /** A phone: the page's "Message Claude about …" closes the sheet and opens the chat full screen; its ← goes back to the list (HbCPhone). */
986
996
  function talk() { S.phoneChat = true; VW.close(); drawList(); chat.focus(); }
@@ -1068,13 +1078,13 @@ function select(id, o = {}) {
1068
1078
  if (isPhone() && (r.kind === 'update' || (r.kind === 'need' && r.row) || r.kind === 'session' || r.needSession)) S.phoneChat = true;
1069
1079
  if (r.kind === 'update') { openTarget(updateTarget()); if (!o.keepViewer) openUpdateViewer(); }
1070
1080
  else if (r.kind === 'need' && r.row) { openTarget(needTarget(r)); if (!o.keepViewer) openNeedViewer(r); }
1071
- else if (r.kind === 'session' || r.needSession) { const s = S.D.sessions.find((x) => x.id === r.sid); if (s) { openTarget(sessionTarget(s)); followViewer(s); if (isMetricsSession(s) && !o.keepViewer && !isPhone()) openMetricsViewer(); } }
1081
+ else if (r.kind === 'session' || r.needSession) { const s = S.D.sessions.find((x) => x.id === r.sid); if (s) { openTarget(sessionTarget(s)); followViewer(s); } }
1072
1082
  else if (r.kind === 'ptask') { S.phoneChat = isPhone(); openTarget(programTarget(r.program, r)); }
1073
1083
  else if (r.kind === 'task') { openBoardTask(r.task); }
1074
1084
  else if (r.kind === 'item') { import('./home-work.js').then((M) => M.openWorkItem(r.key)); }
1075
1085
  else if (r.kind === 'finished') { openFinished(r.finished); }
1076
1086
  else if (r.kind === 'meeting') { openMeeting(r.meeting); }
1077
- else if (r.kind === 'routine') { if (isMetrics(r.schedule)) openMetrics(o); else openRoutine(r.schedule); }
1087
+ else if (r.kind === 'routine') { if (isMetrics(r.schedule)) openMetrics(); else openRoutine(r.schedule); }
1078
1088
  else if (r.kind === 'file') { openFile(r.file); }
1079
1089
  else if (r.kind === 'person') { openPerson(r.person); }
1080
1090
  drawList();
@@ -1518,79 +1528,11 @@ async function openFile(f) {
1518
1528
  const personCtx = () => { const id = S.ini; return { VW, pmPost, toast: (m, undo) => (undo ? toastUndo(m, undo) : toast(m)), ws: deskWs(), ini: id, iniTitle: iniTitle(id), saved: () => load(), back: () => VW.back() }; };
1519
1529
  function openPerson(p) { SV.openPersonVw(p, { ...personCtx(), back: null }); }
1520
1530
  function addPerson() { SV.openPersonForm(personCtx()); }
1521
- /* ── the metrics review (AgMetrics): the Strategist's conversation, and the review in the Viewer: three tiles, the correction rate by week
1522
- * (the current week in blue) and what moved it. Every number is a record of the product's repository (GET /api/board-metrics-premium:
1523
- * corrections from its run log, merges from its trunk, blocked from its workflow state); a measure that is not read says so. ── */
1524
- const STRAT = { key: 'strategy', name: 'Strategist', initial: 'St' };
1525
- const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
1531
+ /* ── the metrics review is Intelligence › Delivery trends (batch 22 item 4): the month in one ✦ line, the six tiles, what moved it and the goals
1532
+ * that moved. Every old door (the routine, ?view=metrics, the product page's chart icon) opens that view; nothing here keeps a second page. ── */
1526
1533
  const isMetrics = (s) => /metric/i.test(String((s && [s.task, s.skill, s.name, s.label].filter(Boolean).join(' ')) || ''));
1527
- const isMetricsSession = (s) => /^chat:metrics-review/.test(H.keyOfSession(s) || '') || (H.roleOf(s, S.D.desk && S.D.desk.roles).key === 'strategy' && /metric/i.test(H.nameOf(s) || ''));
1528
- let MET = null;
1529
- async function metricsModel() {
1530
- if (MET && MET.model && Date.now() - MET.at < 60000) return MET.model;
1531
- const b = (S.D.board && S.D.board.board) || {};
1532
- const r = await getRetry('/api/board-metrics-premium?weeks=8' + (b.ws ? '&ws=' + encodeURIComponent(b.ws) : wsQ('&')), 6);
1533
- MET = { at: Date.now(), model: r && r.ok && r.model ? r.model : null, error: r && !r.ok ? r.error || 'the metrics were not read' : '' };
1534
- return MET.model;
1535
- }
1536
- /** The review from the metrics model: { tiles, bars, moved, line }. Pure over the model and the product card. */
1537
- function metricsView(m) {
1538
- const T = (k) => ((m && m.tiles) || []).find((t) => t.key === k) || null;
1539
- const two = (v) => (v == null ? null : (v / 100).toFixed(2)); // per 100 runs → per agent run, as the mockup reads it
1540
- const cor = T('corrections'), mer = T('merges'), blk = T('blocked');
1541
- const ser = cor && !cor.absent ? cor.ser : [];
1542
- const idx = ser.map((v, i) => (v != null ? i : -1)).filter((i) => i >= 0);
1543
- const cur = idx.length ? ser[idx[idx.length - 1]] : null, prev = idx.length > 1 ? ser[idx[idx.length - 2]] : null;
1544
- const tile = (t, label, value, note) => (!t ? null : t.absent ? { label, value: '–', note: t.absent } : { label, value, note });
1545
- const tiles = [
1546
- tile(cor, 'Correction rate', two(cur), prev != null ? 'Was ' + two(prev) + ' the week before' : cor && cor.text),
1547
- tile(mer, 'Merged a week', mer && mer.value, mer && (mer.change ? mer.change.txt : mer.text)),
1548
- tile(blk, 'Blocked', blk && blk.value, blk && blk.text),
1549
- ].filter(Boolean);
1550
- const last6 = ser.slice(-6), wk = (cor && cor.wk ? cor.wk : []).slice(-6);
1551
- const mx = Math.max(0, ...last6.filter((v) => v != null)) || 1;
1552
- const bars = last6.map((v, i) => ({ v: v == null ? '–' : two(v), h: v == null ? 0 : Math.max(4, Math.round(v / mx * 100)), w: 'W' + (i + 1), week: wk[i] || '', now: i === last6.length - 1 }));
1553
- const moved = ((m && m.tiles) || []).filter((t) => !t.absent && t.change && t.change.txt !== 'No change').map((t) => [t.label + (t.text ? ' · ' + t.text : ''), t.change.txt]);
1554
- for (const x of H.productCard(S.D, S.D.now).items.filter((i) => i.kind === 'risk')) moved.push([x.label, 'At risk']);
1555
- const month = MONTHS[new Date(S.D.now).getMonth()];
1556
- const line = cur == null ? month + ': no week has enough agent runs to count a correction rate yet.'
1557
- : month + ' in one line: the correction rate ' + (prev == null ? 'is ' + two(cur) + ' per agent run' : prev === cur ? 'held at ' + two(cur) + ' per agent run' : (cur < prev ? 'fell' : 'rose') + ' from ' + two(prev) + ' to ' + two(cur) + ' per agent run' + (cur < prev ? ', the direction you want' : ', the wrong direction')) + '.'
1558
- + (moved.length ? ' ' + moved.length + (moved.length === 1 ? ' thing' : ' things') + ' moved this month.' : '');
1559
- return { tiles, bars, moved, line, month, empty: !m };
1560
- }
1561
- function openMetricsViewer() {
1562
- const draw = (b) => {
1563
- const m = MET && MET.model, V = metricsView(m);
1564
- if (!m) { b.innerHTML = `<div class="hv"><p class="hx-n" role="status">${MET && MET.error ? 'The metrics were not read: ' + esc(MET.error) + '.' : 'Reading the metrics.'}</p></div>`; return; }
1565
- // shell A (canvas XvAMetrics): the summary card leads with the correction rate and the month in one line; the weekly bars follow;
1566
- // the other tiles and what moved it are rows below. There is no primary: nothing here writes (honest state).
1567
- const [first, ...rest] = V.tiles;
1568
- const fell = /fell/.test(V.line), rose = /rose/.test(V.line);
1569
- b.innerHTML = VW.czSummary({ line: first ? first.label + ' ' + first.value : '', tone: rose ? 'warn' : fell ? 'ok' : '', text: V.line, meta: (m && m.note) || '' })
1570
- + (V.bars.length ? `<figure class="hm-fig"><figcaption>Correction rate per agent run, by week (lower is better)</figcaption><div class="hm-chart" role="img" aria-label="${esc('Correction rate by week: ' + V.bars.map((x) => x.w + ' ' + x.v).join(', '))}">${V.bars.map((x) => `<div title="${esc(x.week ? 'Week to ' + x.week : x.w)}"><span>${esc(x.v)}</span><i class="${x.now ? 'now' : ''}" data-h="${x.h}"></i></div>`).join('')}</div><div class="hm-chx" aria-hidden="true">${V.bars.map((x) => `<span>${x.w}</span>`).join('')}</div></figure>` : '')
1571
- + VW.czSections([{ id: 'moved', title: 'What moved it', count: V.moved.length, open: true,
1572
- html: `<table class="hm-moved"><thead><tr><th scope="col">What moved it</th><th scope="col">Effect</th></tr></thead><tbody>${V.moved.map(([n, e]) => `<tr><td>${esc(n)}</td><td>${esc(e)}</td></tr>`).join('') || '<tr><td colspan="2">Nothing moved since the week before.</td></tr>'}</tbody></table>` }]
1573
- .concat(rest.map((t, i) => ({ id: 't' + i, title: t.label, count: t.value, html: t.note ? `<p>${esc(t.note)}</p>` : '' }))), { key: 'metrics' }); // the first tile's note (was N the week before) is already in the line: said once
1574
- b.querySelectorAll('.hm-chart i[data-h]').forEach((i) => i.style.setProperty('--bd-h', i.dataset.h + 'px')); // each bar's height: run-time geometry
1575
- };
1576
- const body = VW.open({ id: 'metrics', kind: 'Metrics review', title: H.productName(S.D) + ' · ' + MONTHS[new Date(S.D.now).getMonth()], icon: I.chart, url: selfUrl({ ini: 'product', view: 'metrics' }), render: draw });
1577
- if (!(MET && MET.model)) metricsModel().then(() => { if (VW.current() && VW.current().id === 'metrics' && body.isConnected) draw(body); });
1578
- }
1579
- function metricsTarget() {
1580
- const V = metricsView(MET && MET.model);
1581
- return { key: 'chat:metrics-review', ini: 'product', ws: WS || undefined, title: 'Metrics review', sub: 'Strategist · ' + V.month, scope: scopeOf('product'), rich: rich(), role: STRAT, to: null,
1582
- intro: { role: STRAT, text: MET ? V.line : 'Reading the metrics of ' + H.productName(S.D) + '.', pills: [{ label: 'Open the review', primary: true, go: () => openMetricsViewer() }, { label: 'Discuss', go: () => chat.focus() }] },
1583
- context: 'The metrics review of ' + H.productName(S.D) + ': ' + V.tiles.map((t) => t.label + ' ' + t.value + (t.note ? ' (' + t.note + ')' : '')).join('; ') + '. What moved: ' + (V.moved.map((x) => x.join(' ')).join('; ') || 'nothing') + '.',
1584
- placeholder: 'Ask Strategist about the metrics', also: null };
1585
- }
1586
- async function openMetrics(o = {}) {
1587
- const id = S.sel;
1588
- openTarget(metricsTarget());
1589
- if (!o.keepViewer && !isPhone()) openMetricsViewer();
1590
- await metricsModel();
1591
- if (S.sel !== id) return;
1592
- openTarget(metricsTarget());
1593
- }
1534
+ const trendsHref = (ws) => '/premium-intelligence.html?' + (ws ? 'ws=' + encodeURIComponent(ws) + '&' : '') + 'view=trends';
1535
+ function openMetrics(ws) { location.assign(trendsHref(ws || boardWs() || deskWs() || '')); }
1594
1536
  function openRoutine(s) { SV.openRoutineVw(s, { VW, now: S.D && S.D.now }); }
1595
1537
 
1596
1538
  /* the agent's terminal, read only, in the Viewer (term-view.js) */
@@ -2014,7 +1956,7 @@ load().then(() => {
2014
1956
  // the Board's program panel Discuss in chat names board:program:<id>: the program's own conversation, the one its tasks open (bug 2026-10-24)
2015
1957
  else if (about && /^board:program:[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/.test(about)) openTarget(programTarget(about.slice(14)));
2016
1958
  else if (about) { openTarget({ ...homeTarget(), key: about, title: (P.get('label') || '').slice(0, 80) || about }); discussed(about, P.get('vid'), P.get('label')); }
2017
- else if (S.ini && P.get('view') === 'metrics') goIni(S.ini).then(() => openMetrics()); // ?view=metrics: the metrics review, as its Open in a new tab names it
1959
+ else if (P.get('view') === 'metrics') openMetrics(P.get('ws') || ''); // ?view=metrics: an old link lands on Intelligence › Delivery trends
2018
1960
  else if (S.ini) goIni(S.ini);
2019
1961
  else if (!isPhone() && !blockOpen && !say && !VW.isOpen()) { const first = H.needsOf(S.D)[0]; if (first) select(first.id); } // a card the PM opened while Home was reading stays
2020
1962
  if (blockOpen) {
@@ -159,8 +159,11 @@ export function mountChat(el, host) {
159
159
  }
160
160
  function queuedHtml() {
161
161
  const q = host.queued ? host.queued(sid()) : [];
162
- const said = new Set(((C.conv && C.conv.messages) || []).filter((m) => m.role === 'user').map((m) => shownUser(m.text))); // as typed: PMOS wraps a report ask in its rule
163
- return q.filter((x) => !said.has(shownUser(x.text))).map((x) => `<div class="hm-q"><div class="hm-qb">${userHtml(x.text)}</div><span class="hm-qn">${esc(role().name)} reads it after this tool call, in seconds<button type="button" class="hm-qx" data-hm-qdel="${esc(x.at)}" aria-label="Take it back" title="Take it back">${SVG(XX, 13)}</button></span></div>`).join('');
162
+ // as typed: PMOS wraps a report ask or a /goal in its rule, adds the files line, and a live session joins the lines (batch 22 item 10:
163
+ // a /goal sent with a file stayed "reads it after this tool call" after Claude had read it), so compare the words alone
164
+ const key = (t) => splitFiles(shownUser(t)).text.replace(/\s+/g, ' ').trim();
165
+ const said = new Set(((C.conv && C.conv.messages) || []).filter((m) => m.role === 'user').map((m) => key(m.text)));
166
+ return q.filter((x) => !said.has(key(x.text))).map((x) => `<div class="hm-q"><div class="hm-qb">${userHtml(x.text)}</div><span class="hm-qn">${esc(role().name)} reads it after this tool call, in seconds<button type="button" class="hm-qx" data-hm-qdel="${esc(x.at)}" aria-label="Take it back" title="Take it back">${SVG(XX, 13)}</button></span></div>`).join('');
164
167
  }
165
168
  const sid = () => (C.t && C.t.sid) || (C.th && C.th.session) || null;
166
169
  // A loose chat that reads like one initiative gets one quiet chip at its top: "Looks like <initiative> · Link it ×" (XvALinkSuggest).
@@ -257,11 +260,19 @@ export function mountChat(el, host) {
257
260
  put(pl, h); pl.hidden = !h;
258
261
  }
259
262
  /** The Goal view in the Viewer: the steps of a goal or session at work, else the goal's plan or how it ended. */
263
+ /** The draft of Claude's newest goal question: what is known so far, before a plan is ready. */
264
+ function askedDraft() {
265
+ const ms = (C.conv && C.conv.messages) || [];
266
+ for (let i = ms.length - 1; i >= 0; i--) { if (ms[i].role !== 'assistant') continue; const b = splitGoal(ms[i].text).block; if (b && b.draft && typeof b.draft === 'object' && Object.keys(b.draft).length) return b.draft; }
267
+ return null;
268
+ }
260
269
  function goalViewNow() {
261
270
  const vo = GU.viewOpts(); // the plan editor, while the PM changes a working goal in the Viewer (home-goal.js)
262
271
  if (vo.edit) return goalViewHtml(C.th && C.th.goal, readyDraft(C.conv), vo);
263
272
  const m = lineModel({ view: true }), g = C.th && C.th.goal;
264
273
  if (m && m.kind === 'goal' && g && (g.state === 'started' || g.state === 'waiting')) m.change = true;
274
+ // while the goal is still being agreed, the Viewer shows the goal as agreed so far, not an empty "Steps" (batch 22 item 10)
275
+ if (g && g.state === 'grilling') { const h = goalViewHtml(g, readyDraft(C.conv) || askedDraft(), vo); if (h) return h; }
265
276
  return m ? viewHtml(m) : goalViewHtml(g, readyDraft(C.conv), vo);
266
277
  }
267
278
  function plPress(k) {
@@ -331,7 +342,7 @@ export function mountChat(el, host) {
331
342
  function openGoal() {
332
343
  const html = goalViewNow(); if (!html) return null;
333
344
  const m = lineModel({ view: true });
334
- return import('./premium-viewer.js').then((V) => { V.vwStyle('doc'); return V.vwOpen({ id: 'goal', title: m && m.kind !== 'goal' ? 'Steps' : 'Goal', icon: 'goal', render: (p) => { p.innerHTML = p.__h = goalViewNow(); GU.fill(p); GU.wire(p); p.onclick = async (e) => { const b = e.target.closest('[data-pl]'); if (b) { plPress(b.dataset.pl); return; } const gb = e.target.closest('button'); if (gb && await GU.press(gb)) return; const g = e.target.closest('[data-goal]'); if (g) goalPress(g); }; } }); }).then((r) => { drawLine(); return r; });
345
+ return import('./premium-viewer.js').then((V) => { V.vwStyle('doc'); return V.vwOpen({ id: 'goal', title: m && m.kind !== 'goal' && !(C.th && C.th.goal && C.th.goal.state === 'grilling') ? 'Steps' : 'Goal', icon: 'goal', render: (p) => { p.innerHTML = p.__h = goalViewNow(); GU.fill(p); GU.wire(p); p.onclick = async (e) => { const b = e.target.closest('[data-pl]'); if (b) { plPress(b.dataset.pl); return; } const gb = e.target.closest('button'); if (gb && await GU.press(gb)) return; const g = e.target.closest('[data-goal]'); if (g) goalPress(g); }; } }); }).then((r) => { drawLine(); return r; });
335
346
  }
336
347
  async function goalPress(gb) {
337
348
  const act = gb.dataset.goal;
@@ -468,7 +479,11 @@ export function mountChat(el, host) {
468
479
  if ('goalOpen' in d) { e.preventDefault(); openGoal(); return; }
469
480
  if (await GU.press(b)) return; // home-goal.js: the method menu, the plan editor, skip and Undo, the /goal choice
470
481
  if (d.goal) { goalPress(b); return; }
471
- if (d.chatSay) { b.disabled = true; send(d.chatSay); return; }
482
+ if (d.chatSay) { // a goal answer stays pressed until Claude's next turn (batch 22 item 10: a press did not feel pressed)
483
+ b.disabled = true; b.classList.add('on');
484
+ if (b.classList.contains('gchip')) { C.said = { n: ((C.conv && C.conv.messages) || []).length, text: d.chatSay }; b.parentElement.querySelectorAll('button').forEach((x) => { x.disabled = true; }); }
485
+ send(d.chatSay); return;
486
+ }
472
487
  if (d.slash) { pickSlash(d.slash); return; }
473
488
  if (d.askPick) {
474
489
  const card = b.closest('.tc'), btn = card && card.querySelector('[data-ask-send]'), at = btn ? btn.dataset.askSend : null, ask = at != null && askOf(at); if (!ask) return;
@@ -36,7 +36,7 @@ export function goalUi(cx) {
36
36
  function blockOpts(mi, block, live) {
37
37
  const g = goal();
38
38
  const b = block && block.step === 'ready' && mi === newestReady() ? { ...block, draft: readyDraft() || block.draft } : block;
39
- return { block: b, live, state: g && g.state, menu: live && C.goalMenu === mi, edit: live && C.goalEdit && C.goalEdit.where === 'chat' ? C.goalEdit.snap : null };
39
+ return { block: b, live, state: g && g.state, menu: live && C.goalMenu === mi, edit: live && C.goalEdit && C.goalEdit.where === 'chat' ? C.goalEdit.snap : null, said: live && C.said && C.said.n === ((C.conv && C.conv.messages) || []).length ? C.said.text : '' };
40
40
  }
41
41
  /** The Goal view in the Viewer: the editor while the PM changes a working goal there. */
42
42
  const viewOpts = () => ({ live: cx.live(), edit: C.goalEdit && C.goalEdit.where === 'view' ? C.goalEdit.snap : null });
@@ -68,13 +68,28 @@ function window5(items, cur, all) {
68
68
  return { items: items.slice(from, from + CAP), more: items.length };
69
69
  }
70
70
 
71
+ const normP = (x) => String(x == null ? '' : x).toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
72
+ /** The same match as lib/goal-chat.js matchPoints: equal, or one holds the other when both are 12 characters or more. */
73
+ const samePoint = (a, b) => { const n = normP(a), r = normP(b); return !!n && !!r && (n === r || (r.length >= 12 && n.length >= 12 && (r.includes(n) || n.includes(r)))); };
74
+ /** The done points the session's to-do list marks completed, and the one it marks in progress. */
75
+ export function liveOf(pts, conv) {
76
+ const steps = conv && Array.isArray(conv.steps) ? conv.steps : [];
77
+ const done = pts.filter((p) => steps.some((s) => s && s.state === 'done' && samePoint(p, s.text)));
78
+ const st = steps.find((s) => s && s.state === 'now'), now = st ? pts.find((p) => samePoint(p, st.text)) || null : null;
79
+ return { done, now };
80
+ }
71
81
  /** A working goal (started, or waiting on the PM) as the line's model. goal: the GET /thread goal record. */
72
82
  export function goalModel(goal, conv, o = {}) {
73
83
  if (!goal || !goal.draft || !['started', 'waiting'].includes(goal.state)) return null;
74
84
  const d = goal.draft, pts = Array.isArray(d.done) ? d.done : [], met = new Set(goal.met || []);
75
85
  const skip = new Set(goal.skipped || []);
86
+ // live, inside a round (batch 22 item 11): the session's own to-do list names the done points (lib/goal-chat.js startMessage), so a
87
+ // point Claude marked completed ticks now and the one in progress is the current one. The round's report still decides at its end.
88
+ const live = liveOf(pts, conv);
89
+ for (const x of live.done) met.add(x);
76
90
  const count = pts.filter((x) => !skip.has(x)).length;
77
- const cur = pts.findIndex((x) => !met.has(x) && !skip.has(x));
91
+ const nowAt = live.now ? pts.indexOf(live.now) : -1;
92
+ const cur = nowAt >= 0 && !met.has(live.now) && !skip.has(live.now) ? nowAt : pts.findIndex((x) => !met.has(x) && !skip.has(x));
78
93
  const limit = Number.isInteger(d.limit) ? d.limit : 12;
79
94
  const asking = goal.state === 'waiting' || !!o.asking;
80
95
  const run = running(conv) || goal.state === 'started';
@@ -186,7 +186,7 @@ export function programGroups(D, groups, products, o, now) {
186
186
  return { id: 'pt:' + pr.id + ':' + t.key, kind: 'ptask', program: pr.id, key: t.key, ws: t.ws, name: t.title, check: true, state: 'quiet', mine: isMe(D, t.owner), late: d != null && d < 0, due: t.due || '',
187
187
  hint: [t.owner, d == null ? '' : d < 0 ? plural(-d, 'day', 'days') + ' late' : d === 0 ? 'due today' : 'due ' + shortDay(t.due)].filter(Boolean).join(' · ') };
188
188
  });
189
- const subs = ((G && G.products) || []).map((sp) => { const at = products.findIndex((p) => p.name === sp.name); return { name: sp.name, initials: at >= 0 ? products[at].initials : initialsOf(sp.name), tone: at >= 0 ? products[at].tone : 0, inis: sp.rows.map((x) => x.r) }; });
189
+ const subs = ((G && G.products) || []).map((sp) => { const at = products.findIndex((p) => p.name === sp.name); return { name: sp.name, ws: at >= 0 ? products[at].ws || '' : '', initials: at >= 0 ? products[at].initials : initialsOf(sp.name), tone: at >= 0 ? products[at].tone : 0, inis: sp.rows.map((x) => x.r) }; });
190
190
  const inis = subs.flatMap((x) => x.inis);
191
191
  // a program with no open initiative here (just made, or its initiatives all cancelled or archived) still shows, under all products or its
192
192
  // home product, so the PM finds it and can move initiatives in; an unticked home product takes it off Home (batch 12 item 5)
@@ -895,11 +895,11 @@ async function loadDocMeta(list) {
895
895
  const docMeta = (p, ws) => { const d = DM[(ws || (M && M.board.ws) || '') + ':' + p]; return d && !d.none ? d : null; };
896
896
 
897
897
  /* ── the shell's bell sits before New initiative, as the design orders the tools; Escape closes a popover, then the panel ──────── */
898
- /* the ⋯ menu ("More: sources, archived, export" in AgBoard and BdHead): the Board adds Metrics and Cancelled and archived */
898
+ /* the ⋯ menu ("More: sources, archived, export" in AgBoard and BdHead): the Board adds Cancelled and archived (Metrics moved to Intelligence › Delivery trends, batch 22 item 4) */
899
899
  {
900
900
  const st = $('#settingsBtn'), mb = $('#moreBtn');
901
901
  if (mb) { mb.setAttribute('aria-label', 'More: sources, archived, export'); mb.title = 'More: sources, archived, export'; }
902
- if (st) st.insertAdjacentHTML('beforebegin', ['metrics', 'gone'].map((k) => `<button role="menuitem" id="${k === 'metrics' ? 'bdMetrics' : 'bdGone'}" aria-haspopup="dialog" data-open="${k}">${k === 'metrics' ? 'Metrics' : 'Cancelled and archived'}</button>`).join(''));
902
+ if (st) st.insertAdjacentHTML('beforebegin', '<button role="menuitem" id="bdGone" aria-haspopup="dialog" data-open="gone">Cancelled and archived</button>');
903
903
  $$('#moreMenu [data-open]').forEach((b) => { b.onclick = () => { if (M) Acts.open[b.dataset.open]($('#moreBtn')); }; });
904
904
  }
905
905
  window.addEventListener('keydown', (e) => {
@@ -40,6 +40,7 @@ import * as IM from './impact.js'; // Your impact's ✦ line (batch 16 item 7)
40
40
  import * as AD from './cozy-adler.js'; // Adler in Claude's ✦ line only, never in a chart (batch 16 item 2, canvas AdH3, AdM3)
41
41
  import * as RL from './ready-lib.js'; // the ready-made reports of every program, product and initiative (batch 17 item 1, PbA6, PbG4)
42
42
  import * as RI from './premium-report-intel.js'; // a report made from Intelligence (batch 15 item 4): the header icon, the ✦ proposals, the draft panel
43
+ import * as TRV from './trends-review.js'; // Delivery trends' words (batch 22 item 4): the month line, Up N vs last week, What moved it
43
44
  import * as OK from './okr-list.js'; // Claude runs the OKRs (batch 16 item 6, 6-B): the goal list, its drafts, the ✦ line, ⋯ › Metrics, the notify choice
44
45
  import * as IP2 from './ins-pane.js'; // Intelligence as the first panel (panels on Board and Intelligence, P-B): the narrow form, Moved by, the open row
45
46
  import * as GC from './goals-clear.js';
@@ -229,7 +230,7 @@ document.addEventListener('cz-viewer', (e) => {
229
230
  const d = e.detail || {}, id = d.open && /^goal:/.test(d.id || '') ? d.id.slice(5) : null;
230
231
  if ((new URLSearchParams(location.search).get('goal') || null) !== id) addr({ goal: id });
231
232
  });
232
- function setView(id) { dash = id; closeLib(); redraw(); noteOpen(); }
233
+ function setView(id) { dash = id; if (new URLSearchParams(location.search).has('view')) addr({ view: null }); closeLib(); redraw(); noteOpen(); }
233
234
  /* the view on screen, noted once a day per view (feedback batch 16 item 1; POST /api/page-opens, local only): it is what lets the ✦ strip say
234
235
  * "You open this every week" from a record, never from a guess. Portfolio is no one product's view, so it is not noted. */
235
236
  const NOTED = new Set();
@@ -978,7 +979,7 @@ const GRP_PILL = (L) => {
978
979
  function drawGoals() {
979
980
  const G = goalsShown(), T = $('#goalTbl');
980
981
  document.body.classList.toggle('ins-trv', dash === TRENDS);
981
- if (dash === TRENDS) { T.innerHTML = bmHtml(true); $('#goalCards').innerHTML = ''; return; }
982
+ if (dash === TRENDS) { T.innerHTML = bmHtml(true); T.hidden = false; $('#goalCards').innerHTML = ''; return; }
982
983
  const head = `<div class="ins-tr ins-th ${COLS}" role="row"><div role="columnheader">Key results <span>${G.length} · ${esc(per ? per.label : '')}</span></div><div role="columnheader">Now, of target <span class="ins-lg"><span><i class="ins-tdk"></i>today</span></span></div><div role="columnheader">So far</div><div role="columnheader">By its date</div><div role="columnheader" class="ins-mvh">Moved by <span class="ins-lg"><span><i class="ins-trk"><i class="k"></i></i>Skipped</span><span><i class="ins-trk"><i class="p m"></i></i>Milestone</span></span></div></div>`;
983
984
  const D = curDash();
984
985
  if (!M.goals.filter(isKr).length) {
@@ -1029,7 +1030,7 @@ $('#goalCards').addEventListener('click', (e) => { if (e.target.closest('a, .okr
1029
1030
  $('#goalTbl').addEventListener('click', (e) => {
1030
1031
  if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; clearFilter(); per = periods()[3]; redraw(); return; }
1031
1032
  if (e.target.closest('a')) return;
1032
- const tile = e.target.closest('[data-tile]'); if (tile) { if (tgOpen === tile.dataset.tile) closeTarget(true); else openTarget(tile.dataset.tile); return; }
1033
+ const tile = e.target.closest('[data-tile], [data-mt]'); if (tile) { if (tgOpen) closeTarget(); openTile(tile.dataset.tile || tile.dataset.mt); return; }
1033
1034
  if (e.target.closest('.okr-dr')) return; // a draft under a row has its own presses
1034
1035
  const bu = e.target.closest('[data-budget]'); if (bu) { openBudget(bu.dataset.budget); return; }
1035
1036
  const r = e.target.closest('[data-goal]'); if (r) pressGoal(r.dataset.goal);
@@ -1341,6 +1342,7 @@ $('#goalCards').addEventListener('click', (e) => { if (e.target.closest('a')) re
1341
1342
  * target's line under it. A press opens the target popover over the tiles. In the Delivery trends view the tiles stand three to a row. ─── */
1342
1343
  const TILES = [['blocked', 'Blocked tickets'], ['late', 'Late initiatives'], ['idle', 'Idle 30+ days'], ['scope', 'Scope added'], ['merges', 'Merged a week'], ['corrections', 'Corrections / 100 runs']];
1343
1344
  const TILE_DIR = { merges: 'at least' }; // more merges is better; every other measure is better lower
1345
+ const TILE_DEF = { late: 'Open initiatives the workflow engine reports as late today. Earlier weeks count the initiatives late today whose end date had already passed; the Board keeps no history of a status.', scope: 'Initiatives whose planned start falls in the week.' };
1344
1346
  const numsOf = (ser) => (ser || []).filter((v) => typeof v === 'number' && Number.isFinite(v));
1345
1347
  /** How a tile's target is read: its direction and its start (POST /api/insights-records/tile), whether the latest reading meets it, and the tile's
1346
1348
  * colour: amber only after the last two readings both miss it (IsTarget), or the one value when there is no series. */
@@ -1358,14 +1360,16 @@ function tileOf(key) {
1358
1360
  if (key === 'late' || key === 'scope') {
1359
1361
  const x = TR[key] || {};
1360
1362
  if (x.value == null) return { v: 'Not read', s: 'the initiatives are not read', abs: true, T: { line: '' } };
1361
- const tg = Number.isFinite(own) ? own : null;
1362
- t = { v: String(x.value), ser: x.ser || null, s: key === 'late' ? 'late today' : 'started this week', tg, base: key === 'late' && x.value > 0 };
1363
+ const tg = Number.isFinite(own) ? own : null, bw = BM && (BM.tiles || []).find((y) => y.wk);
1364
+ t = { v: String(x.value), ser: x.ser || null, s: key === 'late' ? 'late today' : 'started this week', note: key === 'late' ? 'late today' : 'started this week', tg, base: key === 'late' && x.value > 0,
1365
+ change: TRV.changeOf(x.ser, 0), wk: bw ? bw.wk : null, def: TILE_DEF[key] };
1363
1366
  } else {
1364
1367
  if (!BM) return { v: bmErr ? 'Not read' : 'Reading', s: '', abs: true, T: { line: '' } };
1365
1368
  const b = (BM.tiles || []).find((x) => x.key === key);
1366
1369
  if (!b) return { v: 'Not read', s: '', abs: true, T: { line: '' } };
1367
- if (b.absent) return { v: b.absent, s: '', abs: true, T: { line: '' } };
1368
- t = { v: b.value, ser: b.ser, s: b.targetTxt || '', tg: b.tg != null ? b.tg : null, base: !!b.look || b.kind === 'warn' || b.kind === 'bad' };
1370
+ if (b.absent) return { v: b.absent, s: '', abs: true, why: b.why || '', def: b.def, T: { line: '' } };
1371
+ t = { v: b.value, ser: b.ser, s: b.targetTxt || '', note: b.text || '', tg: b.tg != null ? b.tg : null, base: !!b.look || b.kind === 'warn' || b.kind === 'bad',
1372
+ change: b.change || null, wk: b.wk || null, nt: b.nt || null, def: b.def, dec: b.dec || 0 };
1369
1373
  }
1370
1374
  t.T = targetOf(key, t);
1371
1375
  t.warn = t.T.tg !== null ? t.T.miss2 : t.base;
@@ -1379,12 +1383,60 @@ function miniSpark(ser, W = 150, H = 18) {
1379
1383
  return `<svg class="ins-tsp" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="presentation"><polygon class="ar" points="${first[0]},${H} ${pts.join(' ')} ${last[0]},${H}"/><polyline class="ln" points="${pts.join(' ')}"/><circle class="dt" cx="${last[0]}" cy="${last[1]}" r="3.6"/></svg>`;
1380
1384
  }
1381
1385
  let tgOpen = null; // the tile whose target popover is open
1386
+ /** The six tiles with their words (label, value, change) as the trends view reads them. */
1387
+ const trendTiles = () => TILES.map(([k, l]) => Object.assign({ key: k, label: l }, tileOf(k)));
1388
+ const CHAT = 'M4 5h16v11H9l-5 4z';
1389
+ /** The ✦ month line (canvas MxA): the Board's measures in one sentence; the chat icon takes it to Strategist. Nothing read, no line. */
1390
+ function monthStrip() {
1391
+ const d = new Date((M.today || iso(today())) + 'T00:00:00Z'), open = BM && BM.counted ? BM.counted.open : 0;
1392
+ const line = TRV.monthLine({ month: MONTH[d.getUTCMonth()], tiles: trendTiles(), open });
1393
+ if (!line) return '';
1394
+ return `<div class="ins-strip ins-trstrip"><span class="sp" aria-hidden="true">${SV(I.spark)}</span><p class="t" id="trLine">${esc(line)}</p><a class="cz-ib sm" href="${esc(homeAsk('insights', 'Why? ' + line))}" aria-label="Discuss with Strategist" title="Discuss with Strategist">${SV(CHAT)}</a></div>`;
1395
+ }
1396
+ /** What moved it (MxA): only the tiles that moved since last week. Zero is silence. */
1397
+ function movedCard() {
1398
+ const R = TRV.movedRows(trendTiles());
1399
+ if (!R.length) return '';
1400
+ return `<section class="ins-mvd" aria-labelledby="hMvd"><h3 class="ins-h3" id="hMvd">What moved it</h3><div class="ins-mcard">${R.map((r) => `<button type="button" class="ins-mrow" data-mt="${esc(r.key)}"><span>${esc(r.label)}</span><span class="note">${esc(r.note)}</span><b>${esc(r.effect)}</b></button>`).join('')}</div></section>`;
1401
+ }
1402
+ /** Goals that moved (MxA): the key results and health budgets that are at risk, as the goal rows themselves (said once, not twice). */
1403
+ const goalHead = () => `<div class="ins-tr ins-th ${COLS}" role="row"><div role="columnheader">Goal</div><div role="columnheader">Now, of target</div><div role="columnheader">So far</div><div role="columnheader">By its date</div><div role="columnheader" class="ins-mvh">Moved by</div></div>`;
1404
+ /** A goal is at risk when its pace says so; one reading has no pace to judge, so it is not called at risk (honest state). */
1405
+ const riskTone = (g) => { const t = g.pace && g.pace.tone !== 'q' ? g.pace.tone : (g.readings || 0) > 1 ? g.tone : null; return t === 'late' || t === 'red' || t === 'risk'; };
1406
+ function movedGoals() {
1407
+ if (PF) return '';
1408
+ const G = listGoals().filter((g) => g.readings && riskTone(g)), B = (M.budgets || []).filter((b) => (b.reading && b.reading.over) || (b.burn && Number.isFinite(b.burn.weeksLeft) && b.burn.weeksLeft < 8));
1409
+ if (!G.length && !B.length) return ''; // zero is silence
1410
+ // wide: the goal rows themselves. Narrow (the phone, or the page beside the Viewer): one line each, its title and At risk (MxC)
1411
+ const cmp = G.map((g) => `<button type="button" class="ins-mrow" data-goal="${esc(g.id)}"><span>${esc(g.title)}</span><span class="cz-pill risk">At risk</span></button>`).concat(B.map((b) => `<button type="button" class="ins-mrow" data-budget="${esc(b.id)}"><span>${esc(b.title)}</span><span class="cz-pill risk">At risk</span></button>`)).join('');
1412
+ return `<section class="ins-mvd" aria-labelledby="hMvg"><h3 class="ins-h3" id="hMvg">Goals that moved</h3><div class="ins-tbl ins-mg-full" role="table" aria-label="Goals that moved">${goalHead()}${G.map(goalRow).join('')}${B.map(budgetRow).join('')}</div><div class="ins-mcard ins-mg-cmp">${cmp}</div></section>`;
1413
+ }
1382
1414
  function bmHtml(big) {
1383
1415
  if (!M.board || !M.board.ws) return big ? '<div class="ins-empty">Delivery trends are read from a board, and this workspace has none.</div>' : '';
1384
- const head = big ? '<div class="ins-trh" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="note">Last 8 weeks · from the Board and its initiatives · press a tile to set its target</span></div>'
1416
+ const head = big ? '<div class="ins-trh" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="note">Last 8 weeks · from the Board and its initiatives · press a tile for its weeks</span></div>'
1385
1417
  : '<div class="ins-grp" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="q">the Board shows today’s counts as chips · press a tile to set its target</span></div>';
1386
- return `<section class="ins-trends${big ? ' big' : ''}" id="cBm" aria-labelledby="hBm">${head}`
1387
- + `<div class="ins-tiles" id="bmBody">${TILES.map(([k, l]) => { const t = tileOf(k), on = tgOpen === k; return `<div class="ins-tile${t.warn ? ' warn' : ''}${t.abs ? ' abs' : ''}${on ? ' sel' : ''}" data-tile="${k}" role="button" tabindex="0" aria-expanded="${on}" aria-label="${esc(l + ', ' + t.v + (t.s ? ', ' + t.s : '') + (t.T.line ? ', ' + t.T.line : ''))}"${t.s ? ` title="${esc(t.s)}"` : ''}><span class="l">${esc(l)}</span><span class="v">${esc(t.v)}</span>${big ? miniSpark(t.ser, 300, 34) : miniSpark(t.ser)}<span class="tg">${on ? 'Setting target…' : esc(t.T.line)}</span></div>`; }).join('')}</div></section>`;
1418
+ const mv = (t) => (big && !t.abs && t.change && t.change.d !== 0 ? `<span class="mv">${esc(t.change.txt)}</span>` : '');
1419
+ return `<section class="ins-trends${big ? ' big' : ''}" id="cBm" aria-labelledby="hBm">${head}${big ? monthStrip() : ''}`
1420
+ + `<div class="ins-tiles" id="bmBody">${TILES.map(([k, l]) => { const t = tileOf(k), on = tgOpen === k; return `<div class="ins-tile${t.warn ? ' warn' : ''}${t.abs ? ' abs' : ''}${on ? ' sel' : ''}" data-tile="${k}" role="button" tabindex="0" aria-expanded="${on}" aria-label="${esc(l + ', ' + t.v + (t.s ? ', ' + t.s : '') + (t.change && t.change.d !== 0 ? ', ' + t.change.txt : '') + (t.T.line ? ', ' + t.T.line : ''))}"${t.s ? ` title="${esc(t.s)}"` : ''}><span class="l">${esc(l)}</span><span class="v">${esc(t.v)}</span>${big ? miniSpark(t.ser, 300, 34) : miniSpark(t.ser)}${mv(t)}<span class="tg">${on ? 'Setting target…' : esc(t.T.line)}</span></div>`; }).join('')}</div>`
1421
+ + (big ? movedCard() + movedGoals() : '') + '</section>';
1422
+ }
1423
+ /** A tile in the Viewer (MxB): its weeks as bars, a blank week dashed with its reason, the definition, where it is counted from, and the target. */
1424
+ function openTile(key) {
1425
+ const L = (TILES.find((x) => x[0] === key) || [])[1] || key;
1426
+ viewer({ kind: 'Intelligence · Delivery trends', title: L, icon: 'chart', id: 'trend:' + key, eye: 'Delivery trends', render: (el) => {
1427
+ const t = tileOf(key), ser = t.ser || [], N = ser.length, vs = numsOf(ser), mx = Math.max(0, ...vs) || 1, dec = t.dec || 0, wk = t.wk || [];
1428
+ const month = MONTH[new Date((M.today || iso(today())) + 'T00:00:00Z').getUTCMonth()];
1429
+ const say = t.abs ? (key === 'corrections' && t.why ? month + ': ' + t.why : (t.why || 'It is not read, so it has no weeks to show.'))
1430
+ : t.v + (t.note ? ' · ' + t.note : '') + (t.change && t.change.d !== 0 ? ' · ' + t.change.txt : '');
1431
+ const bars = N ? `<div class="ins-bars" role="img" aria-label="${esc(L + ' by week: ' + ser.map((v, i) => (wk[i] || 'W' + (i + 1)) + ' ' + (v == null ? 'blank' : v)).join(', '))}">${ser.map((v, i) => `<div><span>${v == null ? '' : esc(String(dec ? Number(v).toFixed(dec) : v))}</span><i class="${v == null ? 'blank' : ''}${i === N - 1 ? ' now' : ''}"${v == null ? '' : ` style="height:${Math.max(4, Math.round(v / mx * 100))}px"`}></i>${esc(wk[i] || 'W' + (i + 1))}</div>`).join('')}</div>` : '';
1432
+ const lowB = TRV.LOW_BETTER[key];
1433
+ el.innerHTML = `<div class="ins-gd"><div class="ins-sayc"><p class="ins-sayv">${esc(say)}</p></div>`
1434
+ + (bars ? `<h3 class="ins-h3">By week${lowB ? ', lower is better' : ', higher is better'}</h3>${bars}<p class="note">${key === 'corrections' ? 'A week with fewer than 10 runs stays blank. ' : ''}The bars fill in as weeks qualify; this week is blue.</p>` : '')
1435
+ + (t.def ? `<p class="note">${esc(t.def)}</p>` : '') + (BM && BM.note ? `<p class="note ins-from">${esc(BM.note)}</p>` : '')
1436
+ + `<div class="ins-acts"><button type="button" class="cz-ib sm" data-tgset aria-label="Set a target" title="Set a target">${SV('M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0-18 0M12 12m-4 0a4 4 0 1 0 8 0a4 4 0 1 0-8 0')}</button>`
1437
+ + `<a class="cz-ib sm" href="${esc(homeAsk('insights', 'About ' + L + ': ' + say))}" aria-label="Discuss with Strategist" title="Discuss with Strategist">${SV(CHAT)}</a></div></div>`;
1438
+ el.addEventListener('click', (e) => { if (e.target.closest('[data-tgset]')) { e.stopPropagation(); closeViewer(); setTimeout(() => openTarget(key), 0); } }); // not in this press: the page's outside-press closes a popover opened by it
1439
+ } });
1388
1440
  }
1389
1441
  async function bmLoad() {
1390
1442
  if (!M || !M.board || !M.board.ws) return;
@@ -2045,7 +2097,8 @@ async function load() {
2045
2097
  setTimeout(load, 15000);
2046
2098
  return;
2047
2099
  }
2048
- const first = !M; M = r.model; loadedAt = Date.now(); draw(); if (first || !BM) bmLoad();
2100
+ const first = !M; M = r.model; loadedAt = Date.now(); if (first && !PF && new URLSearchParams(location.search).get('view') === 'trends') dash = TRENDS; // an old Metrics link, the monthly routine and the product page's chart icon land here
2101
+ draw(); if (first || !BM) bmLoad();
2049
2102
  if (on.length > 1 && first) await openPortfolio(on, true);
2050
2103
  // A shared goal link (?goal=<id>, from "Copy link" in the goal's ⋯) opens that goal once, after the first read.
2051
2104
  if (first) { const gid = new URLSearchParams(location.search).get('goal'); if (gid && allGoals().some((g) => g.id === gid)) openGoalDetail(gid); }
@@ -53,7 +53,7 @@ import { open as vOpen, current as vCur, czSections } from './cozy-viewer.js';
53
53
  import * as MP from './premium-mtg-present.js'; // the one presenter window for every kind (canvas note xvPresent)
54
54
  import { presentInRecording } from './cozy-rec-bridge.js'; // while a meeting records, the recording tab presents it (rule 10)
55
55
  import { placeholderHtml } from './cozy-placeholder.js';
56
- import './premium-vw-open.js'; // registers window.czViews
56
+ import { vzStyle } from './premium-vw-open.js'; // registers window.czViews; vzStyle adds the Viewer's sheet (cozy-vw.css)
57
57
  import { cycleGroups, cycleName, briefModel, briefGlanceHtml, briefConfirmHtml, briefWhyHtml, briefLooksHtml, paperModel, paperHtml, liveModel, liveHtml, presentHtml, dayMon, reportSummary,
58
58
  rpSumHtml, rpBarHtml, cadenceWords, goesOutWords, FORMATS } from './rp-parts.js';
59
59
 
@@ -176,11 +176,18 @@ function slides() {
176
176
  export const longSlot = (s) => { const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(s || '')); return m ? +m[3] + ' ' + MONS[+m[2] - 1] + ' ' + m[1] : String(s || ''); };
177
177
  /** The title slide (ReportPanel.dc.html): the audience tag, the title with the audience as its accent line, a subtitle (the file's
178
178
  * subtitle or description, else its first sections) and the as-of line. Nothing is made up: a part with no source is left out. */
179
+ const AUD_MAX = 40;
180
+ /** The note older drafts carried in their description: how the file is made, for PMOS, never a subtitle. */
181
+ const INTERNAL_RE = /pmos report draft writes every number|between the note markers/i;
179
182
  function titleSlide(w) {
180
183
  const heads = (w.sections || []).map((x) => x.h).filter((h) => !/^summary$/i.test(h)).slice(0, 3);
181
184
  const list = heads.length > 1 ? heads.slice(0, -1).join(', ') + ' and ' + heads[heads.length - 1].toLowerCase() : heads.join('');
182
185
  const f = headFigure(w), t = [R.row.slot ? 'As of ' + longSlot(R.row.slot) : '', f && f.data ? 'Data: ' + f.data : ''].filter(Boolean).join(' · ');
183
- return { k: 'title', h: 'Title', title: w.title, eye: R.audience || 'Report', acc: R.audience ? R.audience.toLowerCase() : '', sub: w.sub || list, t,
186
+ // A long audience (a list of people) stays in At a glance: on the slide it would fill the eyebrow and repeat as the accent line (Wawan, 2026-11-01).
187
+ const aud = R.audience && R.audience.length <= AUD_MAX ? R.audience : '';
188
+ // an older draft is titled from the report's id ("Scarlet-assessment-report report 2026-11-02"): show the report's name instead
189
+ const idTitle = R.name && /^[A-Za-z][a-z0-9]*(?:-[a-z0-9]+)+ report \d{4}-\d{2}-\d{2}$/.test(w.title || '');
190
+ return { k: 'title', h: 'Title', title: idTitle ? R.name : w.title, eye: aud || 'Report', acc: aud ? aud.toLowerCase() : '', sub: (!INTERNAL_RE.test(w.sub || '') && w.sub) || list, t,
184
191
  fig: f ? { v: f.v, cap: f.cap } : null };
185
192
  }
186
193
  /** The title slide's headline figure (ReportPanel.dc.html: "81%" over "597 of 733 web logins"): the first bold number of the first
@@ -427,7 +434,35 @@ function bodyHtml() {
427
434
  }
428
435
  const view = R.err ? `<p class="vz-msg" data-tone="bad" role="alert">The document could not be read: ${esc(R.err)}</p>` : !R.W ? '<p class="vz-empty" role="status">Reading the report.</p>'
429
436
  : R.view === 'deck' ? deckHtml() : R.view === 'live' ? liveView() : pageHtml();
430
- return `<div class="vz-rpb">${R.conf ? confHtml() : R.W ? sumHtml() : ''}${R.W && !R.err ? cutsHtml() : ''}${R.msg ? `<p class="vz-msg" role="status" data-tone="${R.msg.tone || ''}">${esc(R.msg.text)}</p>` : ''}${R.W && !R.err ? barHtml() : ''}${view}${R.W && !R.err ? foldsHtml() : ''}${askHtml()}</div>`;
437
+ return `<div class="vz-rpb">${R.conf ? confHtml() : R.W ? sumHtml() : ''}${R.W && !R.err ? cutsHtml() : ''}${R.msg ? `<p class="vz-msg" role="status" data-tone="${R.msg.tone || ''}">${esc(R.msg.text)}</p>` : ''}${R.edit ? '' : waitHtml()}${R.W && !R.err ? barHtml() : ''}${view}${R.W && !R.err ? foldsHtml() : ''}${askHtml()}</div>`;
438
+ }
439
+ /** What Claude is still doing on this report, said where the PM reads it (Wawan, 2026-11-01, batch 22 item 13: "I have to wait, but there's
440
+ * no indication of me having to wait"). Nothing running → ''. */
441
+ export function waitWords(x, draft) {
442
+ const st = x && x.structure, de = x && x.design, out = [];
443
+ if (draft && draft.state === 'drafting') out.push('Claude is writing this report again with your sections. It takes a few minutes; the new draft opens here when it lands.');
444
+ else if (draft && draft.state === 'held') out.push('The new draft waits for a check of ' + (draft.sources || []).join(', ') + '.');
445
+ if (st && st.running) out.push('Claude is reshaping the sections to your change. It takes a minute or two. Until you keep it, this draft has the standard sections.');
446
+ else if (st && st.current != null && st.current !== st.saved) out.push('New sections are ready. Open the report from your chat and press Use this; Claude then writes the draft again with them.');
447
+ if (de && de.running) out.push('Claude is making the look' + ((de.samples || []).length ? ' from ' + de.samples.map((y) => y.name).join(', ') : '') + '. It takes a minute or two. Until then, the slides use the standard PMOS look.');
448
+ return out;
449
+ }
450
+ function waitHtml() {
451
+ const L = waitWords(R.bfRaw, R.setup && R.setup.draft);
452
+ return L.length ? `<p class="vz-msg rp-wait" role="status">${L.map(esc).join(' ')}</p>` : '';
453
+ }
454
+ /** While Claude works on the report, read its state again every few seconds, so the line above clears and the new draft shows. */
455
+ let waitT = null;
456
+ function waitPoll() {
457
+ clearTimeout(waitT);
458
+ if (!R || !waitWords(R.bfRaw, R.setup && R.setup.draft).length) return;
459
+ const me = R, wasDrafting = !!(R.setup && R.setup.draft);
460
+ waitT = setTimeout(async () => {
461
+ if (R !== me) return;
462
+ await readSetup(); if (R !== me) return;
463
+ if (wasDrafting && !(R.setup && R.setup.draft)) await reread();
464
+ await readBrief(); if (R === me) waitPoll();
465
+ }, 4000);
431
466
  }
432
467
  const tipText = (i, n) => `Slide ${i + 1} of ${n}. Click an item to change it; double-click text to type.`;
433
468
  /** The editor's slide and its undo history changed: the tip and the dimmed Undo and Redo follow it. */
@@ -645,7 +680,7 @@ async function readBrief() {
645
680
  ].map((x) => Promise.resolve(x).catch(() => null)));
646
681
  if (R !== me) return;
647
682
  R.bfRaw = { structure: st && st.ok ? st.structure : null, design: de && de.ok ? de.design : null, checks: ch, confirms: cf && cf.ok ? cf.keys : [] };
648
- buildBrief(); draw();
683
+ buildBrief(); draw(); waitPoll();
649
684
  }
650
685
  function buildBrief() {
651
686
  const x = R.bfRaw; if (!x) return;
@@ -886,7 +921,9 @@ export async function openReport(row, hand = {}) {
886
921
  if (!row || !row.path) return null;
887
922
  const c = cycleOf(row);
888
923
  row = { ...row, cadence: c.cadence, slot: c.slot };
889
- rpStyle();
924
+ // the slides, the title card and the thumbnails are drawn by cozy-vw.css: a report opened from Home had no sheet, so its slides showed as
925
+ // plain text (Wawan, 2026-11-01, batch 22 item 13)
926
+ vzStyle(); rpStyle();
890
927
  if (R) present(false);
891
928
  const me = R = { row, ws: hand.ws || '', id: c.cadence, name: hand.name || row.name || c.cadence || 'Report', audience: hand.audience || '', issued: row.state === 'issued', archived: !!row.archived,
892
929
  text: '', err: '', W: null, view: 'deck', BF: null, bfRaw: null, bfMsg: '', LV: null, blank: false, i: 0, cyc: null, setup: undefined, pop: null, conf: false, checks: null, issueErr: '', busy: false, ask: '', askErr: '', edit: false, msg: null,