create-pmos 0.396.0 → 0.398.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 (177) hide show
  1. package/package.json +25 -25
  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/scripts/nine-stages.js +49 -20
  6. package/payload/state/discoveries.md +1 -1
  7. package/payload/state/log.md +1 -1
  8. package/workspace/briefing-premium-adddoc-test.js +103 -74
  9. package/workspace/briefing-premium-board-test.js +316 -154
  10. package/workspace/briefing-premium-calendar-2-test.js +135 -195
  11. package/workspace/briefing-premium-calendar-3-test.js +143 -413
  12. package/workspace/briefing-premium-calendar-test.js +86 -185
  13. package/workspace/briefing-premium-doc-edit-test.js +95 -83
  14. package/workspace/briefing-premium-initiative-test.js +166 -294
  15. package/workspace/briefing-premium-insights-test.js +351 -214
  16. package/workspace/briefing-premium-metrics-test.js +53 -118
  17. package/workspace/briefing-premium-products-test.js +40 -27
  18. package/workspace/briefing-premium-sources-test.js +91 -52
  19. package/workspace/briefing-premium-test.js +150 -633
  20. package/workspace/briefing-premium-work-test.js +88 -269
  21. package/workspace/changelog.json +24 -0
  22. package/workspace/fixtures/board-premium-facts.js +2 -1
  23. package/workspace/fixtures/board-premium-jira.js +28 -0
  24. package/workspace/fixtures/board-premium-trail.js +32 -0
  25. package/workspace/fixtures/initiative-premium-facts.js +2 -1
  26. package/workspace/fixtures/initiatives-api/list.json +30 -42
  27. package/workspace/fixtures/initiatives-api/roadmap.json +40 -56
  28. package/workspace/fixtures/initiatives-api/sheet.json +10 -14
  29. package/workspace/fixtures/insights-premium-facts.js +11 -2
  30. package/workspace/fixtures/premium-viewer-fixtures.js +182 -0
  31. package/workspace/guide/briefing-premium.md +3 -1
  32. package/workspace/guide/home.md +47 -0
  33. package/workspace/guide/index.md +2 -0
  34. package/workspace/guide/lifecycle.md +51 -0
  35. package/workspace/home-shot.js +38 -0
  36. package/workspace/lib/agent-roles.js +71 -0
  37. package/workspace/lib/board-premium.js +160 -3
  38. package/workspace/lib/board-trail.js +223 -0
  39. package/workspace/lib/engine/boards.js +15 -14
  40. package/workspace/lib/engine/nine-stages.js +49 -20
  41. package/workspace/lib/engine/signals/detectors.js +13 -11
  42. package/workspace/lib/home-work-item.js +58 -0
  43. package/workspace/lib/insights-goals.js +196 -0
  44. package/workspace/lib/insights-premium.js +126 -1
  45. package/workspace/lib/insights-records.js +101 -0
  46. package/workspace/lib/jira-tickets.js +1 -1
  47. package/workspace/lib/route-modules.js +4 -0
  48. package/workspace/lib/routes-board-premium.js +3 -2
  49. package/workspace/lib/routes-board-trail.js +33 -0
  50. package/workspace/lib/routes-home-desk.js +176 -0
  51. package/workspace/lib/routes-initiatives.js +1 -1
  52. package/workspace/lib/routes-insights-premium.js +19 -3
  53. package/workspace/lib/routes-insights-records.js +129 -0
  54. package/workspace/lib/routes-notes.js +1 -0
  55. package/workspace/lib/routes-viewer.js +108 -0
  56. package/workspace/lib/transcript-steps.js +123 -0
  57. package/workspace/lib/vendor/scripts/nine-stages.js +49 -20
  58. package/workspace/lib/viewer-meeting.js +205 -0
  59. package/workspace/lib/viewer-report.js +89 -0
  60. package/workspace/package-lock.json +2 -2
  61. package/workspace/package.json +1 -1
  62. package/workspace/premium-agreed-viewer-shots.js +76 -0
  63. package/workspace/premium-board-actions-test.js +85 -73
  64. package/workspace/premium-briefing-depth-test.js +66 -53
  65. package/workspace/premium-chat-attach-test.js +54 -63
  66. package/workspace/premium-chat-chart-tab-test.js +35 -36
  67. package/workspace/premium-chat-context-test.js +22 -19
  68. package/workspace/premium-chat-goal-view-test.js +28 -26
  69. package/workspace/premium-chat-notes-test.js +29 -33
  70. package/workspace/premium-chat-report-tab-test.js +35 -25
  71. package/workspace/premium-chat-term-test.js +16 -14
  72. package/workspace/premium-chat-viewer-test.js +60 -53
  73. package/workspace/premium-core-doc-issue-test.js +50 -41
  74. package/workspace/premium-html-viewer-test.js +17 -18
  75. package/workspace/premium-phone-card-test.js +8 -2
  76. package/workspace/premium-phone-room-test.js +42 -31
  77. package/workspace/premium-report-read-test.js +115 -197
  78. package/workspace/premium-viewer-download-test.js +19 -22
  79. package/workspace/premium-viewer-flicker-test.js +11 -16
  80. package/workspace/premium-viewer-share-test.js +6 -9
  81. package/workspace/premium-viewer-test.js +41 -60
  82. package/workspace/premium-vw-backlog-test.js +53 -31
  83. package/workspace/premium-vw-cal-test.js +82 -123
  84. package/workspace/premium-vw-copy-test.js +17 -33
  85. package/workspace/premium-vw-doc-test.js +12 -11
  86. package/workspace/premium-vw-item-test.js +50 -48
  87. package/workspace/premium-vw-jira-test.js +55 -26
  88. package/workspace/premium-vw-meet-test.js +118 -187
  89. package/workspace/premium-vw-notes-test.js +85 -107
  90. package/workspace/premium-vw-rec-test.js +72 -193
  91. package/workspace/premium-vw-slides-test.js +46 -50
  92. package/workspace/premium-welcome-test.js +3 -2
  93. package/workspace/premium-work-depth-test.js +63 -51
  94. package/workspace/public/pm/bd-acts.js +305 -0
  95. package/workspace/public/pm/bd-span.js +224 -0
  96. package/workspace/public/pm/bd-stages.js +47 -0
  97. package/workspace/public/pm/c3-doc-sheet.js +1 -1
  98. package/workspace/public/pm/c3-md.js +3 -395
  99. package/workspace/public/pm/c3-phone-detail.js +1 -1
  100. package/workspace/public/pm/c3-phone-model.js +3 -68
  101. package/workspace/public/pm/chat-term.js +3 -3
  102. package/workspace/public/pm/cozy-board.css +640 -0
  103. package/workspace/public/pm/cozy-home.css +580 -0
  104. package/workspace/public/pm/cozy-home.js +172 -0
  105. package/workspace/public/pm/cozy-initiative.css +138 -0
  106. package/workspace/public/pm/cozy-insights.css +421 -0
  107. package/workspace/public/pm/cozy-md.js +396 -0
  108. package/workspace/public/pm/cozy-nav.js +65 -0
  109. package/workspace/public/pm/cozy-placeholder.js +26 -0
  110. package/workspace/public/pm/cozy-viewer.css +143 -0
  111. package/workspace/public/pm/cozy-viewer.js +144 -0
  112. package/workspace/public/pm/cozy-vw.css +485 -0
  113. package/workspace/public/pm/cozy.css +254 -0
  114. package/workspace/public/pm/home-adddoc.js +48 -0
  115. package/workspace/public/pm/home-app.js +905 -0
  116. package/workspace/public/pm/home-around.js +515 -0
  117. package/workspace/public/pm/home-chat.js +459 -0
  118. package/workspace/public/pm/home-data.js +312 -0
  119. package/workspace/public/pm/home-draft.js +68 -0
  120. package/workspace/public/pm/home-more.js +249 -0
  121. package/workspace/public/pm/home-phone-card.js +109 -0
  122. package/workspace/public/pm/home-work.js +519 -0
  123. package/workspace/public/pm/lifecycle-lens-model.js +45 -27
  124. package/workspace/public/pm/lifecycle-lens.js +22 -11
  125. package/workspace/public/pm/phone-moment.js +69 -0
  126. package/workspace/public/pm/pm-work-view.js +1 -1
  127. package/workspace/public/pm/premium-attach.js +4 -0
  128. package/workspace/public/pm/premium-board.js +544 -253
  129. package/workspace/public/pm/premium-brief.js +1 -1
  130. package/workspace/public/pm/premium-chart-tab.js +110 -62
  131. package/workspace/public/pm/premium-chat.js +17 -10
  132. package/workspace/public/pm/premium-deck.js +3 -3
  133. package/workspace/public/pm/premium-first.js +25 -21
  134. package/workspace/public/pm/premium-initiative-head.js +138 -0
  135. package/workspace/public/pm/premium-initiative.js +28 -4
  136. package/workspace/public/pm/premium-insights.js +950 -440
  137. package/workspace/public/pm/premium-meeting.js +61 -549
  138. package/workspace/public/pm/premium-notes.js +1 -1
  139. package/workspace/public/pm/premium-report-frame.css +20 -0
  140. package/workspace/public/pm/premium-report-read.js +509 -480
  141. package/workspace/public/pm/premium-report-tab.js +87 -63
  142. package/workspace/public/pm/premium-shell.js +107 -124
  143. package/workspace/public/pm/premium-viewer.js +27 -1
  144. package/workspace/public/pm/premium-vw-cal.js +187 -48
  145. package/workspace/public/pm/premium-vw-doc.css +6 -0
  146. package/workspace/public/pm/premium-vw-doc.js +40 -2
  147. package/workspace/public/pm/premium-vw-file.js +2 -2
  148. package/workspace/public/pm/premium-vw-jira-model.js +22 -5
  149. package/workspace/public/pm/premium-vw-jira.css +11 -0
  150. package/workspace/public/pm/premium-vw-jira.js +11 -4
  151. package/workspace/public/pm/premium-vw-meet.js +6 -83
  152. package/workspace/public/pm/premium-vw-mtg.js +731 -0
  153. package/workspace/public/pm/premium-vw-notes.js +56 -69
  154. package/workspace/public/pm/premium-vw-open.js +35 -0
  155. package/workspace/public/pm/premium-vw-page.js +16 -0
  156. package/workspace/public/pm/premium-vw-rec.js +11 -215
  157. package/workspace/public/pm/premium-vw-slides.css +5 -0
  158. package/workspace/public/pm/premium-vw-slides.js +44 -8
  159. package/workspace/public/pm/term-view.js +22 -0
  160. package/workspace/public/premium-board.html +57 -64
  161. package/workspace/public/premium-chat.html +7 -33
  162. package/workspace/public/premium-initiative.html +8 -41
  163. package/workspace/public/premium-insights.html +63 -62
  164. package/workspace/public/premium-viewer.html +20 -0
  165. package/workspace/public/premium-work.html +6 -72
  166. package/workspace/public/premium.html +21 -66
  167. package/workspace/public/vendor/nunito-var.woff2 +0 -0
  168. package/workspace/server.js +25 -3
  169. package/workspace/test-files.json +1 -0
  170. package/workspace/test-lists/home-libs.json +9 -0
  171. package/workspace/test-lists/premium-agreed-viewer.json +9 -0
  172. package/workspace/test-lists/premium-report-read.json +1 -1
  173. package/workspace/test-lists/premium-vw-agreed.json +9 -0
  174. package/workspace/test-lists/premium-vw-notes.json +1 -1
  175. package/workspace/third-party/README.md +1 -0
  176. package/workspace/public/pm/premium-work.js +0 -719
  177. package/workspace/public/pm/premium.js +0 -1133
@@ -1,491 +1,1001 @@
1
- /* pm/premium-insights.js — the premium Insights page (initiative briefing-premium-insights, slice 9). Reads GET /api/insights-premium and draws the model
2
- * lib/insights-premium.js builds from the KR metric records and the report files the console's Reports tab reads: the Dashboards card (charts with a target
3
- * line, what stands out), the Reports card, the dock and the standard dialog.
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
- * 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'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
8
- * (PRD L1 to L6); its one new press is Pin, POST /api/premium-dashboards/pin. Nothing else posts, and nothing is sent outward. */
9
- import { $, $$, esc, openDlg, popKey, closeDlg, toast, loadThread, onScroll, wireRail, logHtml, turnA, ptx, pillOf, crumbHtml, wireCrumb, kv, setPageGaps, infoBtn, growAsk } from './premium-shell.js';
1
+ /* pm/premium-insights.js — the premium Insights page, drawn to the Agreed design's frames (initiative premium-agreed-design): AgInsGoals, AgInsPeriod,
2
+ * AgInsNewGoal, AgInsNewDash, AgInsChart, AgInsOutcomes, AgInsVerdict, AgInsLibrary and AgInsPhone.
3
+ *
4
+ * READS: GET /api/insights-premium (lib/insights-premium.js: the KR metric records as goals, the board's initiatives that move them, the health budgets
5
+ * they anchor to, the dashboards, the report files and setups) and GET /api/board-metrics-premium (the Delivery trends tiles).
6
+ * WRITES, each a press on the page: New goal adds a KR metric record (POST /api/records/kr-metrics/add: metric, baseline, target, by, unit, pillar);
7
+ * New dashboard and Edit chart save a dashboard (POST /api/premium-dashboards/save: name, purpose and its goals in order); Pin (POST
8
+ * /api/premium-dashboards/pin). A field the design shows and no route accepts is drawn and marked "Not saved yet". Record verdict has no route, so it
9
+ * is not available yet. Nothing is sent outward.
10
+ * A part of the page the design does not draw (the goal detail, a Delivery trends target, a report setup, request or finding) opens the "Waiting for
11
+ * design" card (window.czPlaceholder) in the Viewer card (window.czViewer); both are feature-detected, with this page's side panel as the fallback.
12
+ * A report file opens in the report reader (pm/premium-report-read.js), the report panel in the Viewer card. The page has no #dlg. */
13
+ import { $, $$, esc, toast, wireRail, setPageGaps } from './premium-shell.js';
10
14
  import { pmPost } from './http.js';
11
15
  import { openReport } from './premium-report-read.js';
12
- import * as MT from './premium-metric-tiles.js';
13
- import { W, P, X, Y, tileHtml } from './premium-chart-draw.js';
16
+ import { mountNav } from './cozy-nav.js';
14
17
 
15
18
  let M = null; // the model
16
- let dash = null; // the dashboard in the top card: the pinned one until a list row opens another
17
- let listF = 'all', listP = 1; // the list's filter and page
18
- const PER = 6; // rows to a page (insights-one-list L5)
19
+ let BM = null, bmErr = ''; // the Board measures (Delivery trends)
20
+ let dash = null; // the view: a dashboard id; 'all' is every goal
21
+ let tab = 'goals';
22
+ let listF = 'all'; // the Library filter
23
+ let per = null; // the period { key, label, name, from, to }
24
+ let find = '';
25
+ let filt = { obj: null, owner: null, type: null, lane: null };
26
+ let selecting = false; let picked = []; // New dashboard: the goals picked in the table, in order
19
27
  wireRail('rep');
20
- const ICO = (p) => `<svg class="i" viewBox="0 0 24 24">${p}</svg>`;
21
- const DOCI = '<path d="M6 3h9l4 4v14H6z"/><path d="M14 3v5h5M9 13h6M9 17h4"/>';
22
- const CHV2 = '<svg class="i" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6"/></svg>';
23
- const PINI = '<path d="M9 3h6l-1 6 4 3v2H6v-2l4-3z"/><path d="M12 14v7"/>';
24
- const DASHI = '<path d="M4 20V10M10 20V4M16 20v-8M22 20H2"/>';
25
- const AIC = '<path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/>';
26
- const byKey = (k) => (M && (M.charts || []).concat(M.mine || []) || []).find((c) => c.key === k) || null;
28
+ mountNav('insights');
29
+
30
+ const SV = (d, sw) => `<svg viewBox="0 0 24 24" aria-hidden="true"${sw ? ` stroke-width="${sw}"` : ''}><path d="${d}"/></svg>`;
31
+ const I = {
32
+ doc: 'M6 3h9l4 4v14H6zM14 3v5h5M9 13h6M9 17h4', pin: 'M9 3h6l-1 6 4 3v2H6v-2l4-3zM12 14v7', chk: 'M5 12l5 5 9-10', x: 'M6 6l12 12M18 6L6 18',
33
+ more: 'M5 12h.01M12 12h.01M19 12h.01', home: 'M3 11l9-7 9 7v9a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z', next: 'M9 6l6 6-6 6', plus: 'M12 5v14M5 12h14',
34
+ spark: 'M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z', up: 'M12 19V5M6 11l6-6 6 6', grip: 'M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01',
35
+ chart: 'M4 20V10M10 20V4M16 20v-8M22 20H2', ext: 'M14 4h6v6M20 4l-9 9M18 14v5H5V6h5', down: 'M7 10l5 5 5-5',
36
+ };
37
+ const byKey = (k) => (M && (M.charts || []).find((c) => c.key === k)) || null;
27
38
  const savedDash = () => (M.dashboards || []).filter((d) => d.saved);
39
+ const wsQ = () => (M && M.board.ws ? 'ws=' + encodeURIComponent(M.board.ws) + '&' : '');
40
+ const homeAsk = (kind, q) => '/premium.html?' + wsQ() + 'ask=' + encodeURIComponent(kind) + '&q=' + encodeURIComponent(q);
41
+ const iniHref = (id) => '/premium-initiative.html?' + wsQ() + 'id=' + encodeURIComponent(id);
42
+ const SRC_NAME = { analytics: 'Product analytics', jira: 'Jira query', file: 'A file or export', typed: 'You type it in' };
43
+ /** A goal's KR id as the design says it: "KR <objective>.<its place in the objective>", in the order of the records; '' with no objective. */
44
+ const krId = (g) => { if (!g || !g.pillar) return ''; const objs = [...new Set(M.goals.map((x) => x.pillar).filter(Boolean))], same = M.goals.filter((x) => x.pillar === g.pillar); return 'KR ' + (objs.indexOf(g.pillar) + 1) + '.' + (same.indexOf(g) + 1); };
45
+ /** The cozy select: a native select drawn as the design's field, with a quiet chevron instead of the system arrow. */
46
+ const csel = (inner, cls = '') => `<span class="ins-sel${cls}">${inner}<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 10l5 5 5-5"/></svg></span>`;
28
47
 
29
- /* ── header ───────────────────────────────────────────────────────────────────────────────────────────────────── */
30
- let crumbed = false;
31
- function drawHead() {
32
- if (!crumbed) {
33
- crumbed = true;
34
- const boards = M.board.switcher || [];
35
- $('#crumbHost').innerHTML = crumbHtml({ page: 'Insights', board: M.board.name || 'Insights', boards });
36
- wireCrumb({ boards, board: M.board.id, goBoard: (ws, id) => location.assign('/premium-insights.html?ws=' + encodeURIComponent(ws) + '&board=' + encodeURIComponent(id)) });
37
- }
38
- $('#snap').textContent = M.header.text;
39
- setPageGaps(((M.header && M.header.missing) || []).length);
40
- $('#snap').title = 'Every figure on this page comes from a KR metric record. A measure with fewer than two readings is listed, not drawn.';
41
- drawHero();
48
+ /* ── the Viewer card and the "Waiting for design" card (another module adds them; this page feature-detects both) ─────────────────── */
49
+ function waitHtml(feature) {
50
+ return `<div class="ins-wait"><b>Waiting for design</b><p>${esc(feature)} has no agreed design yet, so this page does not draw it. Nothing here changes a record.</p></div>`;
51
+ }
52
+ function viewer(o) {
53
+ const V = window.czViewer;
54
+ if (V && typeof V.open === 'function') { V.open({ kind: o.kind, title: o.title, icon: o.icon, render: (el) => { const w = document.createElement('div'); w.className = 'ins-vbody'; el.appendChild(w); o.render(w); } }); return; }
55
+ openSide({ kind: 'view', eye: o.eye || '', title: o.title, body: '', note: '', go: null });
56
+ o.render($('#sideBody'));
57
+ }
58
+ function placeholder(feature) {
59
+ const V = window.czViewer;
60
+ if (V && typeof V.placeholder === 'function') { V.placeholder(feature, { kind: 'Insights' }); return; }
61
+ viewer({ kind: 'placeholder', title: feature, icon: 'wait', eye: 'Waiting for design', render: (el) => {
62
+ if (typeof window.czPlaceholder === 'function') window.czPlaceholder(el, feature); else el.innerHTML = waitHtml(feature);
63
+ } });
42
64
  }
43
65
 
44
- /* ── the insight (insights-one-list L1, L2): the strongest finding across the board's measures, its reason, two more, and a press to the measure ── */
45
- function drawHero() {
46
- const I = M.insight;
47
- $('#insEye').innerHTML = ICO(AIC) + esc(I.none ? 'Insight' : 'Insight · ' + I.off + ' of ' + I.total + ' behind their line · readings to ' + I.asOf) + (I.none && I.why ? ' ' + infoBtn('insWhy', 'How an insight is drawn') : '');
48
- $('#brief').textContent = I.text;
49
- $('#insWhy').textContent = I.why || '';
50
- $('#insWhy').hidden = !!I.none; // with no insight, the explanation waits behind an ⓘ (premium-calmer-first-screen)
51
- $('#insMore').innerHTML = (I.more || []).map((x) => `<li><button class="imr" data-open="${esc(x.chart)}" aria-haspopup="dialog">${esc(x.text)}${CHV2}</button></li>`).join('');
52
- $('#insAct').innerHTML = I.chart ? `<button class="dmcta" data-askwhy="${esc(I.chart)}" aria-haspopup="dialog">Ask PMOS why</button><button class="dmcta alt" data-open="${esc(I.chart)}" aria-haspopup="dialog">See the chart</button>` : '';
53
- $('#insNote').textContent = I.proj || (I.more || []).length ? 'A sentence that says where a measure lands by its target date is a straight line through its last four readings, carried to that date. It is not drawn on a chart.' : '';
54
- $('#insHero').classList.toggle('calm', !!(I.none || I.calm));
55
- }
56
- $('#insHero').addEventListener('click', (e) => {
57
- const o = e.target.closest('[data-open]'); if (o) { openChart(byKey(o.dataset.open)); return; }
58
- const a = e.target.closest('[data-askwhy]'); if (!a) return;
59
- openChart(byKey(a.dataset.askwhy));
60
- const t = $('#dTabs [data-t="chat"]'); if (t) t.click();
61
- const inp = $('#askIn'); if (inp) { inp.value = 'Why is this happening, and what would change it?'; growAsk(); inp.focus(); }
66
+ /* ── small menus: one open at a time, Escape and an outside press close it ─────────────────────────────────────────────────────── */
67
+ const MENUS = [['#prodPick', '#prodMenu'], ['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#newB', '#newMenu'], ['#moreB', '#moreMenu']];
68
+ function menu(btn, box, open) { $(box).hidden = !open; $(btn).setAttribute('aria-expanded', String(open)); }
69
+ function closeMenus(except) { for (const [b, m] of MENUS) if (m !== except && !$(m).hidden) menu(b, m, false); const cm = $('#chMenu'); if (cm) cm.hidden = true; }
70
+ for (const [b, m] of MENUS) {
71
+ $(b).addEventListener('click', (e) => {
72
+ e.stopPropagation(); const open = $(m).hidden; closeMenus(m); menu(b, m, open);
73
+ if (open) { const f = $(m).querySelector('button:not([disabled]), input, a'); if (f) f.focus(); }
74
+ });
75
+ }
76
+ document.addEventListener('click', (e) => {
77
+ for (const [b, m] of MENUS) if (!$(m).hidden && !e.target.closest(m) && !e.target.closest(b)) menu(b, m, false);
78
+ const om = $('#ngObjMenu'); if (om && !om.hidden && !e.target.closest('#ngObjMenu, #ngObjB')) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); }
79
+ });
80
+ document.addEventListener('keydown', (e) => {
81
+ if (e.key !== 'Escape') return;
82
+ for (const [b, m] of MENUS) if (!$(m).hidden) { menu(b, m, false); $(b).focus(); return; }
83
+ const om = $('#ngObjMenu'); if (om && !om.hidden) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); $('#ngObjB').focus(); return; }
84
+ if (!$('#side').hidden) closeSide();
62
85
  });
63
86
 
64
- /* ── charts ───────────────────────────────────────────────────────────────────────────────────────────────────── */
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. */
66
- function chartAt(t, j) {
67
- const c = byKey(t.dataset.key); if (!c) return;
68
- const n = c.pts.length; j = j == null ? n - 1 : Math.max(0, Math.min(n - 1, j));
69
- const p = c.pts[j], last = j === n - 1;
70
- const cx = $('.cx', t), dt = $('.dt', t);
71
- cx.setAttribute('x1', X(p.fx)); cx.setAttribute('x2', X(p.fx)); dt.setAttribute('cx', X(p.fx)); dt.setAttribute('cy', Y(p.fy));
72
- t.classList.toggle('hv', !last); t.dataset.j = j;
73
- const val = last ? c.v : p.txt, cap = last ? 'on ' + c.at + (c.targetTxt ? ' · ' + c.targetTxt : '') : 'on ' + p.d + (c.targetTxt ? ' · ' + c.targetTxt : '');
74
- $('.mval', t).textContent = val; $('.mwk', t).textContent = cap;
75
- t.setAttribute('aria-label', c.title + ', ' + (last ? 'now ' : '') + val + ', ' + cap + '. Use the arrow keys to read each reading.');
87
+ /* ── dates and the period (AgInsPeriod) ─────────────────────────────────────────────────────────────────────────────────────────── */
88
+ const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
89
+ const DAY = 864e5;
90
+ const day = (s) => { const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(s || '')); return m ? Date.UTC(+m[1], +m[2] - 1, +m[3]) : null; };
91
+ const iso = (t) => new Date(t).toISOString().slice(0, 10);
92
+ const md = (t) => { if (t == null) return ''; const d = new Date(t); return MON[d.getUTCMonth()] + ' ' + d.getUTCDate(); };
93
+ const today = () => day(M && M.today) || Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate());
94
+ function periods() {
95
+ const d = new Date(today()), y = d.getUTCFullYear(), q = Math.floor(d.getUTCMonth() / 3), h = d.getUTCMonth() < 6 ? 0 : 1;
96
+ const span = (y0, m0, y1, m1) => ({ from: Date.UTC(y0, m0, 1), to: Date.UTC(y1, m1, 0) });
97
+ const lq = q ? { y, q: q - 1 } : { y: y - 1, q: 3 };
98
+ return [
99
+ Object.assign({ key: 'q', label: 'Q' + (q + 1) + ' ' + y, short: 'Q' + (q + 1), name: 'This quarter', said: 'this quarter' }, span(y, q * 3, y, q * 3 + 3)),
100
+ Object.assign({ key: 'lq', label: 'Q' + (lq.q + 1) + ' ' + lq.y, short: 'Q' + (lq.q + 1), name: 'Last quarter', said: 'last quarter' }, span(lq.y, lq.q * 3, lq.y, lq.q * 3 + 3)),
101
+ Object.assign({ key: 'h', label: 'H' + (h + 1) + ' ' + y, short: 'H' + (h + 1), name: 'This half', said: 'this half' }, span(y, h * 6, y, h * 6 + 6)),
102
+ Object.assign({ key: 'y', label: String(y), short: String(y), name: 'This year', said: 'this year' }, span(y, 0, y + 1, 0)),
103
+ ];
76
104
  }
105
+ const inPer = (g, p = per) => {
106
+ if (!p) return true;
107
+ const a = day(g.fromAt) ?? day(g.byAt), b = day(g.byAt) ?? day(g.fromAt);
108
+ return a === null ? true : a <= p.to && b >= p.from;
109
+ };
110
+ function drawPeriod() {
111
+ const P = periods(); if (!per) per = P[0];
112
+ const t = today(), total = Math.round((per.to - per.from) / DAY) + 1, gone = Math.max(0, Math.min(total, Math.round((t - per.from) / DAY) + 1));
113
+ per.gone = t >= per.from && t <= per.to ? gone : 0; per.total = total;
114
+ $('#perName').textContent = per.label;
115
+ $('#perSub').innerHTML = tab === 'outcomes' ? `<span class="ins-perr">shipped or judged ${esc(per.said || 'in these dates')}</span>`
116
+ : `<span class="ins-perr">${esc(md(per.from) + ' – ' + md(per.to))}${per.gone ? ' · ' : ''}</span>${per.gone ? `<span class="ins-perday">day ${gone} of ${total}</span>` : ''}`;
117
+ const n = (p) => M.goals.filter((g) => inPer(g, p)).length, goals = (k) => k + (k === 1 ? ' goal' : ' goals');
118
+ /* a closed period: the goals due in it, and how many reached their target by their date (a reading on or before it) */
119
+ const hits = (p) => { let k = 0, h = 0; for (const g of M.goals) { const by = day(g.byAt); if (by === null || by < p.from || by > p.to) continue; k++; const dir = g.target !== null && g.base !== null ? Math.sign(g.target - g.base) : 0; if (dir && (g.series || []).some((r) => day(r.at) <= by && (dir > 0 ? r.v >= g.target : r.v <= g.target))) h++; } return { k, h }; };
120
+ /* a year names its yearly goals, each shown in a quarter with that quarter's checkpoint (AgInsPeriod) */
121
+ const yearly = (p) => M.goals.filter((g) => inPer(g, p) && g.period && g.period.kind === 'Year').length;
122
+ const sub = (p) => { if (p.key === 'y' && yearly(p)) { const k = yearly(p); return k + (k === 1 ? ' yearly goal, with quarter checkpoints' : ' yearly goals, each with quarter checkpoints'); }
123
+ if (p.to >= t) return md(p.from) + ' – ' + md(p.to) + ' · ' + goals(n(p)); const x = hits(p); return 'Closed · ' + goals(n(p)) + (x.k ? ', ' + x.h + ' of ' + x.k + ' due in it hit' : ', none due in it'); };
124
+ $('#perMenu').innerHTML = P.map((p) => `<button type="button" role="menuitemradio" aria-checked="${per.key === p.key}" data-per="${p.key}">${per.key === p.key ? SV(I.chk) : '<i class="ins-ck"></i>'}<span>${esc(p.name + ' · ' + p.label)}<small>${esc(sub(p))}</small></span></button>`).join('')
125
+ + `<button type="button" role="menuitemradio" aria-checked="${per.key === 'c'}" data-per="c">${per.key === 'c' ? SV(I.chk) : '<i class="ins-ck"></i>'}<span>Custom<small>Pick a start and end date</small></span></button>`
126
+ + `<div class="ins-cust" id="perCust" ${per.key === 'c' ? '' : 'hidden'}><label>From<input type="date" id="perFrom" value="${esc(iso(per.from))}"></label><label>To<input type="date" id="perTo" value="${esc(iso(per.to))}"></label><button type="button" class="cz-chip" id="perGo">Apply</button></div>`
127
+ + '<p class="note ins-mnote">A goal shows here when its period overlaps the one you pick. A yearly goal in a quarter shows that quarter’s checkpoint. Health budgets have no end, so they always show.</p>';
128
+ }
129
+ $('#perMenu').addEventListener('click', (e) => {
130
+ if (e.target.closest('#perGo')) {
131
+ const a = day($('#perFrom').value), b = day($('#perTo').value);
132
+ if (a === null || b === null || b < a) { toast('Pick a start date before the end date.'); return; }
133
+ per = { key: 'c', label: 'Custom', short: 'these dates', name: 'Custom', said: 'in these dates', from: a, to: b }; closeMenus(); redraw(); return;
134
+ }
135
+ const b = e.target.closest('[data-per]'); if (!b) return;
136
+ if (b.dataset.per === 'c') { $('#perCust').hidden = false; $('#perFrom').focus(); return; }
137
+ per = periods().find((p) => p.key === b.dataset.per); closeMenus(); redraw();
138
+ });
77
139
 
78
- /* ── the top card: the pinned dashboard (insights-one-list L4) ─────────────────────────────────────────────────── */
140
+ /* ── the bar: product, tabs, view, filter, find, ⋯ ─────────────────────────────────────────────────────────────────────────────── */
79
141
  const curDash = () => M.dashboards.find((d) => d.id === dash) || M.dashboards[0];
80
- const pinnable = (D) => !!M.board.id && (D.id === 'all' || D.saved);
81
- /* The dashboard's insight band. The finding the page already leads with is skipped, so the band says what else is on this dashboard. */
82
- function findingsHtml(D) {
83
- const I = D.insight; if (!I || I.none) return '';
84
- const all = I.finds, F = all.filter((f) => f.chart !== M.insight.chart), also = F.length < all.length;
85
- const label = also ? 'Also on this dashboard' : 'Insight';
86
- const rows = F.length ? F.map((f) => `<li class="${esc(f.kind)}"><button class="nfr" data-open="${esc(f.chart)}" aria-haspopup="dialog"><i class="nfdot" aria-hidden="true"></i><span class="nft"><b>${esc(f.text)}</b> ${esc(f.why)}</span>${CHV2}</button></li>`).join('')
87
- : `<li class="calm"><div class="nfr"><i class="nfdot" aria-hidden="true"></i><span class="nft">${esc(also ? 'Nothing else stands out here.' : I.calmText)}</span></div></li>`;
88
- return `<div class="nfd" role="region" aria-label="${esc(label)}"><p class="label">${esc(label)}</p><ul>${rows}</ul></div>`;
89
- }
90
- function drawDash() {
91
- const D = curDash(), L = D.keys.map(byKey).filter(Boolean), isPin = M.pinned === D.id;
92
- $('#hDash').textContent = D.name;
93
- $('#dashTag').textContent = isPin ? 'Pinned' : 'Not pinned';
94
- $('#dashTag').className = 'ptag' + (isPin ? ' on' : '');
95
- $('#dashCap').textContent = L.length ? (L.length - D.off) + ' of ' + L.length + ' on their line' : '';
96
- drawDashBar(D, isPin);
97
- $('#cDash').hidden = !D.saved && !M.charts.length; // with nothing to chart, All measures is a row of the list only (premium-calmer-first-screen)
98
- if (D.saved) { drawSaved(D, L); return; }
99
- if (!M.charts.length) {
100
- $('#dashBody').innerHTML = `<div class="nempty" style="margin-top:14px"><p><b>${esc(M.counts.total ? 'No KR metric holds two readings yet.' : 'No KR metric is recorded for this workspace.')}</b> ${esc(M.counts.total ? 'A chart needs a series, so nothing is drawn.' : 'There is nothing to chart. Add one where the KR metrics are kept.')}</p></div>` + noSeriesHtml();
101
- return;
142
+ const dashName = (D) => (D.id === 'all' ? 'All goals' : D.name);
143
+ function drawBar() {
144
+ $('#prodName').textContent = M.board.name || 'Insights';
145
+ const boards = M.board.switcher || [];
146
+ $('#prodMenu').innerHTML = boards.length ? boards.map((b) => `<button type="button" role="menuitemradio" aria-checked="${b.id === M.board.id && b.ws === M.board.ws}" data-ws="${esc(b.ws)}" data-board="${esc(b.id)}">${esc(b.name)}</button>`).join('')
147
+ : '<p class="note ins-mnote">One product is registered.</p>';
148
+ $('#nGoals').textContent = String(goalsShown().length);
149
+ $('#nOutcomes').textContent = String(outcomesShown().length);
150
+ const D = curDash();
151
+ $('#viewName').textContent = dashName(D);
152
+ $('#viewMenu').innerHTML = M.dashboards.map((d) => `<button type="button" role="menuitemradio" aria-checked="${d.id === D.id}" data-view="${esc(d.id)}">${esc(dashName(d))}<small>${d.id === 'all' ? 'Every goal and budget' : d.saved ? 'Saved dashboard · ' + d.charts.length + (d.charts.length === 1 ? ' goal' : ' goals') : 'Objective'}${M.pinned === d.id ? ' · pinned' : ''}</small></button>`).join('');
153
+ drawPeriod(); drawFilter();
154
+ }
155
+ $('#prodMenu').addEventListener('click', (e) => { const b = e.target.closest('[data-board]'); if (!b) return; location.assign('/premium-insights.html?ws=' + encodeURIComponent(b.dataset.ws) + '&board=' + encodeURIComponent(b.dataset.board)); });
156
+ $('#viewMenu').addEventListener('click', (e) => { const b = e.target.closest('[data-view]'); if (!b) return; closeMenus(); setView(b.dataset.view); });
157
+ const setQ = (o) => { const q = new URLSearchParams(location.search); for (const [k, v] of Object.entries(o)) { if (v == null) q.delete(k); else q.set(k, v); } const s = q.toString(); return location.pathname + (s ? '?' + s : ''); };
158
+ function setTab(t) {
159
+ tab = t;
160
+ for (const b of $$('.ins-tabs [role="tab"]')) { const on = b.dataset.tab === t; b.setAttribute('aria-selected', String(on)); b.tabIndex = on ? 0 : -1; }
161
+ $('#pGoals').hidden = t !== 'goals'; $('#pOutcomes').hidden = t !== 'outcomes'; $('#pLibrary').hidden = t !== 'library';
162
+ for (const x of $$('.ins-vw')) x.hidden = t !== 'goals';
163
+ document.body.dataset.tab = t;
164
+ if (M) drawPeriod(); // the period chip says "shipped or judged" on Outcomes
165
+ try { history.replaceState(null, '', setQ({ tab: t === 'goals' ? null : t })); } catch { /* no history */ }
166
+ }
167
+ $('.ins-tabs').addEventListener('click', (e) => { const b = e.target.closest('[role="tab"]'); if (b) setTab(b.dataset.tab); });
168
+ $('.ins-tabs').addEventListener('keydown', (e) => {
169
+ if (!/^Arrow(Left|Right)$/.test(e.key)) return;
170
+ const T = $$('.ins-tabs [role="tab"]'), i = T.findIndex((x) => x.getAttribute('aria-selected') === 'true'), n = T[(i + (e.key === 'ArrowRight' ? 1 : T.length - 1)) % T.length];
171
+ setTab(n.dataset.tab); n.focus();
172
+ });
173
+ function setView(id) { dash = id; setTab('goals'); redraw(); }
174
+
175
+ const FILT_HEAD = { obj: 'Objective', owner: 'Owner', type: 'Type', lane: 'Lane' };
176
+ const noFilter = () => Object.values(filt).every((v) => v === null);
177
+ function filterValues() {
178
+ const moves = M.goals.flatMap((g) => g.moves);
179
+ return {
180
+ obj: [...new Set(M.goals.map((g) => g.pillar || ''))].map((v) => [v, v || 'No objective']),
181
+ owner: [...new Set(moves.map((m) => m.owner).filter(Boolean))].sort().map((v) => [v, v]),
182
+ type: [...new Set(M.goals.map((g) => g.type))].map((v) => [v, v]),
183
+ lane: [...new Set(moves.map((m) => m.lane).filter(Boolean))].sort().map((v) => [v, v]),
184
+ };
185
+ }
186
+ function drawFilter() {
187
+ const V = filterValues();
188
+ const row = (k, v, label) => `<button type="button" role="menuitemcheckbox" aria-checked="${filt[k] === v}" data-fk="${k}" data-fv="${esc(v)}">${filt[k] === v ? SV(I.chk) : '<i class="ins-ck"></i>'}<span>${esc(label)}</span></button>`;
189
+ $('#filtMenu').innerHTML = Object.keys(FILT_HEAD).map((k) => `<p class="ins-mh">${FILT_HEAD[k]}</p>` + (V[k].length ? V[k].map(([v, l]) => row(k, v, l)).join('') : `<p class="note ins-mnote">${k === 'owner' ? 'No initiative that moves a goal names an owner.' : k === 'lane' ? 'No initiative that moves a goal names a lane.' : 'None'}</p>`)).join('')
190
+ + (noFilter() ? '' : '<button type="button" data-fclr>Clear the filter</button>');
191
+ $('#filtDot').hidden = noFilter();
192
+ }
193
+ $('#filtMenu').addEventListener('click', (e) => {
194
+ if (e.target.closest('[data-fclr]')) { filt = { obj: null, owner: null, type: null, lane: null }; closeMenus(); redraw(); return; }
195
+ const b = e.target.closest('[data-fk]'); if (!b) return;
196
+ filt[b.dataset.fk] = filt[b.dataset.fk] === b.dataset.fv ? null : b.dataset.fv; redraw(); menu('#filtB', '#filtMenu', true);
197
+ });
198
+ $('#findB').addEventListener('click', () => { const open = $('#findRow').hidden; $('#findRow').hidden = !open; $('#findB').setAttribute('aria-expanded', String(open)); if (open) $('#findIn').focus(); });
199
+ $('#findIn').addEventListener('input', () => { find = $('#findIn').value.trim().toLowerCase(); redraw(); });
200
+ $('#findX').addEventListener('click', () => { $('#findIn').value = ''; find = ''; $('#findRow').hidden = true; $('#findB').setAttribute('aria-expanded', 'false'); redraw(); $('#findB').focus(); });
201
+ const hit = (...s) => !find || s.some((x) => String(x || '').toLowerCase().includes(find));
202
+
203
+ /* ⋯: Sources, Export (no route yet) and About these numbers, each in the Viewer card */
204
+ $('#moreMenu').addEventListener('click', (e) => {
205
+ const b = e.target.closest('[data-more]'); if (!b || b.disabled) return; closeMenus();
206
+ if (b.dataset.more === 'sources') viewer({ kind: 'Insights', title: 'Sources', icon: 'list', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
207
+ else if (b.dataset.more === 'export') location.assign('/api/insights-records/export?' + wsQ() + (M.board.id ? 'board=' + encodeURIComponent(M.board.id) : ''));
208
+ else if (b.dataset.more === 'about') viewer({ kind: 'Insights', title: 'About these numbers', icon: 'info', eye: 'Insights', render: (el) => { el.innerHTML = ABOUT; } });
209
+ });
210
+ function sourcesHtml() {
211
+ const miss = (M.header && M.header.missing) || [];
212
+ const rows = [
213
+ ['Goals', 'The KR metric records of this workspace and their readings (planning/records/kr-metrics.jsonl)', !miss.includes('outcomes')],
214
+ ['What moves them', 'The board’s initiatives and their anchors', M.initiativesRead],
215
+ ['Health budgets', 'The budget registry (planning/okrs/health-budgets.md) and the initiatives anchored to health:<id>', M.budgetsRead && M.initiativesRead],
216
+ ['Charts and verdicts', 'Each chart’s form and range, the verdicts and the trend targets (the workspace’s insights-records.jsonl)', !((M.header && M.header.missing) || []).includes('insights records')],
217
+ ['Delivery trends', 'The Board’s measures (corrections, merges, blocked and idle work)', !!BM],
218
+ ['Library', 'The report files, the report setups and your requests', !M.reports.missing],
219
+ ];
220
+ return `<div class="ins-src">${rows.map(([a, b, ok]) => `<div><b>${esc(a)}</b><span>${esc(b)}</span><span class="cz-pill ${ok ? 'ok' : 'late'}">${ok ? 'Read' : 'Not read'}</span></div>`).join('')}</div>`
221
+ + (miss.length ? `<p class="note">Not read on the last load: ${esc(miss.join(', '))}.</p>` : '');
222
+ }
223
+ const ABOUT = '<div class="ins-about"><p>Every goal is a KR metric record of this workspace, and every number on Goals is one of its readings, its target or its date. The bar under Now has a mark for how much of the goal’s time has gone.</p>'
224
+ + '<p>“By its date” is a straight line through the last four readings, carried to the goal’s date. It is said, not drawn as a fact. A goal with fewer than two readings has no line and no pace.</p>'
225
+ + '<p>What moves a goal is every initiative whose anchor names it. Its pill is read from its end date and owner: days over, ships soon, or no owner.</p>'
226
+ + '<p>A press records only what it says: a goal in the KR metric records, or a dashboard in the workspace’s state folder. Nothing is sent from this page.</p></div>';
227
+
228
+ /* ── the strip ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
229
+ function drawStrip() {
230
+ const I0 = M.insight, G = goalsShown();
231
+ const behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
232
+ $('#insEye').textContent = per && per.gone && per.key !== 'c' ? per.gone + ' of ' + per.total + ' days gone in ' + per.short + '.' : G.length + (G.length === 1 ? ' goal' : ' goals') + (behind ? ', ' + behind + ' behind.' : '.');
233
+ $('#brief').textContent = I0.text;
234
+ $('#insWhy').textContent = I0.none ? '' : I0.why || '';
235
+ $('#askWhy').href = homeAsk('insights', I0.none ? 'Why is there no insight on my goals yet?' : 'Why? ' + I0.text);
236
+ $('#askWhy').hidden = false;
237
+ }
238
+
239
+ /* ── Goals (AgInsGoals) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── */
240
+ const COLS = 'ins-cols';
241
+ function moveHit(g) { return (filt.owner === null || g.moves.some((m) => m.owner === filt.owner)) && (filt.lane === null || g.moves.some((m) => m.lane === filt.lane)); }
242
+ function goalsShown() {
243
+ const D = curDash(), ids = D.saved ? D.charts : null;
244
+ const L = M.goals.filter((g) => inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
245
+ && (filt.obj === null || (g.pillar || '') === filt.obj) && (filt.type === null || g.type === filt.type) && moveHit(g) && hit(g.title, g.pillar, ...g.moves.map((m) => m.title)));
246
+ return ids ? L.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)) : L;
247
+ }
248
+ const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok', 'on hold': 'q' };
249
+ /** The lifecycle track: six stages and two milestones; the current stage is the large dot in the initiative's status colour. A stage the Board
250
+ * recorded as skipped (its "Skipped <stage>" warning) is a dashed ring. */
251
+ function trackHtml(r) {
252
+ const tone = TRACK_TONE[r.status] || 'q', labels = (M.lifecycle || []).map((x) => x.label.toLowerCase()), skip = new Set((r.skipped || []).map((x) => labels.indexOf(String(x).toLowerCase())).filter((i) => i >= 0));
253
+ return `<span class="ins-trk" title="${esc(r.stageLabel || 'No stage')}" aria-label="${esc((r.stageLabel ? 'Stage ' + r.stageLabel : 'No lifecycle stage') + (r.status ? ', ' + r.status : ''))}" role="img">`
254
+ + [0, 1, 2, 3, 4, 5, 6, 7].map((i) => `<i class="${[skip.has(i) && i !== r.idx ? 'k' : i < r.idx ? 'p' : '', i === r.idx ? 'c ' + tone : '', i === 5 || i === 7 ? 'm' : ''].filter(Boolean).join(' ')}"></i>`).join('') + '</span>';
255
+ }
256
+ /** The pill of an initiative that moves a goal: a delivery fact read from its end date and owner, else its status. */
257
+ function movePill(r) {
258
+ if (r.status === 'done') return ['ok', 'Done'];
259
+ if (r.status === 'cancelled') return ['q', 'Stopped'];
260
+ const end = day(r.endAt), d = end === null ? null : Math.round((end - today()) / DAY);
261
+ if (d !== null && d < 0 && r.idx < 6) return ['late', -d + (d === -1 ? ' day over' : ' days over')]; // Monitor and Evaluate have shipped
262
+ if (!r.owner) return ['risk', 'No owner'];
263
+ if (d === 0) return ['q', 'Ships today'];
264
+ if (d === 1) return ['q', 'Ships tomorrow'];
265
+ if (d !== null && d >= 0 && d <= 14) return ['q', 'Ships in ' + d + ' days'];
266
+ return { late: ['late', 'Late'], 'at risk': ['risk', 'At risk'], 'on hold': ['q', 'On hold'], 'on track': ['q', 'On track'] }[r.status] || null;
267
+ }
268
+ const initRow = (r, pill = true) => { const p = pill ? movePill(r) : null; return `<a class="ins-ini" href="${iniHref(r.id)}">${trackHtml(r)}<span class="n">${esc(r.title)}</span>${p ? `<span class="cz-pill ${p[0]}">${esc(p[1])}</span>` : ''}</a>`; };
269
+ const TONE_BAR = { ok: 'var(--cz-dot-ok)', late: 'var(--cz-dot-late)', red: 'var(--cz-dot-red)', q: 'var(--cz-dot-q)', risk: 'var(--cz-dot-risk)' };
270
+ function barHtml(g, cls = '') {
271
+ return `<div class="ins-bar1${cls}" role="img" aria-label="${g.done === null ? 'No progress to read' : Math.round(g.done * 100) + '% of the way to the target'}${g.timeGone == null ? '' : ', ' + Math.round(g.timeGone * 100) + '% of its time gone'}"><i style="width:${g.done === null ? 0 : Math.round(g.done * 100)}%;background:${TONE_BAR[g.tone] || TONE_BAR.q}"></i>${g.timeGone == null ? '' : `<span class="today" title="today" style="left:${Math.round(g.timeGone * 100)}%"></span>`}</div>`;
272
+ }
273
+ /** The so-far sparkline: the readings at their dates across the goal's span, the target dashed, and the pace carried to the date, dashed. */
274
+ function sparkHtml(g, w = 210, h = 40) {
275
+ const c = g.key ? byKey(g.key) : null;
276
+ if (!c) return `<span class="note">${esc(g.readings ? 'One reading, no series yet' : 'No reading yet')}</span>`;
277
+ const t0 = day(c.pts[0].at), tl = day(c.pts[c.pts.length - 1].at), t1 = Math.max(tl, day(g.byAt) || tl);
278
+ const ys = c.pts.map((p) => p.v).concat(g.target !== null ? [g.target] : [], g.proj ? [g.proj.atDue] : []), lo = Math.min(...ys), hi = Math.max(...ys), rg = hi - lo || 1;
279
+ const x = (t) => 5 + (t1 > t0 ? (t - t0) / (t1 - t0) : 1) * (w - 10), y = (v) => 4 + (1 - (v - lo) / rg) * (h - 8);
280
+ const pts = c.pts.map((p) => x(day(p.at)).toFixed(1) + ',' + y(p.v).toFixed(1)), last = pts[pts.length - 1].split(',');
281
+ const fill = `${x(t0).toFixed(1)},${h} ${pts.join(' ')} ${last[0]},${h}`;
282
+ const proj = g.proj && day(g.byAt) > tl ? `<polyline points="${last.join(',')} ${x(day(g.byAt)).toFixed(1)},${y(g.proj.atDue).toFixed(1)}" class="pj"/>` : '';
283
+ return `<svg class="ins-spark" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="${esc(g.title + ': ' + c.pts.length + ' readings' + (g.targetTxt ? ', target ' + g.targetTxt : ''))}"><polygon points="${fill}" class="ar"/>${g.target !== null ? `<line x1="0" x2="${w}" y1="${y(g.target).toFixed(1)}" y2="${y(g.target).toFixed(1)}" class="tg"/>` : ''}${proj}<polyline points="${pts.join(' ')}" class="ln"/><circle cx="${last[0]}" cy="${last[1]}" r="3.6" class="dt" style="fill:${TONE_BAR[g.tone]}"/></svg>`;
284
+ }
285
+ /** A Count goal with a small whole target is drawn as blocks: one per unit of the target, the ones reached filled. */
286
+ const isBlocks = (g) => g.type === 'Count' && Number.isInteger(g.target) && g.target >= 1 && g.target <= 12 && Number.isInteger(g.now) && g.now >= 0;
287
+ const blocksHtml = (g, w, names = true) => `<div class="ins-blocks" style="width:${w}px" role="img" aria-label="${esc(g.now + ' of ' + g.target)}">${Array.from({ length: g.target }, (_, i) => `<i class="${i < g.now ? 'on' : ''}"></i>`).join('')}</div>`
288
+ + (names && g.items && g.items.length ? `<div class="note ins-items">${esc(g.items.slice(0, g.now).join(', '))}</div>` : ''); // the reached items, when the goal records them
289
+ /** Done or not: its steps as a checklist; Stay within: the readings over a green band that marks the budget, with no forecast. */
290
+ const stepsHtml = (g) => `<div class="ins-steps">${(g.steps || []).map((s) => `<span class="${s.done ? 'on' : ''}"><i class="ins-cb${s.done ? ' on' : ''}">${s.done ? SV(I.chk, 3) : ''}</i>${esc(s.text)}</span>`).join('')}</div>`;
291
+ /** pts [{ at, v }] over a band: the floor or ceiling `lim` to the chart's edge is green (inside the budget); the line has no target line and no
292
+ * forecast. ceil: the budget is below the limit. One reading is drawn as a dot. */
293
+ function bandSvg(pts, lim, ceil, tone, label, w = 210, h = 40) {
294
+ const ys = pts.map((p) => p.v).concat([lim]), lo = Math.min(...ys), hi = Math.max(...ys), rg = hi - lo || 1;
295
+ const t0 = day(pts[0].at), t1 = day(pts[pts.length - 1].at), x = (t) => (t1 > t0 ? 5 + (t - t0) / (t1 - t0) * (w - 10) : w - 5), y = (v) => 4 + (1 - (v - lo) / rg) * (h - 8);
296
+ const yl = y(lim), band = ceil ? `<rect x="0" y="${yl.toFixed(1)}" width="${w}" height="${(h - yl).toFixed(1)}" class="bd"/>` : `<rect x="0" y="0" width="${w}" height="${yl.toFixed(1)}" class="bd"/>`;
297
+ const L = pts.map((p) => x(day(p.at)).toFixed(1) + ',' + y(p.v).toFixed(1)), last = L[L.length - 1].split(',');
298
+ const line = L.length > 1 ? `<polygon points="${L[0].split(',')[0]},${h} ${L.join(' ')} ${last[0]},${h}" class="ar"/><polyline points="${L.join(' ')}" class="ln"/>` : '';
299
+ return `<svg class="ins-spark" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="${esc(label)}">${band}${line}<circle cx="${last[0]}" cy="${last[1]}" r="3.6" class="dt" style="fill:${TONE_BAR[tone] || TONE_BAR.q}"/></svg>`;
300
+ }
301
+ function soFarHtml(g, w = 210) {
302
+ if (g.type === 'Done or not') return g.steps && g.steps.length ? stepsHtml(g) : '<span class="note">No steps recorded</span>';
303
+ if (g.type === 'Stay within' && g.target !== null && g.series && g.series.length) {
304
+ return bandSvg(g.series, g.target, g.limit !== 'floor', g.pace && g.pace.tone !== 'q' ? g.pace.tone : g.tone, g.title + ': ' + g.series.length + (g.series.length === 1 ? ' reading' : ' readings') + ', the green band is inside the budget', w);
102
305
  }
103
- const off = D.off, tot = L.length;
104
- $('#dashBody').innerHTML = `<div class="mprog" role="progressbar" aria-label="Measures on their line" aria-valuemin="0" aria-valuemax="${tot}" aria-valuenow="${tot - off}"><b style="width:${(tot - off) / tot * 100}%"></b></div>`
105
- + findingsHtml(D)
106
- + `<p class="mhint" style="margin-top:6px"><b>${tot - off} of ${tot}</b> on their line${off ? `. <b class="mflag">${off} ${off === 1 ? 'is' : 'are'} behind it.</b>` : '.'} ${infoBtn('dashFold', 'About these charts')}</p><div class="ifold" id="dashFold" hidden><p class="mhint">Each chart is one KR metric, drawn at the dates of its readings. A gap between readings is left as a gap. The dashed line is the target.</p></div>`
107
- + `<div class="ngrid">${L.map((c) => tileWrap(c)).join('')}</div>` + (D.id === 'all' ? mineHtml() + noSeriesHtml() : '');
108
- }
109
- /* The bar under the heading: Pin or Unpin, Back to the pinned one, a saved dashboard's purpose and Edit, and New chart. Hidden with no board to save on. */
110
- function drawDashBar(D, isPin) {
111
- const bar = $('#dashBar'); dashMenu(false);
112
- $('#dashPurpose').textContent = D.saved ? D.purpose : D.id === 'all' ? 'Every KR metric of this board. PMOS makes it, so it cannot be deleted.' : 'The measures of the ' + D.name + ' pillar.';
113
- $('#dashMore').hidden = !M.board.id;
114
- if (!M.board.id) { bar.innerHTML = ''; return; }
115
- const P = M.pinned ? M.dashboards.find((d) => d.id === M.pinned) : null;
116
- bar.innerHTML = `<p class="note pdst">${isPin ? 'Pinned to the top of Insights' : 'Not pinned'}</p>`
117
- + (pinnable(D) ? `<button class="dmcta${isPin ? ' alt' : ''}" id="pdPin" data-pin="${esc(isPin ? '' : D.id)}" aria-pressed="${isPin}">${ICO(PINI)}${isPin ? 'Unpin' : 'Pin'}</button>` : '')
118
- + (P && !isPin ? `<button class="dmcta alt" id="pdBack">Back to ${esc(P.name)}</button>` : '')
119
- + (D.saved ? '<button class="dmcta alt" id="pdEdit" aria-haspopup="dialog">Edit</button>' : '')
120
- + (M.charts.length ? '<button class="dmcta alt" id="pcNew" aria-haspopup="dialog">New chart</button>' : '');
121
- }
122
- function drawSaved(D, L) {
123
- const off = D.off, tot = L.length;
124
- const gone = D.gone.length ? `<p class="label ngl">Not drawn · ${D.gone.length}</p><div class="dplist" role="list">${D.gone.map((g) => `<div class="nempty" role="listitem" style="margin-bottom:6px"><p><b>${esc(g.title)}</b><br>${esc(g.why)}</p></div>`).join('')}</div>` : '';
125
- const checks = D.checks.length ? `<p class="note pdck">${D.checks.map(esc).join(' ')}</p>` : '';
126
- $('#dashBody').innerHTML = (tot ? `<div class="mprog" role="progressbar" aria-label="Measures on their line" aria-valuemin="0" aria-valuemax="${tot}" aria-valuenow="${tot - off}"><b style="width:${(tot - off) / tot * 100}%"></b></div>`
127
- + findingsHtml(D)
128
- + `<p class="mhint" style="margin-top:6px"><b>${tot - off} of ${tot}</b> on their line${off ? `. <b class="mflag">${off} ${off === 1 ? 'is' : 'are'} behind it.</b>` : '.'} ${infoBtn('dashFold', 'About these charts')}</p><div class="ifold" id="dashFold" hidden><p class="mhint">The charts are drawn in the order you saved. The dashed line is the target.</p></div>`
129
- + `<div class="ngrid">${L.map((c) => tileWrap(c)).join('')}</div>`
130
- : `<div class="nempty" style="margin-top:14px"><p><b>This dashboard draws no chart yet.</b> Press Edit to add a measure with a series.</p></div>`) + checks + gone;
131
- }
132
- /* A tile with its footer: Details, and Edit for a chart the PM saved (premium-studio-chart C4). */
133
- const tileWrap = (c) => `<div class="ntw">${tileHtml(c)}<div class="ntf"><button class="lk" data-open="${esc(c.key)}">Details</button>${c.mine ? `<button class="lk" data-ced="${esc(c.id)}" aria-haspopup="dialog">Edit</button>` : ''}</div></div>`;
134
- /* The board's saved charts under All measures (premium-studio-chart C2). A saved chart whose measure has no series in its range is listed, not drawn. */
135
- function mineHtml() {
136
- const L = M.mine || [], G = M.mineGone || [];
137
- if (!L.length && !G.length) return '';
138
- return `<p class="label ngl">Your charts · ${L.length + G.length}</p>` + (L.length ? `<div class="ngrid">${L.map(tileWrap).join('')}</div>` : '')
139
- + G.map((g) => `<div class="nempty" role="listitem" style="margin-bottom:6px"><p><b>${esc(g.title)}</b><br>${esc(g.why)} It is not drawn. <button class="lk" data-ced="${esc(g.id)}" aria-haspopup="dialog">Edit</button></p></div>`).join('');
140
- }
141
- function noSeriesHtml() {
142
- const N = M.noSeries; if (!N.length) return '';
143
- return `<p class="label ngl">No series recorded · ${N.length}</p><div class="dplist" role="list">${N.map((n) => `<div class="nempty" role="listitem" style="margin-bottom:6px"><p><b>${esc(n.title)}</b>${n.pillar ? ' · ' + esc(n.pillar) : ''}<br>${esc(n.why)} It is not drawn.</p></div>`).join('')}</div>`;
144
- }
145
- /* Pin or unpin (PRD L4): one `pin` line in the dashboards ledger. The pinned dashboard shows in the top card of this page, and nowhere else. */
146
- async function pinDash(id, from) {
147
- const res = await pmPost('/api/premium-dashboards/pin', { ws: M.board.ws, board: M.board.id, id: id || null });
148
- if (!res || res.ok !== true) { toast((res && res.error) || 'The pin could not be saved. Nothing changed.'); return; }
149
- const D = M.dashboards.find((d) => d.id === id);
150
- dash = res.pinned || 'all';
151
- toast(res.pinned ? 'Pinned ' + (D ? D.name : 'the dashboard') + '. It shows at the top of Insights.' : 'Unpinned. All measures shows at the top.');
152
- await load();
153
- if (from === 'list') { try { $('#cDash').scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch { /* no scroll */ } }
154
- }
155
- /* the ⋯ of the top card: Pin or Unpin, Back, Edit and New chart (premium-calmer-first-screen) */
156
- function dashMenu(open) { $('#dashBar').hidden = !open; $('#dashMore').setAttribute('aria-expanded', String(open)); }
157
- $('#dashMore').addEventListener('click', () => { const open = $('#dashBar').hidden; dashMenu(open); if (open) { const f = $('#dashBar button'); if (f) f.focus(); } });
158
- document.addEventListener('click', (e) => { if (!$('#dashBar').hidden && !e.target.closest('#dashBar, #dashMore')) dashMenu(false); });
159
- document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !$('#dashBar').hidden) { dashMenu(false); $('#dashMore').focus(); } });
160
- $('#dashBar').addEventListener('click', (e) => {
161
- const pin = e.target.closest('#pdPin'); if (pin) { pin.disabled = true; pinDash(pin.dataset.pin || null, 'card'); return; }
162
- if (e.target.closest('#pdBack')) { dash = M.pinned; drawDash(); drawList(); return; }
163
- if (e.target.closest('#pdEdit')) openDashEdit(curDash()); else if (e.target.closest('#pcNew')) openChartEdit(null);
306
+ if (isBlocks(g)) return blocksHtml(g, w);
307
+ return sparkHtml(g, w);
308
+ }
309
+ const PACE_C = { ok: 'var(--cz-ok)', late: 'var(--cz-late)', risk: 'var(--cz-risk)', q: 'var(--cz-ink3)' };
310
+ function goalSub(g) {
311
+ const by = day(g.byAt), late = per && by !== null && by > per.to && per.key !== 'y' && per.key !== 'c';
312
+ if (g.type === 'Done or not') return [g.steps && g.steps.length ? g.steps.filter((x) => x.done).length + ' of ' + g.steps.length + ' steps' : '', by !== null ? 'due ' + md(by) : ''].filter(Boolean).join(' · ');
313
+ if (g.type === 'Stay within') return [g.dirTxt + ' ' + (g.targetTxt || ''), g.alwaysOn ? 'always on' : by !== null ? 'until ' + md(by) : ''].filter(Boolean).join(' · ');
314
+ const from = g.baseTxt ? 'from ' + g.baseTxt + (g.fromAt && (g.type === 'Percentage' || g.type === 'Amount') ? ' on ' + md(day(g.fromAt)) : '') : '';
315
+ const cp = late ? (g.checkpoints || []).find((c) => day(c.by) >= per.from && day(c.by) <= per.to) : null;
316
+ const unitOf = (v) => { const u = String(g.unit || '').trim(); return v + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : ''); };
317
+ return [g.dirTxt, from, late ? 'due ' + md(by) + ' ' + new Date(by).getUTCFullYear() + ' · ' + (cp ? per.short + ' checkpoint ' + unitOf(cp.target) : 'no ' + per.short + ' checkpoint recorded') : ''].filter(Boolean).join(' · ');
318
+ }
319
+ function goalRow(g) {
320
+ const sel = selecting && picked.includes(g.id);
321
+ return `<div class="ins-tr ins-row ${COLS}${sel ? ' sel' : ''}" role="row" data-goal="${esc(g.id)}" tabindex="0" aria-label="${esc(g.title)}"${selecting ? ` aria-selected="${sel}"` : ''}>`
322
+ + `<div class="nm" role="cell"><span><b>${esc(g.title)}</b><small><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="ins-sub" title="${esc(goalSub(g))}">${esc(goalSub(g))}</span></small></span></div>`
323
+ + `<div class="val" role="cell"><b>${esc(g.nowTxt || '—')}</b> <span class="note">${esc(g.targetTxt ? 'of ' + g.targetTxt : 'no target')}</span>${barHtml(g)}</div>`
324
+ + `<div class="sofar" role="cell">${soFarHtml(g)}</div>`
325
+ + `<div class="pace" role="cell"><b style="color:${PACE_C[g.pace.tone]}">${esc(g.pace.head)}</b><div class="note">${esc(g.pace.sub)}</div></div>`
326
+ + `<div class="mv" role="cell">${g.moves.length ? g.moves.slice(0, 3).map((r) => initRow(r)).join('') + (g.moves.length > 3 ? `<span class="note">and ${g.moves.length - 3} more</span>` : '') : `<span class="note">${M.initiativesRead ? 'No initiative anchors to it' : 'The initiatives are not read yet'}</span>`}</div>`
327
+ + '</div>';
328
+ }
329
+ /** A health budget (D59): always on. Its reading is its share of the board's open initiatives, against its quarterly cap (planning/okrs/health-budgets.md). */
330
+ const pct = (v) => Math.round(v * 100) + '%';
331
+ function budgetRow(b) {
332
+ const R = b.reading, cap = b.cap;
333
+ const val = R ? `<b>${R.n}</b> <span class="note">of ${R.total} open initiatives</span>` : '<b>—</b> <span class="note">' + (b.declared ? 'the initiatives are not read' : 'not in the budget registry') + '</span>';
334
+ const scale = R && R.share !== null && cap !== null ? Math.max(cap * 1.5, R.share) || 1 : 1;
335
+ const bar = R && R.share !== null && cap !== null ? `<div class="ins-bar1" role="img" aria-label="${esc(pct(R.share) + ' of open initiatives, cap ' + pct(cap))}"><i style="width:${Math.round(R.share / scale * 100)}%;background:${R.over ? TONE_BAR.late : TONE_BAR.ok}"></i><span class="today" title="cap" style="left:${Math.round(cap / scale * 100)}%"></span></div>` : barHtml({ done: null, timeGone: null, tone: 'q' });
336
+ const pace = !R || R.share === null ? ['var(--cz-ink3)', '—', b.declared ? 'no open initiative to share' : 'add it to health-budgets.md to give it a cap']
337
+ : R.over ? ['var(--cz-late)', 'Over its ' + pct(cap) + ' cap', pct(R.share) + ' of open initiatives'] : ['var(--cz-ok)', 'Within its ' + pct(cap) + ' cap', pct(R.share) + ' of open initiatives'];
338
+ return `<div class="ins-tr ins-row ${COLS} ins-budget" role="row" data-budget="${esc(b.id)}" tabindex="0" aria-label="${esc(b.title)}">`
339
+ + `<div class="nm" role="cell"><span><b>${esc(b.title)}</b><small><span class="cz-pill q ins-type">Stay within</span><span class="ins-sub">always on${cap !== null ? ' · cap ' + pct(cap) + ' of a quarter' : ''}</span></small></span></div>`
340
+ + `<div class="val" role="cell">${val}${bar}</div>`
341
+ + `<div class="sofar" role="cell">${R && R.share !== null && cap !== null ? bandSvg([{ at: M.today || iso(today()), v: R.share * 100 }], cap * 100, true, R.over ? 'late' : 'ok', b.title + ': ' + pct(R.share) + ' of open initiatives, the green band is inside its ' + pct(cap) + ' cap') : ''}<span class="note">${esc(b.covers ? 'Covers ' + b.covers : 'What it covers is not declared')}</span></div>`
342
+ + `<div class="pace" role="cell"><b style="color:${pace[0]}">${esc(pace[1])}</b><div class="note">${esc(pace[2])}</div></div>`
343
+ + `<div class="mv" role="cell">${b.moves.length ? b.moves.slice(0, 3).map((r) => initRow(r)).join('') : '<span class="note">No initiative anchors to it</span>'}</div></div>`;
344
+ }
345
+ const GRP_PILL = (L) => {
346
+ const scored = L.filter((g) => g.tone !== 'q'), bad = scored.filter((g) => g.tone === 'late' || g.tone === 'red').length;
347
+ return !scored.length ? '' : bad ? `<span class="cz-pill late">${bad} of ${L.length} behind</span>` : '<span class="cz-pill ok">on track</span>';
348
+ };
349
+ function drawGoals() {
350
+ const G = goalsShown(), T = $('#goalTbl');
351
+ const head = `<div class="ins-tr ins-th ${COLS}" role="row"><div role="columnheader">Goal <span>${G.length} · in ${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>`;
352
+ const D = curDash();
353
+ if (!M.goals.length) {
354
+ T.innerHTML = head + '<div class="ins-empty"><b>No goal is recorded for this workspace.</b> A goal is a KR metric with a target and a date. Press New, then New goal.</div>' + budgetsHtml(D) + bmHtml();
355
+ drawCards([]); return;
356
+ }
357
+ const by = new Map(); for (const g of G) { const k = g.pillar || ''; if (!by.has(k)) by.set(k, []); by.get(k).push(g); }
358
+ const objs = [...new Set(M.goals.map((g) => g.pillar || ''))];
359
+ const groups = [...by.entries()].map(([k, L]) => `<div class="ins-grp" role="row"><span role="cell">${k ? 'Objective ' + (objs.indexOf(k) + 1) + ' · ' + esc(k) : 'No objective'}</span> <span class="q">${esc(per ? per.label : '')}</span>${GRP_PILL(L)}</div>` + L.map(goalRow).join('')).join('');
360
+ T.innerHTML = head + (G.length ? groups : `<div class="ins-empty">No goal matches${find ? ' “' + esc(find) + '”' : ''}${noFilter() ? '' : ' this filter'} in ${esc(per.label)}. <button type="button" class="lk" id="goalsAll">Show every goal</button></div>`) + budgetsHtml(D) + bmHtml();
361
+ drawCards(G);
362
+ }
363
+ function budgetsHtml(D) {
364
+ if (D.saved || D.id.startsWith('p:') || !M.initiativesRead || filt.obj !== null || (filt.type !== null && filt.type !== 'Stay within')) return '';
365
+ const B = (M.budgets || []).filter((b) => hit(b.title, ...b.moves.map((m) => m.title)) && (filt.owner === null || b.moves.some((m) => m.owner === filt.owner)) && (filt.lane === null || b.moves.some((m) => m.lane === filt.lane)));
366
+ return '<div class="ins-grp" role="row"><span role="cell">Health budgets</span> <span class="q">always on, judged every week</span></div>'
367
+ + (B.length ? B.map(budgetRow).join('') : '<div class="ins-empty ins-sm2">No health budget is declared and no initiative anchors to one.</div>');
368
+ }
369
+ $('#goalTbl').addEventListener('click', (e) => {
370
+ if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; filt = { obj: null, owner: null, type: null, lane: null }; per = periods()[3]; redraw(); return; }
371
+ if (e.target.closest('a')) return;
372
+ const tile = e.target.closest('[data-tile]'); if (tile) { openTarget(tile.dataset.tile); return; }
373
+ const bu = e.target.closest('[data-budget]'); if (bu) { openBudget(bu.dataset.budget); return; }
374
+ const r = e.target.closest('[data-goal]'); if (r) pressGoal(r.dataset.goal);
164
375
  });
376
+ $('#goalTbl').addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; const r = e.target.closest && e.target.closest('.ins-row, [data-tile]'); if (!r || e.target !== r) return; e.preventDefault(); r.click(); });
377
+ /** A goal press: picks it while New dashboard is open; opens Edit chart on a saved dashboard (AgInsChart); otherwise the goal detail waits for its design. */
378
+ function pressGoal(id) {
379
+ if (selecting) { picked = picked.includes(id) ? picked.filter((x) => x !== id) : picked.concat(id); drawGoals(); drawDashSide(); return; }
380
+ const D = curDash();
381
+ if (D.saved) openChartEdit(id, D); else openGoalDetail(id);
382
+ }
383
+ /* a goal's detail and readings: no agreed design, so a plain list of its readings, a form to add one, and a Done-or-not goal's steps to tick */
384
+ function openGoalDetail(id) {
385
+ const g = M.goals.find((x) => x.id === id); if (!g) return;
386
+ viewer({ kind: 'Goal', title: g.title, icon: 'goal', render: (el) => {
387
+ const steps = g.type === 'Done or not' && g.steps && g.steps.length;
388
+ const facts = [['Type', g.type], ['Now', g.nowTxt || 'no reading'], ['Target', g.targetTxt ? g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'none'], ['By its date', g.pace.head + (g.pace.sub ? ' · ' + g.pace.sub : '')],
389
+ g.owner ? ['Owner', g.owner] : null, g.guardrail ? ['Guardrail', g.guardrail] : null, g.source ? ['Readings from', SRC_NAME[g.source] || g.source] : null].filter(Boolean);
390
+ el.innerHTML = waitMark('A goal’s detail and readings') + `<dl class="ins-kv">${facts.map(([a, b]) => `<dt>${esc(a)}</dt><dd>${esc(b)}</dd>`).join('')}</dl>`
391
+ + (steps ? `<form class="ins-mf" data-stf><p class="ins-fl">Steps</p>${g.steps.map((x, i) => `<label class="ins-ck2"><input type="checkbox" name="s${i}"${x.done ? ' checked' : ''}> ${esc(x.text)}</label>`).join('')}<div class="ins-mact"><button type="submit" class="ins-primary">Save steps</button><span class="note" data-msg></span></div></form>` : '')
392
+ + `<p class="ins-fl">Readings <span class="q">${g.series.length}</span></p>` + (g.series.length ? `<ul class="ins-rd">${g.series.slice().reverse().map((r) => `<li><span>${esc(md(day(r.at)) + ' ' + r.at.slice(0, 4))}</span><b>${esc(String(r.v) + (g.unit ? (/^[A-Za-z]/.test(g.unit) ? ' ' + g.unit : g.unit) : ''))}</b></li>`).join('')}</ul>` : '<p class="note">No reading is recorded yet.</p>')
393
+ + (steps ? '' : `<form class="ins-mf" data-rdf><p class="ins-fl">Add a reading</p><div class="ins-2"><label class="ins-fl">Date<input class="ins-inp" type="date" name="at" value="${esc(M.today || '')}"></label><label class="ins-fl">Value<input class="ins-inp" name="v" inputmode="decimal" maxlength="16"></label></div><div class="ins-mact"><button type="submit" class="ins-primary">Add reading</button><span class="note" data-msg></span></div></form>`);
394
+ const done = async (res, msg, said) => { if (!res || res.ok !== true) { msg.textContent = (res && res.error) || 'It could not be saved. Nothing changed.'; return; } toast(said); await load(); openGoalDetail(id); };
395
+ const rf = el.querySelector('[data-rdf]');
396
+ if (rf) rf.addEventListener('submit', async (e) => {
397
+ e.preventDefault(); const msg = rf.querySelector('[data-msg]'), v = rf.v.value.trim(), at = rf.at.value;
398
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(at) || v === '' || !Number.isFinite(Number(v))) { msg.textContent = 'Pick a date and type a number.'; return; }
399
+ msg.textContent = 'Saving.'; done(await pmPost('/api/records/kr-metrics/reading', { ws: M.board.ws, rid: g.id, at, value: Number(v), why: 'Reading from Insights' }), msg, 'Added the reading.');
400
+ });
401
+ const sf = el.querySelector('[data-stf]');
402
+ if (sf) sf.addEventListener('submit', async (e) => {
403
+ e.preventDefault(); const msg = sf.querySelector('[data-msg]'); msg.textContent = 'Saving.';
404
+ done(await pmPost('/api/insights-records/steps', { ws: M.board.ws, rid: g.id, done: g.steps.map((_, i) => sf['s' + i].checked) }), msg, 'Saved the steps.');
405
+ });
406
+ } });
407
+ }
408
+ /* a health budget's detail: what it covers, its cap, its reading and the work anchored to it */
409
+ function openBudget(id) {
410
+ const b = (M.budgets || []).find((x) => x.id === id); if (!b) return;
411
+ viewer({ kind: 'Health budget', title: b.title, icon: 'goal', render: (el) => {
412
+ const R = b.reading;
413
+ el.innerHTML = waitMark('A health budget’s detail') + `<dl class="ins-kv"><dt>Anchor</dt><dd>${esc(b.anchor)}</dd><dt>Covers</dt><dd>${esc(b.covers || 'Not declared in health-budgets.md')}</dd><dt>Cap</dt><dd>${b.cap !== null ? pct(b.cap) + ' of a quarter’s initiatives' : 'none declared'}</dd><dt>Now</dt><dd>${R && R.share !== null ? R.n + ' of ' + R.total + ' open initiatives (' + pct(R.share) + ')' : 'no reading'}</dd></dl>`
414
+ + `<p class="ins-fl">Anchored to it <span class="q">${b.moves.length}</span></p>` + (b.moves.length ? b.moves.map((r) => initRow(r)).join('') : '<p class="note">No initiative anchors to it.</p>')
415
+ + '<p class="note">The PM edits the budgets in planning/okrs/health-budgets.md.</p>';
416
+ } });
417
+ }
165
418
 
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) */
170
- async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
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 ' });
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); });
180
- $('#dashBody').addEventListener('keydown', (e) => {
181
- const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
182
- e.preventDefault(); const c = byKey(t.dataset.key), j = +(t.dataset.j == null ? c.pts.length - 1 : t.dataset.j); chartAt(t, j + (e.key === 'ArrowRight' ? 1 : -1));
419
+ /* the phone (AgInsPhone): one card per goal, its status at the top right, its value, its so-far, its bar and the first initiative that moves it */
420
+ function cardPill(g) {
421
+ const t = g.pace && g.pace.tone !== 'q' ? g.pace.tone : g.tone;
422
+ if (t === 'late' || t === 'red') return ['late', 'Behind'];
423
+ if (t === 'ok') return g.done !== null && g.timeGone != null && g.done > g.timeGone ? ['ok', 'Ahead'] : ['ok', 'On track'];
424
+ return null;
425
+ }
426
+ function drawCards(G) {
427
+ $('#goalCards').innerHTML = G.map((g) => {
428
+ const p = cardPill(g), tg = g.targetTxt ? (g.type === 'Count' ? 'of ' : 'target ') + g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'no target';
429
+ return `<div class="ins-card" role="listitem" data-goal="${esc(g.id)}" tabindex="0" aria-label="${esc(g.title)}"><div class="ins-ch"><b>${esc(g.title)}</b>${p ? `<span class="cz-pill ${p[0]}">${p[1]}</span>` : ''}</div>`
430
+ + `<div class="ins-cs"><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="note">${esc(tg)}</span></div>`
431
+ + `<div class="ins-cv"><b>${esc(g.nowTxt || '—')}</b><span class="ins-cg">${isBlocks(g) ? blocksHtml(g, 190, false) : g.type === 'Stay within' && g.series.length && g.target !== null ? bandSvg(g.series, g.target, g.limit !== 'floor', g.tone, g.title, 190, 30) : g.key ? sparkHtml(g, 190, 30) : ''}</span></div>${barHtml(g, ' ins-wide')}`
432
+ + (g.moves[0] ? `<div class="ins-c1">${initRow(g.moves[0], false)}</div>` : '') + '</div>';
433
+ }).join('') || (M.goals.length ? '<p class="note">No goal in this period.</p>' : '<p class="note">No goal is recorded for this workspace.</p>');
434
+ }
435
+ $('#goalCards').addEventListener('click', (e) => { if (e.target.closest('a')) return; const c = e.target.closest('[data-goal]'); if (c) pressGoal(c.dataset.goal); });
436
+
437
+ /* ── Delivery trends: six compact tiles from the Board's measures (AgInsGoals): a label, the value and a small line with its end dot;
438
+ * a press waits for the target's design. A target is said in the tile's label for a screen reader, not as a line under it. ─────────── */
439
+ const TILES = [['blocked', 'Blocked tickets'], ['late', 'Late initiatives'], ['idle', 'Idle 30+ days'], ['scope', 'Scope added'], ['merges', 'Merged a week'], ['corrections', 'Corrections / 100 runs']];
440
+ function tileOf(key) {
441
+ const TR = M.trends || {}, own = (TR.targets || {})[key];
442
+ if (key === 'late' || key === 'scope') {
443
+ const x = TR[key] || {};
444
+ if (x.value == null) return { v: 'Not read', s: 'the initiatives are not read', abs: true };
445
+ const tg = Number.isFinite(own) ? own : null, sub = (key === 'late' ? 'late today' : 'started this week') + (tg !== null ? ', target ' + tg : '');
446
+ return { v: String(x.value), ser: x.ser || null, s: sub, warn: tg !== null ? x.value > tg : key === 'late' && x.value > 0, tg };
447
+ }
448
+ if (!BM) return { v: bmErr ? 'Not read' : 'Reading', s: '', abs: true };
449
+ const t = (BM.tiles || []).find((x) => x.key === key);
450
+ if (!t) return { v: 'Not read', s: '', abs: true };
451
+ if (t.absent) return { v: t.absent, s: '', abs: true };
452
+ return { v: t.value, ser: t.ser, s: t.targetTxt || '', warn: !!t.look || t.kind === 'warn' || t.kind === 'bad', tg: t.tg != null ? t.tg : null };
453
+ }
454
+ /** A tile's line, as the design draws it: 150 by 18, the weeks from 5 to 145, a soft fill under it and the end dot (orange on a tile to look at). */
455
+ function miniSpark(ser) {
456
+ const S = (ser || []).map((v, j) => [j, v]).filter((p) => p[1] != null); if (S.length < 2) return '<span class="ins-tsp0"></span>';
457
+ const n = ser.length - 1 || 1, vs = S.map((p) => p[1]), lo = Math.min(...vs), hi = Math.max(...vs), rg = hi - lo || 1, W = 150, H = 18;
458
+ const pts = S.map(([j, v]) => (5 + j / n * (W - 10)).toFixed(1) + ',' + (5 + (1 - (v - lo) / rg) * (H - 10)).toFixed(1)), last = pts[pts.length - 1].split(','), first = pts[0].split(',');
459
+ return `<svg class="ins-tsp" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" 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>`;
460
+ }
461
+ function bmHtml() {
462
+ if (!M.board || !M.board.ws) return '';
463
+ return '<section class="ins-trends" id="cBm" aria-labelledby="hBm"><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>'
464
+ + `<div class="ins-tiles" id="bmBody">${TILES.map(([k, l]) => { const t = tileOf(k); return `<div class="ins-tile${t.warn ? ' warn' : ''}${t.abs ? ' abs' : ''}" data-tile="${k}" role="button" tabindex="0" aria-label="${esc(l + ', ' + t.v + (t.s ? ', ' + t.s : ''))}"${t.s ? ` title="${esc(t.s)}"` : ''}><span class="l">${esc(l)}</span><span class="v">${esc(t.v)}</span>${miniSpark(t.ser)}</div>`; }).join('')}</div></section>`;
465
+ }
466
+ async function bmLoad() {
467
+ if (!M || !M.board || !M.board.ws) return;
468
+ let r = null;
469
+ try { const res = await fetch('/api/board-metrics-premium?ws=' + encodeURIComponent(M.board.ws) + '&weeks=8', { credentials: 'same-origin' }); r = await res.json(); } catch { r = null; }
470
+ if (!r || !r.ok || r.state !== 'ready') { BM = null; bmErr = (r && r.error) || '1'; } else { BM = r.model; bmErr = ''; }
471
+ if (tab === 'goals') drawGoals();
472
+ if (BM && BM.pending) setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
473
+ }
474
+
475
+ /* a Delivery trends target: no agreed design, so a plain minimal form in the Viewer card, with the "Waiting for design" marker. The Board's four
476
+ * measures keep their targets in board-metric-targets.jsonl (POST /api/board-metric-targets/save); Late and Scope added in insights-records.jsonl. */
477
+ function openTarget(key) {
478
+ const L = (TILES.find((x) => x[0] === key) || [])[1] || key, t = tileOf(key), mine = key === 'late' || key === 'scope';
479
+ viewer({ kind: 'Delivery trends', title: L, icon: 'chart', render: (el) => {
480
+ el.innerHTML = waitMark('Setting a Delivery trends target') + `<form class="ins-mf" data-tgf><p class="note">Now: <b>${esc(t.v)}</b>${t.s ? ' · ' + esc(t.s) : ''}</p>`
481
+ + `<label class="ins-fl">Target<input class="ins-inp" name="tg" inputmode="decimal" maxlength="12" value="${t.tg != null ? esc(String(t.tg)) : ''}" placeholder="Leave empty for no target"></label>`
482
+ + `<div class="ins-mact"><button type="submit" class="ins-primary">Save target</button><span class="note" data-msg></span></div></form>`;
483
+ el.querySelector('[data-tgf]').addEventListener('submit', async (e) => {
484
+ e.preventDefault(); const v = e.target.tg.value.trim(), msg = el.querySelector('[data-msg]');
485
+ if (v !== '' && !Number.isFinite(Number(v))) { msg.textContent = 'Type a number, or leave it empty.'; return; }
486
+ msg.textContent = 'Saving.';
487
+ const res = mine ? await pmPost('/api/insights-records/target', { ws: M.board.ws, key, target: v === '' ? null : Number(v) })
488
+ : await pmPost('/api/board-metric-targets/save', { ws: M.board.ws, key, target: v === '' ? null : Number(v) });
489
+ if (!res || res.ok !== true) { msg.textContent = (res && res.error) || 'The target could not be saved. Nothing changed.'; return; }
490
+ msg.textContent = 'Saved.'; toast('Saved the target of ' + L + '.'); BM = null; await load(); bmLoad();
491
+ });
492
+ } });
493
+ }
494
+ /** The small "Waiting for design" marker on a part the Agreed design does not draw yet; the part itself still works. */
495
+ const waitMark = (feature) => (typeof window.czPlaceholderHtml === 'function' ? window.czPlaceholderHtml(feature) : `<div class="ins-wmark" role="note">${esc(feature)} · Waiting for design</div>`);
496
+
497
+ /* ── Outcomes (AgInsOutcomes) ───────────────────────────────────────────────────────────────────────────────────────────────────── */
498
+ const sgn = (v, u) => { const r = Math.round(v * 100) / 100, s = r > 0 ? '+' : r < 0 ? '−' : ''; const a = Math.abs(r); return s + (String(u).trim() === '%' ? a + (a === 1 ? ' pt' : ' pts') : a + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : '')); };
499
+ function outcomesShown() {
500
+ /* shipped or judged in the period: a decided row by the day of its verdict, the others by their ship date; one that needs a verdict always shows */
501
+ const when = (r) => (r.verdict && r.verdict.at ? r.verdict.at : r.endAt);
502
+ return (M.outcomes || []).filter((r) => hit(r.title, r.goal && r.goal.title) && (r.group === 'verdict' || when(r) == null || inPer({ fromAt: when(r), byAt: when(r) })));
503
+ }
504
+ function promiseOf(r) {
505
+ const g = r.goal && M.goals.find((x) => x.id === r.goal.id);
506
+ if (!g) return null;
507
+ const moved = g.now !== null && g.base !== null ? g.now - g.base : null, promised = g.target !== null && g.base !== null ? g.target - g.base : null;
508
+ const share = moved !== null && promised ? moved / promised : null;
509
+ const state = share === null ? 'none' : share >= 1 ? 'met' : share > 0 ? 'part' : 'none';
510
+ return { g, moved, promised, share, state };
511
+ }
512
+ /** The promise's bullet: the dashed range is what was promised (baseline to target), the bar is what happened, the tick is the baseline. */
513
+ function bulletHtml(P) {
514
+ const { g, moved, promised } = P, W = 80;
515
+ if (promised === null) return '';
516
+ const span = Math.max(Math.abs(promised), Math.abs(moved || 0)) * 1.15 || 1, neg = promised < 0, z = neg ? W - 10 : 10, sc = (W - 20) / span;
517
+ const exL = neg ? z - Math.abs(promised) * sc : z, exW = Math.abs(promised) * sc;
518
+ const acW = moved === null ? 0 : Math.abs(moved) * sc, acL = (moved || 0) * Math.sign(promised || 1) >= 0 ? (neg ? z - acW : z) : (neg ? z : z - acW);
519
+ const col = P.state === 'met' ? 'var(--cz-dot-ok)' : P.state === 'part' ? 'var(--cz-dot-risk)' : 'var(--cz-dot-q)';
520
+ return `<div class="ins-bul" style="width:${W}px" role="img" aria-label="${esc((moved === null ? 'no reading' : sgn(moved, g.unit)) + ' of ' + sgn(promised, g.unit))}"><span class="ex" style="left:${exL.toFixed(0)}px;width:${exW.toFixed(0)}px"></span><span class="ac" style="left:${acL.toFixed(0)}px;width:${acW.toFixed(0)}px;background:${col}"></span><span class="z" style="left:${z}px"></span></div>`;
521
+ }
522
+ function promiseHtml(r) {
523
+ const P = promiseOf(r);
524
+ if (!P) return `<span class="note">${r.anchor ? 'Anchored to ' + esc(r.anchor) + ', which is not a goal with readings.' : 'No goal is anchored, so nothing was promised to measure.'}</span>`;
525
+ const { g, moved, promised } = P, col = P.state === 'met' ? 'var(--cz-ok)' : P.state === 'part' ? 'var(--cz-risk)' : 'var(--cz-ink3)';
526
+ const text = g.title + (promised !== null ? ' ' + sgn(promised, g.unit) : '') + (g.byAt ? ' by ' + md(day(g.byAt)) : '');
527
+ const res = moved === null ? 'no reading yet' : promised === null ? sgn(moved, g.unit) : moved === 0 ? 'no change' : sgn(moved, g.unit) + ' of ' + sgn(promised, g.unit);
528
+ return `<div class="ins-prom"><span><span class="cz-pill q ins-type">${esc(g.type)}</span></span><span class="pt">${esc(text)}</span><span class="pr">${bulletHtml(P)}<b style="color:${moved === 0 ? 'var(--cz-late)' : col}">${esc(res)}</b></span></div>`;
529
+ }
530
+ /** A guardrail: the goal the PM named as one that must not get worse, read from the last reading before the ship date to the latest one. */
531
+ function guardOf(r) {
532
+ const P = promiseOf(r), name = P && P.g.guardrail ? P.g.guardrail.replace(/ must not get worse$/, '') : '';
533
+ const gg = name ? M.goals.find((x) => x.title === name) : null;
534
+ if (!name) return null;
535
+ if (!gg) return { name, state: 'gone', text: 'its goal is not on record' };
536
+ const ship = day(r.endAt), S = gg.series || [], before = ship === null ? S[0] : S.filter((x) => day(x.at) <= ship).pop(), last = S[S.length - 1];
537
+ if (!before || !last || before === last) return { name, state: 'none', text: 'no reading since it shipped' };
538
+ const d = last.v - before.v, worse = gg.direction === 'down' ? d > 0 : d < 0;
539
+ return { name, state: worse ? 'worse' : 'held', text: (worse ? 'worse by ' : d === 0 ? 'held' : 'held, moved ') + (d === 0 ? '' : sgn(Math.abs(d), gg.unit).replace(/^\+/, '')) };
540
+ }
541
+ /** Guardrail and overlap: the goal's guardrail, then the other initiatives that move the same goal. */
542
+ function guardHtml(r) {
543
+ const P = promiseOf(r), others = P ? P.g.moves.filter((m) => m.id !== r.id) : [], G = guardOf(r);
544
+ return (others.length ? `<span class="cz-pill risk">Shares ${esc(P.g.title.toLowerCase())}</span><div class="note ins-ov">with ${esc(others.map((m) => m.title).join(', '))}</div>` : '')
545
+ + (G ? `<div class="note"><span class="cz-pill ${G.state === 'worse' ? 'late' : G.state === 'held' ? 'ok' : 'q'}">${esc(G.name)}</span> ${esc(G.text)}</div>` : '<div class="note">No guardrail set.</div>');
546
+ }
547
+ /** The window as the design says it: "Judged <date>" while it is open (or not open yet), "Closed <date>" once it has closed. A verdict recorded
548
+ * before the window closed says the day it was judged. A verdict is due when the window closes. */
549
+ const WIN_SAY = { open: (w) => (w.closes ? 'Judged ' + md(day(w.closes)) : 'Open, no end date'), 'not open': (w) => (w.closes ? 'Judged ' + md(day(w.closes)) : 'Opens at ship'), closed: (w) => 'Closed ' + md(day(w.closes)),
550
+ judged: (w, r) => (w.closes && day(w.closes) <= today() ? 'Closed ' + md(day(w.closes)) : 'Judged ' + md(day((r && r.verdict && r.verdict.at) || M.today))), none: () => 'No ship date recorded' };
551
+ const dueOf = (r) => (r && r.window && r.window.closes ? day(r.window.closes) : null);
552
+ const OUT_G = { verdict: 'Needs your verdict', window: 'In their window', decided: 'Decided' };
553
+ function outRow(r) {
554
+ const due = dueOf(r);
555
+ const verdict = r.group === 'verdict' ? `<button type="button" class="ins-dec" data-verdict="${esc(r.id)}" aria-haspopup="dialog">${SV(I.chk)}Decide${due !== null ? ' · due ' + esc(md(due)) : ''}</button>`
556
+ : r.group === 'decided' ? (r.verdict ? `<span class="cz-pill ${r.verdict.verdict === 'Stop' ? 'q' : 'ok'}">${r.verdict.verdict === 'Keep' ? SV(I.chk) + 'Kept' : r.verdict.verdict === 'Iterate' ? 'Iterating' : 'Stopped'}</span><div class="note">${esc(r.verdict.learned)}</div>`
557
+ : (r.status === 'done' ? `<span class="cz-pill ok">${SV(I.chk)}Kept</span>` : '<span class="cz-pill q">Stopped</span>') + '<div class="note">No learning recorded.</div>')
558
+ : `<span class="note">${r.idx === 6 ? (due !== null ? 'Opens ' + esc(md(due)) : 'Being monitored') : 'Too early'}</span>`; // the verdict opens when the window closes
559
+ return `<div class="ins-tr ins-row ins-ocols" role="row" data-ini="${esc(r.id)}"><div class="nm" role="cell"><a href="${iniHref(r.id)}"><b>${esc(r.title)}</b></a>${trackHtml(r)}</div>`
560
+ + `<div role="cell">${promiseHtml(r)}</div><div role="cell" class="ins-guard">${guardHtml(r)}</div>`
561
+ + `<div role="cell">${winHtml(r)}</div><div role="cell">${verdict}</div></div>`;
562
+ }
563
+ function winHtml(r) {
564
+ const w = r.window || { state: 'none' }, sh = w.state === 'judged' || w.state === 'closed' ? 1 : w.share || 0, say = (WIN_SAY[w.state] || WIN_SAY.none)(w, r);
565
+ return `<div class="ins-win" role="img" aria-label="${esc(say)}"><i style="width:${Math.round(sh * 100)}%"></i></div><div class="note">${esc(say)}</div>`;
566
+ }
567
+ function drawOutcomes() {
568
+ const L = outcomesShown(), need = L.filter((r) => r.group === 'verdict');
569
+ const P = L.map(promiseOf).filter(Boolean), met = P.filter((x) => x.state === 'met').length, part = P.filter((x) => x.state === 'part').length, win = L.filter((r) => r.group === 'window' && promiseOf(r)).length;
570
+ $('#outText').innerHTML = !M.initiativesRead ? 'The board’s initiatives are not read yet, so no shipped work is listed.'
571
+ : !L.length ? 'No initiative is past Build yet. Shipped work shows here, with what its goal promised.'
572
+ : (need.length ? `<b>${esc(need[0].title)} needs your verdict${dueOf(need[0]) !== null ? ' by ' + esc(md(dueOf(need[0]))) : ''}.</b> ` : '') + esc('Of ' + P.length + (P.length === 1 ? ' promise ' : ' promises ') + (per.said || 'in these dates') + ', ' + met + (met === 1 ? ' is' : ' are') + ' met, ' + part + (part === 1 ? ' is' : ' are') + ' partly met and ' + win + (win === 1 ? ' is' : ' are') + ' still in their window.');
573
+ const head = '<div class="ins-tr ins-th ins-ocols" role="row"><div role="columnheader">Shipped initiative</div><div role="columnheader">What it promised · and what happened so far</div><div role="columnheader">Guardrail and overlap</div><div role="columnheader">Window</div><div role="columnheader">Verdict</div></div>';
574
+ const groups = Object.keys(OUT_G).map((k) => { const G = L.filter((r) => r.group === k); return G.length ? `<div class="ins-grp" role="row"><span role="cell">${k === 'decided' ? 'Decided ' + esc(per.said || 'in these dates') : OUT_G[k]}</span> <span class="q">${G.length}</span></div>` + G.map(outRow).join('') : ''; }).join('');
575
+ $('#outTbl').innerHTML = head + (groups || '<div class="ins-empty">Nothing to judge yet.</div>');
576
+ }
577
+ $('#outTbl').addEventListener('click', (e) => { const b = e.target.closest('[data-verdict]'); if (b) openVerdict((M.outcomes || []).find((r) => r.id === b.dataset.verdict)); });
578
+
579
+ /* ── the side panel: New goal, New dashboard, Edit chart and the verdict ─────────────────────────────────────────────────────────── */
580
+ let sideKind = null, sideBack = null, SIDE_GO = null;
581
+ function openSide(o) {
582
+ sideKind = o.kind; sideBack = document.activeElement; SIDE_GO = o.onGo || null;
583
+ $('#side').dataset.kind = o.kind;
584
+ $('#sideEye').innerHTML = o.eyeHtml || esc(o.eye || ''); $('#sideTitle').innerHTML = o.titleHtml || esc(o.title || ''); $('#sideTools').innerHTML = o.tools || '';
585
+ $('#sideBody').innerHTML = o.body || ''; $('#sideNote').textContent = o.note || ''; $('#sideMsg').textContent = '';
586
+ $('#sideAct').innerHTML = (o.pre || '') + (o.go ? `<button type="button" class="ins-primary" id="sideGo"${o.goOff ? ` disabled aria-disabled="true" title="${esc(o.goOff)}"` : ''}>${SV(I.chk)}${esc(o.go)}</button>` : '');
587
+ $('#side').hidden = false; document.body.classList.add('ins-sideon');
588
+ $('#sideX').setAttribute('aria-label', o.kind === 'goal' || o.kind === 'dash' ? 'Cancel' : 'Close');
589
+ /* the panel takes focus itself, so no field opens with a focus ring the design does not draw; New goal focuses its name, which has none */
590
+ const f = o.focus ? $(o.focus) : null; if (f) f.focus(); else $('#side').focus({ preventScroll: true });
591
+ }
592
+ function closeSide() {
593
+ $('#side').hidden = true; document.body.classList.remove('ins-sideon'); sideKind = null; SIDE_GO = null;
594
+ if (selecting) { selecting = false; picked = []; drawGoals(); }
595
+ if (sideBack && sideBack.focus && document.contains(sideBack)) sideBack.focus();
596
+ }
597
+ $('#sideX').addEventListener('click', closeSide);
598
+ $('#sideAct').addEventListener('click', (e) => { const b = e.target.closest('#sideGo'); if (b && !b.disabled && SIDE_GO) SIDE_GO(); });
599
+ const seg = (name, opts, on, cls = '') => `<div class="cz-seg${cls}" role="radiogroup" aria-label="${esc(name)}" data-seg="${esc(name)}">${opts.map((o) => `<button type="button" role="radio" aria-checked="${o === on}" aria-pressed="${o === on}" data-v="${esc(o)}">${esc(o)}</button>`).join('')}</div>`;
600
+ const segVal = (name, root = $('#side')) => { const b = root.querySelector(`[data-seg="${name}"] [aria-checked="true"]`); return b ? b.dataset.v : null; };
601
+ const tog = (id, on, label) => `<span class="ins-togw"><button type="button" class="ins-tog${on ? ' on' : ''}" role="switch" aria-checked="${on}" id="${id}" aria-label="${esc(label)}"></button><span>${esc(label)}</span></span>`;
602
+ $('#side').addEventListener('click', (e) => {
603
+ const b = e.target.closest('[data-seg] [data-v]');
604
+ if (b) { for (const x of $$('[data-v]', b.parentElement)) { const on = x === b; x.setAttribute('aria-checked', String(on)); x.setAttribute('aria-pressed', String(on)); } if (sideKind === 'goal') goalHint(); if (sideKind === 'chart') drawChartPreview(); return; }
605
+ const o = e.target.closest('.ins-opt'); if (o) { for (const x of $$('.ins-opt', o.parentElement)) { const on = x === o; x.classList.toggle('on', on); x.setAttribute('aria-checked', String(on)); } return; }
606
+ const t = e.target.closest('.ins-tog'); if (t) { const on = t.getAttribute('aria-checked') !== 'true'; t.setAttribute('aria-checked', String(on)); t.classList.toggle('on', on); if (sideKind === 'chart') drawChartPreview(); if (sideKind === 'goal') goalHint(); return; }
607
+ const c = e.target.closest('[data-src]'); if (c) { for (const x of $$('[data-src]', c.parentElement)) { const on = x === c; x.classList.toggle('on', on); x.setAttribute('aria-pressed', String(on)); } }
608
+ });
609
+
610
+ /* New goal (AgInsNewGoal): its name is the title; type, better is, baseline, target, period, readings, owner and guardrail */
611
+ const GOAL_TYPES = ['Done or not', 'Percentage', 'Count', 'Amount', 'Duration', 'Stay within'];
612
+ function goalPeriods() {
613
+ const P = periods(), t = new Date(today()), y = t.getUTCFullYear(), out = [];
614
+ for (let k = 0; k < 4; k++) { const q = (Math.floor(t.getUTCMonth() / 3) + k) % 4, yy = y + Math.floor((Math.floor(t.getUTCMonth() / 3) + k) / 4); out.push({ kind: 'Quarter', label: 'Q' + (q + 1) + ' ' + yy, by: Date.UTC(yy, q * 3 + 3, 0) }); }
615
+ out.push({ kind: 'Half', label: P[2].label, by: P[2].to }, { kind: 'Half', label: 'H' + (P[2].label[1] === '1' ? '2 ' + y : '1 ' + (y + 1)), by: P[2].label[1] === '1' ? Date.UTC(y, 12, 0) : Date.UTC(y + 1, 6, 0) });
616
+ out.push({ kind: 'Year', label: String(y), by: Date.UTC(y, 12, 0) }, { kind: 'Year', label: String(y + 1), by: Date.UTC(y + 1, 12, 0) });
617
+ return out;
618
+ }
619
+ function openNewGoal() {
620
+ const objs = [...new Set(M.goals.map((g) => g.pillar).filter(Boolean))];
621
+ const GP = goalPeriods(), others = M.goals.map((g) => g.title);
622
+ /* the objective is eyebrow text with a quiet chevron (AgInsNewGoal: "New goal · Objective 1"); its menu names each objective */
623
+ const objSel = `<span class="ins-mw"><button type="button" class="ins-objb" id="ngObjB" aria-haspopup="menu" aria-expanded="false" aria-controls="ngObjMenu" aria-label="Objective: ${objs.length ? 'Objective 1 · ' + esc(objs[0]) : 'No objective'}">${objs.length ? 'Objective 1' : 'No objective'}<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 10l5 5 5-5"/></svg></button>`
624
+ + `<div class="ins-menu" id="ngObjMenu" role="menu" aria-label="Objective" hidden>${objs.map((o, i) => `<button type="button" role="menuitemradio" aria-checked="${i === 0}" data-obj="${esc(o)}" data-said="Objective ${i + 1}">Objective ${i + 1} · ${esc(o)}</button>`).join('')}<button type="button" role="menuitemradio" aria-checked="${!objs.length}" data-obj="" data-said="No objective">No objective</button><button type="button" role="menuitemradio" aria-checked="false" data-obj="+" data-said="A new objective">A new objective…</button></div></span>`
625
+ + `<input type="hidden" id="ngObj" value="${esc(objs[0] || '')}"><input class="ins-inp ins-onew" id="ngObjNew" maxlength="80" placeholder="Name the objective" aria-label="New objective" hidden>`;
626
+ openSide({ kind: 'goal', eyeHtml: 'New goal · ' + objSel, titleHtml: '<input class="ins-tin" id="ngName" maxlength="120" placeholder="Name the goal" aria-label="Goal name">', go: 'Save goal', note: 'Initiatives can anchor to it once it is saved.', onGo: saveGoal, focus: '#ngName',
627
+ body: `<div><p class="ins-fl">Type</p>${seg('Type', GOAL_TYPES, 'Percentage', ' ins-wrap')}</div>`
628
+ + `<div data-for="measured"><p class="ins-fl">Better is</p>${seg('Better is', ['Up', 'Down', 'Exactly the target'], 'Up')}</div>`
629
+ + `<div data-for="within" hidden><p class="ins-fl">The limit is a</p><div class="ins-prow">${seg('Limit', ['Ceiling', 'Floor'], 'Ceiling')}${tog('ngAlways', true, 'Always on, no end date')}</div></div>`
630
+ + `<div class="ins-2" data-for="measured within"><label class="ins-fl"><span data-lab="base">Baseline</span><span class="ins-uf"><input id="ngBase" inputmode="decimal" maxlength="16" placeholder="24"><span class="u" data-unit></span><span class="on">on ${esc(md(today()))}</span></span></label><label class="ins-fl"><span data-lab="tgt">Target</span><span class="ins-uf"><input id="ngTgt" inputmode="decimal" maxlength="16" placeholder="50"><span class="u" data-unit></span></span></label></div>`
631
+ + '<label class="ins-fl" data-for="within" hidden>Unit, optional<input class="ins-inp" id="ngUnit" maxlength="12" placeholder="for example: s, ms, %"></label>'
632
+ + '<label class="ins-fl" data-for="done" hidden>Steps, one a line, optional<textarea class="ins-ta" id="ngSteps" maxlength="1500" placeholder="Scope agreed&#10;Evidence collected&#10;Audit booked"></textarea></label>'
633
+ + `<div data-for="dated"><p class="ins-fl">Period</p><div class="ins-prow">${seg('Period', ['Quarter', 'Half', 'Year', 'Custom'], 'Quarter')}${csel(`<select class="ins-inp" id="ngPer" aria-label="Which period">${GP.filter((p) => p.kind === 'Quarter').map((p) => `<option value="${iso(p.by)}">${esc(p.label)}</option>`).join('')}</select>`, ' ins-psel')}<input class="ins-inp ins-psel" id="ngBy" type="date" aria-label="Due date" hidden></div><div class="note ins-fn" id="ngCp">A yearly goal asks for a checkpoint at the end of each quarter.</div></div>`
634
+ + `<div><p class="ins-fl">Where the readings come from</p><div class="ins-dg"><button type="button" class="cz-chip on" data-src="analytics" aria-pressed="true">${SV(I.chart)}Product analytics</button><button type="button" class="cz-chip" data-src="jira" aria-pressed="false">${SV(I.ext)}Jira query</button><button type="button" class="cz-chip" data-src="file" aria-pressed="false">${SV(I.doc)}A file or export</button><button type="button" class="cz-chip" data-src="typed" aria-pressed="false">You type it in</button></div><div class="note ins-fn">Read every Monday. PMOS never guesses a missing reading.</div></div>`
635
+ + `<div class="ins-2"><label class="ins-fl"><span>Owner</span><input class="ins-inp" id="ngOwner" maxlength="60" placeholder="Who owns it"></label><label class="ins-fl"><span>Guardrail, optional</span>${csel(`<select class="ins-inp" id="ngGuard"><option value="">None</option>${others.map((t) => `<option>${esc(t)} must not get worse</option>`).join('')}</select>`)}</label></div>`
636
+ + '<div class="ins-box note">For <b>Done or not</b> you set a due date and optional steps instead of a baseline. For <b>Stay within</b> you set a floor or ceiling, and there is no end date.</div>' });
637
+ $('#ngObjB').addEventListener('click', (e) => { e.stopPropagation(); const m = $('#ngObjMenu'); m.hidden = !m.hidden; $('#ngObjB').setAttribute('aria-expanded', String(!m.hidden)); if (!m.hidden) { const c = m.querySelector('[aria-checked="true"]'); if (c) c.focus(); } });
638
+ $('#ngObjMenu').addEventListener('click', (e) => {
639
+ const b = e.target.closest('[data-obj]'); if (!b) return; e.stopPropagation();
640
+ for (const x of $$('[data-obj]', $('#ngObjMenu'))) x.setAttribute('aria-checked', String(x === b));
641
+ $('#ngObj').value = b.dataset.obj; $('#ngObjB').firstChild.textContent = b.dataset.said; $('#ngObjB').setAttribute('aria-label', 'Objective: ' + b.textContent);
642
+ $('#ngObjMenu').hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false');
643
+ const n = b.dataset.obj === '+'; $('#ngObjNew').hidden = !n; if (n) $('#ngObjNew').focus(); else $('#ngObjB').focus();
644
+ });
645
+ $('#ngPer').dataset.kind = 'Quarter';
646
+ goalHint();
647
+ }
648
+ /** The form follows its type: a measured goal has Better is, a baseline and a target; Stay within a limit and the reading now; Done or not its steps. */
649
+ function goalHint() {
650
+ const ty = segVal('Type'), kind = ty === 'Done or not' ? 'done' : ty === 'Stay within' ? 'within' : 'measured';
651
+ const always = kind === 'within' && $('#ngAlways') && $('#ngAlways').getAttribute('aria-checked') === 'true';
652
+ for (const x of $$('#sideBody [data-for]')) { const k = x.dataset.for.split(' '); x.hidden = !(k.includes(kind) || (k.includes('dated') && !always)); }
653
+ const lb = $('#sideBody [data-lab="base"]'), lt = $('#sideBody [data-lab="tgt"]'), UNIT = { Percentage: '%', Duration: 'days', Amount: '$' };
654
+ for (const u of $$('#sideBody [data-unit]')) u.textContent = UNIT[ty] || '';
655
+ const on = $('#sideBody .ins-uf .on'); if (on) on.hidden = kind !== 'measured'; // the baseline is read on the day the goal is saved
656
+ if (lb) { lb.textContent = kind === 'within' ? 'Reading now' : 'Baseline'; lt.textContent = kind === 'within' ? 'Limit' : 'Target'; }
657
+ const pk = segVal('Period'), sel = $('#ngPer'), by = $('#ngBy'); if (!sel) return;
658
+ if (pk !== sel.dataset.kind) {
659
+ sel.dataset.kind = pk; sel.closest('.ins-sel').hidden = pk === 'Custom'; by.hidden = pk !== 'Custom';
660
+ if (pk !== 'Custom') sel.innerHTML = goalPeriods().filter((p) => p.kind === pk).map((p) => `<option value="${iso(p.by)}">${esc(p.label)}</option>`).join('');
661
+ }
662
+ $('#ngCp').hidden = kind === 'done';
663
+ }
664
+ async function saveGoal() {
665
+ const v = (id) => $(id).value.trim(), m = $('#sideMsg'), ty = segVal('Type'), pk = segVal('Period');
666
+ const obj = $('#ngObj').value === '+' ? v('#ngObjNew') : $('#ngObj').value;
667
+ if (!v('#ngName')) { m.textContent = 'Give the goal a name.'; $('#ngName').focus(); return; }
668
+ const always = ty === 'Stay within' && $('#ngAlways').getAttribute('aria-checked') === 'true';
669
+ const src = $('#sideBody [data-src][aria-pressed="true"]');
670
+ const body = { ws: M.board.ws, name: v('#ngName'), type: ty, direction: segVal('Better is'), baseline: v('#ngBase'), target: v('#ngTgt'),
671
+ due: pk === 'Custom' ? v('#ngBy') : $('#ngPer').value, period_kind: always ? null : pk, period_label: pk === 'Custom' ? 'Custom' : ($('#ngPer').selectedOptions[0] || {}).textContent || pk,
672
+ objective: obj || '', source: src ? src.dataset.src : '', owner: v('#ngOwner'), guardrail: $('#ngGuard').value,
673
+ steps: ty === 'Done or not' ? $('#ngSteps').value.split('\n').map((x) => x.trim()).filter(Boolean) : undefined,
674
+ limit: ty === 'Stay within' ? (segVal('Limit') === 'Floor' ? 'floor' : 'ceiling') : undefined, unit: ty === 'Stay within' ? v('#ngUnit') : undefined, always_on: always };
675
+ $('#sideGo').disabled = true; m.textContent = 'Saving.';
676
+ const res = await pmPost('/api/insights-records/goal', body);
677
+ $('#sideGo').disabled = false;
678
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The goal could not be saved. Nothing changed.'; return; }
679
+ closeSide(); toast('Saved ' + body.name + '. It shows on All goals' + (ty === 'Done or not' || ty === 'Stay within' ? '.' : '; its line is drawn after two readings.')); await load();
680
+ if (curDash().id !== 'all') setView('all'); // a saved dashboard does not hold the new goal, so show every goal
681
+ }
682
+
683
+ /* New dashboard (AgInsNewDash): pick goals in the table; each chart's form, the order (drag), Range and Pin */
684
+ const FORMS = ['Line', 'Bars', 'Number', 'Meter'];
685
+ const formOf = {}; // the form picked for each goal while the panel is open (no route keeps it yet)
686
+ function openNewDash() {
687
+ if (!M.board.id) { toast('A dashboard is saved on a board, and this workspace has none.'); return; }
688
+ selecting = true; picked = []; setTab('goals'); if (curDash().saved) dash = 'all'; drawGoals();
689
+ openSide({ kind: 'dash', eye: 'New dashboard · a saved view of Goals', title: 'New dashboard', go: 'Save dashboard', note: 'Saved in this workspace. It shows under View and in Library.', onGo: saveNewDash, body: '' });
690
+ drawDashSide();
691
+ }
692
+ function drawDashSide() {
693
+ if (sideKind !== 'dash') return;
694
+ const keep = { n: ($('#ndName') || {}).value || '', q: ($('#ndQ') || {}).value || '', pin: $('#ndPin') ? $('#ndPin').getAttribute('aria-checked') === 'true' : false, r: segVal('Range') || 'Quarter', msg: ($('#ndMsg') || {}).textContent || '' };
695
+ const L = picked.map((id) => M.goals.find((g) => g.id === id)).filter(Boolean), rest = M.goals.filter((g) => !picked.includes(g.id));
696
+ $('#sideTitle').textContent = keep.n || 'New dashboard';
697
+ $('#sideBody').innerHTML = `<form class="ins-desc" id="ndAsk"><span class="sp">${SV(I.spark)}</span><input id="ndAskIn" maxlength="300" placeholder="Or describe it, and PMOS fills this in" aria-label="Describe the dashboard"><button type="submit" class="cz-ib solid sm" aria-label="Fill it in from the description" title="Fill it in">${SV(I.up)}</button></form>`
698
+ + `<p class="note ins-dmsg" id="ndMsg" role="status"${keep.msg ? '' : ' hidden'}>${esc(keep.msg)}</p>`
699
+ + `<label class="ins-fl">Name<input class="ins-inp" id="ndName" maxlength="60" value="${esc(keep.n)}" placeholder="For example: Partner first week"></label>`
700
+ + `<label class="ins-fl">The question it answers<input class="ins-inp" id="ndQ" maxlength="200" value="${esc(keep.q)}" placeholder="Are new partners getting value in their first week?"></label>`
701
+ + `<div><p class="ins-fl">Charts <span class="q">${L.length} picked on the left · drag to order</span></p>`
702
+ + (L.length ? `<div class="ins-picked" id="ndList">${L.map((g) => `<div class="ins-pk" draggable="true" tabindex="0" aria-label="${esc(g.title)}: Alt and the arrow keys move it, Delete takes it off" data-pk="${esc(g.id)}"><span class="ins-grip" aria-hidden="true">⋮⋮</span><b>${esc(g.title)}</b>${seg('Form of ' + g.title, FORMS, formOf[g.id] || 'Line')}</div>`).join('')}</div>` : '<p class="note">Press goals in the table to add them.</p>')
703
+ + (rest.length ? `<button type="button" class="cz-chip gh ins-addg" id="ndAdd">${SV(I.plus)}Add a goal that is not on Goals</button><select class="ins-inp" id="ndAddSel" aria-label="Add a goal" hidden><option value="">Pick a goal</option>${rest.map((g) => `<option value="${esc(g.id)}">${esc(g.title)}</option>`).join('')}</select>` : '') + '</div>'
704
+ + `<div class="ins-rrow"><div><p class="ins-fl">Range</p>${seg('Range', ['8w', 'Quarter', '26w'], keep.r)}</div>${tog('ndPin', keep.pin, 'Pin, so it opens first')}</div>`;
705
+ $('#ndAsk').addEventListener('submit', async (e) => {
706
+ e.preventDefault(); const t = $('#ndAskIn').value.trim(), m = $('#ndMsg'); m.hidden = false; // the describe message is said under the box, not in the footer
707
+ if (!t) { m.textContent = 'Describe the dashboard in a few words.'; $('#ndAskIn').focus(); return; }
708
+ m.textContent = 'Filling it in.';
709
+ const r = await pmPost('/api/insights-records/describe', { ws: M.board.ws, text: t });
710
+ if (!r || r.ok !== true) { m.textContent = (r && r.error) || 'It could not be filled in. Nothing changed.'; return; }
711
+ picked = [...new Set(picked.concat(r.goals))]; drawGoals();
712
+ $('#ndName').value = $('#ndName').value.trim() || r.name; if (r.question && !$('#ndQ').value.trim()) $('#ndQ').value = r.question;
713
+ const keepR = r.range; drawDashSide(); const rb = $(`#sideBody [data-seg="Range"] [data-v="${keepR}"]`); if (rb) rb.click();
714
+ $('#ndMsg').hidden = false; $('#ndMsg').textContent = r.goals.length ? 'Filled in from your words: ' + r.said.join(', ') + '. Check it, then save.' : 'No goal is named in that description, so none is picked. The name and question are filled in.';
715
+ });
716
+ $('#ndName').addEventListener('input', () => { $('#sideTitle').textContent = $('#ndName').value.trim() || 'New dashboard'; });
717
+ const add = $('#ndAdd'); if (add) add.onclick = () => { add.hidden = true; $('#ndAddSel').hidden = false; $('#ndAddSel').focus(); };
718
+ const sel = $('#ndAddSel'); if (sel) sel.onchange = () => { if (sel.value) { picked = picked.concat(sel.value); drawGoals(); drawDashSide(); } };
719
+ }
720
+ /* a chart comes off the list by pressing its row in the table again (pressGoal), or with Delete on its row here */
721
+ $('#sideBody').addEventListener('click', (e) => { const f = e.target.closest('.ins-pk [data-v]'); if (f) formOf[f.closest('[data-pk]').dataset.pk] = f.dataset.v; });
722
+ /* drag to order (and Alt+Arrow keys on a row of the list) */
723
+ let dragId = null;
724
+ $('#sideBody').addEventListener('dragstart', (e) => { const r = e.target.closest && e.target.closest('[data-pk]'); if (!r) return; dragId = r.dataset.pk; try { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', dragId); } catch { /* no data */ } });
725
+ $('#sideBody').addEventListener('dragover', (e) => { if (dragId && e.target.closest('[data-pk]')) e.preventDefault(); });
726
+ $('#sideBody').addEventListener('drop', (e) => {
727
+ const r = e.target.closest('[data-pk]'); if (!dragId || !r) return; e.preventDefault();
728
+ const to = r.dataset.pk; if (to !== dragId) { const L = picked.filter((x) => x !== dragId); L.splice(L.indexOf(to) + (picked.indexOf(dragId) < picked.indexOf(to) ? 1 : 0), 0, dragId); picked = L; drawGoals(); drawDashSide(); }
729
+ dragId = null;
183
730
  });
184
- $('#dashBody').addEventListener('pointermove', (e) => {
185
- const t = e.target.closest && e.target.closest('.mch'); $$('#dashBody .mch.hv').forEach((x) => { if (x !== t) chartAt(x); });
186
- if (!t) return; const c = byKey(t.dataset.key), r = $('svg', t).getBoundingClientRect(); if (!c || !r.width) return;
187
- const fx = Math.max(0, Math.min(1, ((e.clientX - r.left) / r.width * W - P) / (W - 2 * P)));
188
- let best = 0; c.pts.forEach((p, i) => { if (Math.abs(p.fx - fx) < Math.abs(c.pts[best].fx - fx)) best = i; }); chartAt(t, best);
731
+ $('#sideBody').addEventListener('keydown', (e) => {
732
+ const r = e.target.closest && e.target.closest('[data-pk]'); if (!r) return;
733
+ if ((e.key === 'Delete' || e.key === 'Backspace') && e.target === r) { e.preventDefault(); picked = picked.filter((x) => x !== r.dataset.pk); drawGoals(); drawDashSide(); return; }
734
+ if (!e.altKey || !/^Arrow(Up|Down)$/.test(e.key)) return;
735
+ e.preventDefault(); const i = picked.indexOf(r.dataset.pk), j = i + (e.key === 'ArrowUp' ? -1 : 1); if (j < 0 || j >= picked.length) return;
736
+ const L = picked.slice(); [L[i], L[j]] = [L[j], L[i]]; picked = L; drawGoals(); drawDashSide();
189
737
  });
190
- $('#dashBody').addEventListener('pointerleave', () => $$('#dashBody .mch.hv').forEach((x) => chartAt(x)));
738
+ async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
739
+ async function saveNewDash() {
740
+ const m = $('#sideMsg'), name = $('#ndName').value.trim(), purpose = $('#ndQ').value.trim();
741
+ if (!name) { m.textContent = 'Give the dashboard a name.'; $('#ndName').focus(); return; }
742
+ if (!purpose) { m.textContent = 'Say the question it answers, in one line.'; $('#ndQ').focus(); return; }
743
+ if (!picked.length) { m.textContent = 'Select at least one goal in the table.'; return; }
744
+ $('#sideGo').disabled = true; m.textContent = 'Saving.';
745
+ const pin = $('#ndPin').getAttribute('aria-checked') === 'true';
746
+ const res = await pmPost('/api/insights-records/dashboard', { ws: M.board.ws, board: M.board.id, name, purpose, charts: picked.map((g) => ({ goal: g, form: formOf[g] || 'Line' })), range: segVal('Range') || 'Quarter', pin });
747
+ $('#sideGo').disabled = false;
748
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The dashboard could not be saved. Nothing changed.'; return; }
749
+ closeSide(); toast('Saved ' + name + (res.pinned ? '. Pinned: it opens first on Goals.' : '. It shows under View and in Library.'));
750
+ await load();
751
+ if (res.id && M.dashboards.some((d) => d.id === res.id)) setView(res.id);
752
+ }
191
753
 
192
- /* ── the list: dashboards, then reports, filtered and paged (insights-one-list L5, L6) ──────────────────────────── */
193
- let askTimer = 0;
194
- const dismissing = new Map(); // finding id → timer: "Not a report" waits 5 s for an Undo before it is sent
195
- const ASKST = { running: ['Working', 'draft'], ready: ['Ready to review', 'issued'], failed: ['Failed', 'none'] };
196
- const insLine = (t, q) => `<span class="nil${q ? ' q' : ''}">${ICO(AIC)}<span>${esc(t)}</span></span>`;
197
- function dashRow(D) {
198
- const I = D.insight || {}, f = I.finds && I.finds[0], on = M.pinned === D.id, shown = curDash().id === D.id && !$('#cDash').hidden;
199
- const line = I.none ? '' : insLine(f ? f.text : I.calmText);
200
- const meta = `<span class="t">Dashboard</span>${on ? '<span class="s issued">Pinned</span>' : ''}${shown ? '<span>Shown above</span>' : ''}<span>${D.total} ${D.total === 1 ? 'chart' : 'charts'}</span>${D.off ? `<span class="s none">${D.off} behind</span>` : D.total ? '<span>All on their line</span>' : ''}`;
201
- return `<div class="dmr" role="listitem"><button class="dmo" data-d="${esc(D.id)}"><span class="dmi c-Dash">${ICO(DASHI)}</span><span class="dmn"><b>${esc(D.name)}</b>${line || `<small>${esc(I.none ? 'No chart is drawn on it yet.' : '')}</small>`}<span class="dmm">${meta}</span></span></button>`
202
- + (pinnable(D) ? `<button class="npin" data-pin="${esc(D.id)}" aria-pressed="${on}" aria-label="${on ? 'Unpin' : 'Pin'} ${esc(D.name)}" title="${on ? 'Unpin' : 'Pin to the top of Insights'}">${ICO(PINI)}</button>` : '') + '</div>';
203
- }
204
- /* A report row's insight is the opening sentence of its latest file, marked as quoted from it. With no file it says no draft is written yet. */
205
- function setupRow(s) {
206
- const L = s.latest, line = L && L.lead ? insLine('“' + L.lead + '”', true) : '';
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';
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>`;
209
- }
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 live = g.files.filter((x) => !x.archived), L = live[0], n = (f) => live.filter(f).length, d = n((x) => x.state !== 'issued'), i = n((x) => x.state === 'issued'), s = g.setup;
215
- const pills = [d ? `<span class="s draft">${d} draft</span>` : '', i ? `<span class="s issued">${i} issued</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). Archived cycles are hidden (PM
221
- * 2026-10-22: "Archived report should be hidden"): a report whose cycles are all archived has no row (a set-up one keeps its set-up row), and
222
- * its archived cycles stay reachable from the reader's cycle chip. */
754
+ /* Edit chart (AgInsChart): one goal drawn one way on a dashboard. The route keeps which goals a dashboard holds and their order; the form, range,
755
+ * comparison, target line, forecast and note are drawn here and not saved yet. */
756
+ let chartDash = null;
757
+ function chartHost(D) { return D && D.saved ? D : savedDash().find((d) => d.id === M.pinned) || savedDash()[0] || null; }
758
+ function openChartEdit(goalId, D0) {
759
+ const D = chartHost(D0 || curDash()); chartDash = D;
760
+ const g = M.goals.find((x) => x.id === goalId) || M.goals.find((x) => x.key) || M.goals[0];
761
+ if (!g) { toast('There is no goal to chart yet. Add one with New goal.'); return; }
762
+ const on = D && D.charts.includes(g.id), cs = (D && (M.chartSet || {})[D.id] || {})[g.id] || {};
763
+ openSide({ kind: 'chart', eye: D ? 'Chart on ' + D.name : 'Chart · no dashboard yet', title: g.title, go: 'Save chart', onGo: saveChart,
764
+ goOff: !D ? 'Make a dashboard first, with New dashboard' : '',
765
+ note: D ? 'Changes this dashboard only. The goal and its readings are not changed.' : 'A chart lives on a dashboard. Make one first with New dashboard.',
766
+ tools: `<span class="ins-mw"><button type="button" class="cz-ib" id="chMore" aria-haspopup="menu" aria-expanded="false" aria-controls="chMenu" aria-label="More: duplicate, remove from dashboard" title="More: duplicate, remove from dashboard">${SV(I.more, 3)}</button><div class="ins-menu ins-right" id="chMenu" role="menu" hidden><button type="button" role="menuitem" disabled aria-disabled="true">Duplicate<small>A dashboard holds one chart for each goal</small></button><button type="button" role="menuitem" id="chRemove"${on ? '' : ' disabled aria-disabled="true"'}>Remove from dashboard<small>${on ? 'Takes this goal off ' + esc(D.name) : 'It is not on this dashboard'}</small></button></div></span>`,
767
+ body: '<div class="ins-prev" id="chPrev"></div>'
768
+ + `<label class="ins-fl">Goal${csel(`<select class="ins-inp" id="chGoal">${M.goals.map((x) => `<option value="${esc(x.id)}"${x.id === g.id ? ' selected' : ''}>${esc(x.title + (krId(x) ? ' · ' + krId(x) : ''))}</option>`).join('')}</select>`)}</label>`
769
+ + `<div><p class="ins-fl">Form</p>${seg('Form', FORMS, cs.form || formOf[g.id] || 'Line')}<div class="note ins-fn">Bars and a meter start at zero. A goal that goes below zero is drawn as a line.</div></div>`
770
+ + `<div class="ins-2"><div><p class="ins-fl">Range</p>${seg('Range', ['8w', 'Quarter', '26w'], cs.range || '26w')}</div><label class="ins-fl"><span>Compare with</span>${csel(`<select class="ins-inp" id="chCmp"><option value="lq"${cs.compare === '' ? '' : ' selected'}>Last quarter</option><option value=""${cs.compare === '' ? ' selected' : ''}>Nothing</option></select>`)}</label></div>`
771
+ + `<div class="ins-togs">${tog('chTgt', cs.target !== false, 'Target line')}${tog('chFc', cs.forecast === true, 'Forecast to its date')}</div>`
772
+ + `<label class="ins-fl"><span>Note under the chart</span><input class="ins-inp" id="chNote" maxlength="160" value="${esc(cs.note || '')}" placeholder="For example: the dip on Oct 15 is an outage"></label>` });
773
+ $('#chGoal').addEventListener('change', () => { $('#sideTitle').textContent = (M.goals.find((x) => x.id === $('#chGoal').value) || {}).title || ''; drawChartPreview(); });
774
+ $('#chCmp').addEventListener('change', drawChartPreview);
775
+ $('#chMore').addEventListener('click', (e) => { e.stopPropagation(); const mm = $('#chMenu'); mm.hidden = !mm.hidden; $('#chMore').setAttribute('aria-expanded', String(!mm.hidden)); });
776
+ $('#chMenu').addEventListener('click', async (e) => {
777
+ const b = e.target.closest('#chRemove'); if (!b || b.disabled || !D) return;
778
+ const id = $('#chGoal').value, res = await saveDash({ id: D.id, name: D.name, purpose: D.purpose, charts: D.charts.filter((x) => x !== id), main: D.main });
779
+ if (!res || res.ok !== true) { $('#sideMsg').textContent = (res && res.error) || 'The dashboard could not be saved. Nothing changed.'; return; }
780
+ closeSide(); toast('Took it off ' + D.name + '.'); await load();
781
+ });
782
+ drawChartPreview();
783
+ }
784
+ const RANGE_DAYS = { '8w': 56, '26w': 182 };
785
+ function drawChartPreview() {
786
+ const box = $('#chPrev'); if (!box) return;
787
+ const g = M.goals.find((x) => x.id === $('#chGoal').value), c = g && g.key ? byKey(g.key) : null, form = segVal('Form'), rg = segVal('Range'), cmp = $('#chCmp').value;
788
+ const t = today(), P = periods(), from = rg === 'Quarter' ? P[0].from : t - RANGE_DAYS[rg] * DAY;
789
+ const head = g ? `<div class="ins-ph"><b>${esc(g.nowTxt || '—')}</b><span class="note">${esc((g.targetTxt ? 'target ' + g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'no target') + (cmp && c ? ' · light ' + (form === 'Bars' ? 'bars' : 'line') + ' is last quarter' : ''))}</span></div>` : '';
790
+ if (!c) { box.innerHTML = head + `<p class="note ins-pe">${esc(g && g.readings ? 'One reading, no series yet, so nothing is drawn.' : 'No reading yet, so nothing is drawn.')}</p>`; return; }
791
+ const pts = c.pts.filter((p) => day(p.at) >= from), prev = cmp ? c.pts.filter((p) => day(p.at) >= P[1].from && day(p.at) <= P[1].to) : [];
792
+ box.innerHTML = head + (pts.length ? chartSvg({ pts, prev, form, target: $('#chTgt').getAttribute('aria-checked') === 'true' ? g.target : null, proj: $('#chFc').getAttribute('aria-checked') === 'true' && g.proj ? { at: g.byAt, v: g.proj.atDue } : null, tone: g.tone })
793
+ + `<div class="ins-px note"><span>${esc(md(day(pts[0].at)))}</span><span>${esc(md(day(pts[pts.length - 1].at)))}</span></div>` : '<p class="note ins-pe">No reading falls in this range.</p>');
794
+ }
795
+ /** One goal's readings drawn as a line, bars, a number or a meter. Values are readings at their dates; nothing is filled in between. */
796
+ function chartSvg(o) {
797
+ const W = 500, H = 140, Pd = 8, all = o.pts.concat(o.prev || []);
798
+ if (o.form === 'Number') { const l = o.pts[o.pts.length - 1]; return `<div class="ins-num"><b>${esc(l.txt)}</b><span class="note">on ${esc(md(day(l.at)))}</span></div>`; }
799
+ const vs = all.map((p) => p.v).concat(o.target != null ? [o.target] : [], o.proj ? [o.proj.v] : []), neg = vs.some((v) => v < 0);
800
+ const form = (o.form === 'Bars' || o.form === 'Meter') && neg ? 'Line' : o.form;
801
+ if (form === 'Meter') {
802
+ const l = o.pts[o.pts.length - 1], mx = Math.max(o.target || 0, l.v) || 1;
803
+ return `<div class="ins-meter" role="img" aria-label="${esc(l.txt + (o.target != null ? ' of ' + o.target : ''))}"><i style="width:${Math.round(l.v / mx * 100)}%;background:${TONE_BAR[o.tone] || TONE_BAR.q}"></i>${o.target != null ? `<span class="tg" style="left:${Math.round(o.target / mx * 100)}%"></span>` : ''}</div>`;
804
+ }
805
+ const lo = form === 'Bars' ? 0 : Math.min(...vs), hi = Math.max(...vs), rg = hi - lo || 1, y = (v) => Pd + (1 - (v - lo) / rg) * (H - 2 * Pd);
806
+ const t0 = day(o.pts[0].at), t1 = Math.max(day(o.pts[o.pts.length - 1].at), o.proj ? day(o.proj.at) : 0), x = (t) => Pd + (t1 > t0 ? (t - t0) / (t1 - t0) : 0.5) * (W - 2 * Pd);
807
+ const tgt = o.target != null ? `<line class="tg" x1="0" x2="${W}" y1="${y(o.target).toFixed(1)}" y2="${y(o.target).toFixed(1)}"/>` : '';
808
+ if (form === 'Bars') {
809
+ const n = o.pts.length + (o.prev || []).length, bw = Math.max(6, Math.min(26, (W - 2 * Pd) / Math.max(1, n) - 8)), L = (o.prev || []).map((p) => [p, 'pv']).concat(o.pts.map((p) => [p, 'cu']));
810
+ return `<svg class="ins-ch2" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(o.pts.length + ' readings as bars')}">${tgt}${L.map(([p, k], i) => { const bx = Pd + i * ((W - 2 * Pd) / Math.max(1, n)); return `<rect class="${k}" x="${bx.toFixed(1)}" y="${y(p.v).toFixed(1)}" width="${bw.toFixed(1)}" height="${(H - Pd - y(p.v)).toFixed(1)}" rx="3"/>`; }).join('')}</svg>`;
811
+ }
812
+ const line = o.pts.map((p) => x(day(p.at)).toFixed(1) + ',' + y(p.v).toFixed(1)), last = line[line.length - 1].split(',');
813
+ const pv = (o.prev || []).length > 1 ? `<polyline class="pv" points="${o.prev.map((p, i) => (Pd + i / (o.prev.length - 1) * (W - 2 * Pd)).toFixed(1) + ',' + y(p.v).toFixed(1)).join(' ')}"/>` : '';
814
+ const pj = o.proj ? `<polyline class="pj" points="${last.join(',')} ${x(day(o.proj.at)).toFixed(1)},${y(o.proj.v).toFixed(1)}"/>` : '';
815
+ const ship = o.ship != null && o.ship >= t0 && o.ship <= t1 ? `<line class="ship" x1="${x(o.ship).toFixed(1)}" x2="${x(o.ship).toFixed(1)}" y1="0" y2="${H}"/><circle class="shipd" cx="${x(o.ship).toFixed(1)}" cy="3" r="3"/>` : '';
816
+ return `<svg class="ins-ch2" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(o.pts.length + ' readings as a line')}">${tgt}${pv}<polygon class="ar" points="${line[0].split(',')[0]},${H} ${line.join(' ')} ${last[0]},${H}"/>${pj}<polyline class="ln" points="${line.join(' ')}"/>${ship}<circle class="dt" cx="${last[0]}" cy="${last[1]}" r="3.6" style="fill:${TONE_BAR[o.tone] || TONE_BAR.q}"/></svg>`;
817
+ }
818
+ async function saveChart() {
819
+ const D = chartDash, id = $('#chGoal').value, m = $('#sideMsg'); if (!D) return;
820
+ $('#sideGo').disabled = true; m.textContent = 'Saving.';
821
+ const res = await pmPost('/api/insights-records/chart', { ws: M.board.ws, board: M.board.id, dash: D.id, goal: id, form: segVal('Form'), range: segVal('Range'), compare: $('#chCmp').value,
822
+ target: $('#chTgt').getAttribute('aria-checked') === 'true', forecast: $('#chFc').getAttribute('aria-checked') === 'true', note: $('#chNote').value.trim(), add: !D.charts.includes(id) });
823
+ $('#sideGo').disabled = false;
824
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The chart could not be saved. Nothing changed.'; return; }
825
+ closeSide(); toast((D.charts.includes(id) ? 'Saved the chart on ' : 'Added to ') + D.name + '.'); await load();
826
+ }
827
+
828
+ /* the verdict (AgInsVerdict): the goal with the ship date marked, what was promised, evidence, and Keep, Iterate or Stop. No route records a verdict
829
+ * yet, so Record verdict is not available; Home is one press away to ask about it. */
830
+ function openVerdict(r) {
831
+ if (!r) return;
832
+ const P = promiseOf(r), g = P && P.g, c = g && g.key ? byKey(g.key) : null, ship = day(r.endAt);
833
+ const chart = !g ? '<p class="note">No goal with readings is anchored to it, so there is nothing measured to judge against. Judge it on what you saw.</p>'
834
+ : `<div><p class="ins-fl">${esc(g.title)} <span class="q">${krId(g) ? esc(krId(g)) + ' · ' : ''}${ship !== null ? 'blue mark is the ship date' : 'no ship date recorded'}</span></p>${c ? chartSvg({ pts: c.pts, form: 'Line', target: g.target, ship, tone: g.tone }) + `<div class="ins-px note"><span>${esc(md(day(c.pts[0].at)))}</span>${ship !== null ? `<span>shipped ${esc(md(ship))}</span>` : ''}<span>${esc(md(day(c.pts[c.pts.length - 1].at)))}</span></div>` : `<p class="note ins-pe">${esc(g.readings ? 'One reading, no series yet, so nothing is drawn.' : 'No reading yet, so nothing is drawn.')}</p>`}</div>`
835
+ + `<div class="ins-kv3"><span><small>Promised</small><b>${esc(P.promised !== null ? sgn(P.promised, g.unit) : '—')}</b></span><span><small>So far</small><b style="color:${P.state === 'met' ? 'var(--cz-ok)' : P.state === 'part' ? 'var(--cz-risk)' : 'var(--cz-ink3)'}">${esc(P.moved !== null ? sgn(P.moved, g.unit) : 'no reading')}</b></span><span><small>Guardrail</small><b class="${guardOf(r) ? '' : 'q'}">${esc(guardOf(r) ? guardOf(r).name + ': ' + guardOf(r).text : 'none set')}</b></span></div>`;
836
+ const due = dueOf(r);
837
+ openSide({ kind: 'verdict', eye: 'Evaluate · your verdict' + (due !== null ? ', due ' + md(due) : ''), title: r.title, go: 'Record verdict', onGo: () => saveVerdict(r),
838
+ note: 'Records the evaluation. Nothing is sent.',
839
+ pre: `<a class="cz-ib sm" href="${esc(homeAsk('verdict', 'Help me judge ' + r.title + ' (' + r.id + ').'))}" aria-label="Ask about this verdict in Home" title="Ask about this verdict in Home">${SV(I.home)}</a>`,
840
+ tools: `<a class="cz-ib" href="${iniHref(r.id)}" aria-label="Open the PRD" title="Open the PRD">${SV(I.doc)}</a><a class="cz-ib" href="/premium-board.html?${wsQ()}focus=${encodeURIComponent(r.id)}" aria-label="Open on the Board" title="Open on the Board">${SV(I.next)}</a>`,
841
+ body: chart
842
+ + `<div><p class="ins-fl">Evidence <span class="q">${(r.evidence || []).length}</span></p>${(r.evidence || []).length ? `<ul class="ins-ev">${r.evidence.map((x) => `<li>${esc(x)}</li>`).join('')}</ul>` : `<p class="note">${g ? 'No reading of ' + esc(g.title) + ' is recorded.' : 'No goal with readings is anchored to it.'}</p>`}</div>`
843
+ + '<div><p class="ins-fl">Your verdict</p><div class="ins-opts" role="radiogroup" aria-label="Your verdict">'
844
+ + [['Keep', 'It stays as built. Move it to Done on the Board.'], ['Iterate', 'Keep it, and start a linked initiative in Triage for the next step.'], ['Stop', 'Archive it and say why. The code stays until a chore removes it.']]
845
+ .map(([k, t], i) => `<button type="button" class="ins-opt${i === 1 ? ' on' : ''}" role="radio" aria-checked="${i === 1}" data-vd="${k}"><i class="rd"></i><span><b>${k}</b><small>${esc(t)}</small></span></button>`).join('') + '</div></div>'
846
+ + '<label class="ins-fl">What we learned<textarea class="ins-ta" id="vdLearn" maxlength="600" placeholder="What the numbers and the work say"></textarea></label>' });
847
+ $('#sideMsg').textContent = '';
848
+ }
849
+ async function saveVerdict(r) {
850
+ const m = $('#sideMsg'), o = $('#sideBody .ins-opt[aria-checked="true"]'), learned = $('#vdLearn').value.trim();
851
+ if (!learned) { m.textContent = 'Say what you learned, in a line.'; $('#vdLearn').focus(); return; }
852
+ $('#sideGo').disabled = true; m.textContent = 'Saving.';
853
+ const res = await pmPost('/api/insights-records/verdict', { ws: M.board.ws, board: M.board.id, ini: r.id, verdict: o ? o.dataset.vd : 'Iterate', learned, goal: r.goal ? r.goal.id : null });
854
+ $('#sideGo').disabled = false;
855
+ if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The verdict could not be saved. Nothing changed.'; return; }
856
+ closeSide(); toast('Recorded: ' + (o ? o.dataset.vd : 'Iterate') + ' for ' + r.title + '.'); await load();
857
+ }
858
+
859
+ /* the + menu */
860
+ $('#newMenu').addEventListener('click', (e) => {
861
+ const b = e.target.closest('[data-new]'); if (!b) return; closeMenus();
862
+ if (b.dataset.new === 'goal') openNewGoal();
863
+ else if (b.dataset.new === 'dash') openNewDash();
864
+ else { const D = curDash(), first = goalsShown().find((g) => g.key) || M.goals[0]; openChartEdit(first ? first.id : null, D); }
865
+ });
866
+
867
+ /* ── Library (AgInsLibrary): reports, then dashboards ───────────────────────────────────────────────────────────────────────────── */
223
868
  function reportGroups() {
224
869
  const R = M.reports, by = new Map();
225
870
  for (const f of R.missing ? [] : R.rows) { if (!by.has(f.cadence)) by.set(f.cadence, []); by.get(f.cadence).push(f); }
226
- const out = [];
227
- const shown = (fs) => fs && fs.some((x) => !x.archived);
871
+ const out = [], shown = (fs) => fs && fs.some((x) => !x.archived);
228
872
  for (const s of R.setupsOk === false ? [] : (R.setups || [])) { const fs = by.get(s.id); by.delete(s.id); out.push(shown(fs) ? { kind: 'file', x: { id: s.id, name: s.name, setup: s, files: fs } } : { kind: 'setup', x: s }); }
229
873
  for (const [id, fs] of by) if (shown(fs)) out.push({ kind: 'file', x: { id, name: id, setup: null, files: fs } });
230
874
  return out;
231
875
  }
232
- 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>`;
233
- 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>`;
234
- function listItems() {
235
- const d = M.dashboards.map((x) => ({ kind: 'dash', x }));
236
- const r = reportGroups();
237
- return { d, r, all: d.concat(r) };
876
+ const cycDots = (states) => `<span class="ins-dots" aria-hidden="true">${states.map((k) => `<i class="${k}"></i>`).join('')}</span>`;
877
+ const fromChips = (s) => { const L = (s && s.source ? [s.source === 'work' ? 'Your work' : s.source] : []).concat(s && s.builtFrom ? s.builtFrom.map((x) => { const g = M.goals.find((y) => y.id === x); return g ? g.title : x; }) : []);
878
+ return L.length ? L.slice(0, 3).map((x) => `<span class="cz-pill q">${esc(x)}</span>`).join(' ') + (L.length > 3 ? ` <span class="note">+${L.length - 3}</span>` : '') : '<span class="note">Not recorded</span>'; };
879
+ const lrow = (attr, name, sub, when, st, from, act) => `<div class="ins-tr ins-row ins-lcols" role="listitem"><button type="button" class="ins-lrow" ${attr}><span class="lic">${SV(I.doc)}</span><span class="nm"><b>${esc(name)}</b><small>${esc(sub)}</small></span><span class="note ins-when">${esc(when)}</span><span>${st}</span><span class="ins-from">${from}</span><span class="ins-act">${act}</span></button></div>`;
880
+ function repRow(g) {
881
+ const live = g.files.filter((x) => !x.archived), L = live[0], s = g.setup, d = live.find((x) => x.state !== 'issued');
882
+ const st = cycDots(live.slice(0, 8).reverse().map((x) => (x.state === 'issued' ? 'is' : 'dr'))) + `<small class="note">${d ? 'Draft ready for ' + esc(md(day(d.slot))) : L ? 'Issued ' + esc(md(day(L.slot))) : ''}${s && !s.paused && s.next ? ' · next ' + esc(s.next) : s && s.paused ? ' · paused' : ''}</small>`;
883
+ return lrow(`data-rpt="${esc(g.id)}"`, g.name, [L.lead ? '“' + L.lead + '”' : '', s && s.audience ? s.audience : '', s && s.output ? s.output : ''].filter(Boolean).join(' · ') || 'Latest: ' + md(day(L.slot)),
884
+ s && s.label ? s.label : 'No schedule', st, fromChips(s), d ? '<span class="cz-pill you">Review draft</span>' : '');
885
+ }
886
+ const setupRow = (s) => lrow(`data-setup="${esc(s.id)}"`, s.name, [s.latest && s.latest.lead ? '“' + s.latest.lead + '”' : 'No draft is written yet', s.audience, s.output].filter(Boolean).join(' · '), s.label || '',
887
+ cycDots(['dr0']) + `<small class="note">${s.paused ? 'Paused' : s.drafting ? 'Drafting' : s.next ? 'First draft ' + esc(s.next) : 'Set up'}</small>`, fromChips(s), '<span class="cz-pill q">Set up</span>');
888
+ const ASKST = { running: ['Working on a proposal', 'q', 'Working'], ready: ['Proposal ready, not set up', 'you', 'Review proposal'], failed: ['The run failed', 'red', 'Failed'] };
889
+ const askRow = (a) => lrow(`data-ask="${esc(a.id)}"`, a.proposal && a.proposal.name ? a.proposal.name : a.text, 'You asked: ' + a.text, '', cycDots(['dr0']) + `<small class="note">${esc(ASKST[a.state][0])}</small>`, '<span class="note">Not recorded</span>', `<span class="cz-pill ${ASKST[a.state][1]}">${ASKST[a.state][2]}</span>`);
890
+ function miniHtml(c) {
891
+ const d = c.pts.map((p, i) => (i ? 'L' : 'M') + (5 + p.fx * 120).toFixed(1) + ',' + (4 + (1 - p.fy) * 18).toFixed(1)).join(''), l = c.pts[c.pts.length - 1];
892
+ return `<span class="ins-mini"><small>${esc(c.title)}</small><b>${esc(c.v)}</b><svg viewBox="0 0 130 26" aria-hidden="true"><path d="${d}L125,26L5,26Z" class="ar"/><path d="${d}" class="ln"/><circle cx="${(5 + l.fx * 120).toFixed(1)}" cy="${(4 + (1 - l.fy) * 18).toFixed(1)}" r="3" style="fill:${c.off ? 'var(--cz-dot-late)' : 'var(--cz-dot-ok)'}"/></svg></span>`;
893
+ }
894
+ function dashCard(D) {
895
+ const L = D.keys.map(byKey).filter(Boolean), on = M.pinned === D.id;
896
+ const pill = !L.length ? '<span class="cz-pill q">No chart</span>' : D.off ? `<span class="cz-pill late">${D.off} behind</span>` : '<span class="cz-pill ok">On course</span>';
897
+ const sub = D.id === 'all' ? 'Every goal and budget · PMOS keeps it' : D.saved ? (D.purpose || D.charts.length + ' goals') + (D.at ? ' · saved ' + md(day(D.at)) : '') : 'The goals of one objective';
898
+ return `<button type="button" class="ins-dcard" role="listitem" data-d="${esc(D.id)}" aria-label="Open ${esc(dashName(D))} on Goals${on ? ', pinned' : ''}"><span class="ins-dh"><b>${esc(dashName(D))}</b>${on ? `<span class="ins-pinned" title="Pinned: opens first on Goals">${SV(I.pin)}</span>` : ''}${pill}</span><span class="ins-minis">${L.slice(0, 2).map(miniHtml).join('') || '<span class="note">No goal on it has a series yet.</span>'}</span><small class="note">${esc(sub)}</small></button>`;
238
899
  }
239
900
  function drawList() {
240
- const R = M.reports, found = (R.found || []).filter((f) => !dismissing.has(f.id)), asks = R.asks || [];
241
- const I = listItems(), L = listF === 'dash' ? I.d : listF === 'rep' ? I.r : I.all, pages = Math.max(1, Math.ceil(L.length / PER));
242
- listP = Math.min(Math.max(1, listP), pages);
243
- $('#repCap').textContent = String(I.all.length);
244
- const F3 = [['all', 'All', I.all.length], ['dash', 'Dashboards', I.d.length], ['rep', 'Reports', I.r.length]], cur = F3.find((f) => f[0] === listF);
245
- $('#listSeg').innerHTML = F3.map(([k, t, n]) => `<button type="button" data-f="${k}" aria-pressed="${listF === k}">${t}<em>${n}</em></button>`).join('');
246
- $('#listF').hidden = !(I.d.length && I.r.length) && listF === 'all'; // one kind only: nothing to filter (premium-calmer-first-screen)
247
- $('#listF').innerHTML = `${cur[1]}<em>${cur[2]}</em><svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="m7 10 5 5 5-5"/></svg>`;
248
- $('#listF').setAttribute('aria-label', 'Show: ' + cur[1] + ', ' + cur[2]);
249
- fMenu(false);
250
- const group = (id, label, G, row) => G.length ? `<div class="dmg ngrp" id="${id}" role="list"><p class="label">${esc(label)} · ${G.length}</p>${G.map(row).join('')}</div>` : '';
251
- const row = (it) => it.kind === 'dash' ? dashRow(it.x) : it.kind === 'setup' ? setupRow(it.x) : repRow(it.x);
252
- const empty = listF !== 'dash' && R.missing ? '<div class="nempty"><p><b>The report files could not be read</b>, so none is listed.</p></div>'
253
- : listF !== 'dash' && R.setupsOk === false ? '<div class="nempty"><p><b>The report setups could not be read</b>, so what PMOS found and what you set up are not listed.</p></div>' : '';
254
- const none = listF === 'rep' && !L.length && !R.missing ? '<div class="nempty"><p><b>No report is set up and no report file is on record.</b> Press New, then Report, or ask PMOS for one.</p></div>' : '';
255
- $('#repBody').innerHTML = (listF === 'dash' ? '' : group('repAsks', 'Your requests', asks, askRow) + group('repFound', 'Found in your work', found, foundRow))
256
- + empty + none
257
- + `<div class="dmg" id="listRows" role="list" aria-label="Dashboards and reports">${L.slice((listP - 1) * PER, listP * PER).map(row).join('')}</div>`;
258
- const from = (listP - 1) * PER + 1, to = Math.min(listP * PER, L.length);
259
- $('#listPager').innerHTML = pages < 2 ? `<span class="note">${L.length} shown</span>`
260
- : `<span class="note">${from}–${to} of ${L.length}</span><span class="pg" role="group" aria-label="Pages"><button data-pg="${listP - 1}" ${listP === 1 ? 'disabled' : ''} aria-label="Previous page">‹</button>${Array.from({ length: pages }, (_, i) => `<button data-pg="${i + 1}"${i + 1 === listP ? ' aria-current="page"' : ''} aria-label="Page ${i + 1}">${i + 1}</button>`).join('')}<button data-pg="${listP + 1}" ${listP === pages ? 'disabled' : ''} aria-label="Next page">›</button></span>`;
261
- clearTimeout(askTimer);
262
- if (asks.some((a) => a.state === 'running')) askTimer = setTimeout(load, 5000);
263
- }
264
- function fMenu(open) { $('#listSeg').hidden = !open; $('#listF').setAttribute('aria-expanded', String(open)); }
265
- $('#listF').addEventListener('click', () => { const open = $('#listSeg').hidden; fMenu(open); if (open) $('#listSeg [aria-pressed="true"]').focus(); });
266
- document.addEventListener('click', (e) => { if (!$('#listSeg').hidden && !e.target.closest('#listSeg, #listF')) fMenu(false); });
267
- document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !$('#listSeg').hidden) { fMenu(false); $('#listF').focus(); } });
268
- $('#listSeg').addEventListener('click', (e) => { const b = e.target.closest('[data-f]'); if (!b) return; fMenu(false); if (b.dataset.f === listF) return; listF = b.dataset.f; listP = 1; drawList(); $('#listF').focus(); });
269
- $('#listPager').addEventListener('click', (e) => { const b = e.target.closest('[data-pg]'); if (!b || b.disabled) return; listP = +b.dataset.pg; drawList(); $('#cRep').scrollIntoView({ block: 'nearest' }); });
270
- const menu = (open) => { $('#listMenu').hidden = !open; $('#listNew').setAttribute('aria-expanded', String(open)); };
271
- $('#listNew').addEventListener('click', () => { const open = $('#listMenu').hidden; menu(open); if (open) $('#listMenu button').focus(); });
272
- $('#listMenu').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; menu(false); if (b.id === 'pdNew') openDashEdit(null); else if (b.id === 'repNew') openReportEdit(null); });
273
- document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !$('#listMenu').hidden) { menu(false); $('#listNew').focus(); } });
274
- document.addEventListener('click', (e) => { if (!$('#listMenu').hidden && !e.target.closest('.newm')) menu(false); });
901
+ const R = M.reports, found = (R.found || []).filter((f) => hit(f.name, f.why)), asks = (R.asks || []).filter((a) => hit(a.text));
902
+ const reps = reportGroups().filter((g) => hit(g.x.name)), dashes = M.dashboards.filter((d) => hit(dashName(d)));
903
+ const nRep = reps.length + asks.length;
904
+ $('#repCap').textContent = String(nRep + dashes.length);
905
+ const F3 = [['all', 'All', nRep + dashes.length], ['rep', 'Reports', nRep], ['dash', 'Dashboards', dashes.length]];
906
+ $('#listSeg').innerHTML = F3.map(([k, t, n]) => `<button type="button" class="cz-chip${listF === k ? ' on' : ''}" data-f="${k}" aria-pressed="${listF === k}">${t} <b>${n}</b></button>`).join('');
907
+ $('#sugB').hidden = false; // with none found it still opens the list, where a report can be asked for
908
+ $('#sugB').innerHTML = SV(I.spark) + (found.length ? found.length + (found.length === 1 ? ' suggestion' : ' suggestions') + ' from your work' : 'Suggestions from your work');
909
+ const empty = R.missing ? '<div class="ins-empty"><b>The report files could not be read</b>, so none is listed.</div>'
910
+ : R.setupsOk === false ? '<div class="ins-empty"><b>The report setups could not be read</b>, so what you set up is not listed.</div>' : '';
911
+ const rhead = '<div class="ins-tr ins-th ins-lcols ins-lhead" role="presentation"><span></span><span>Report · audience</span><span>When</span><span>Issued · next</span><span>Built from</span><span></span></div>';
912
+ const repRows = reps.map((g) => (g.kind === 'setup' ? setupRow(g.x) : repRow(g.x))).join('') + asks.map(askRow).join('');
913
+ const repBlock = listF === 'dash' ? '' : `<div class="ins-sec"><h3>Reports</h3><span class="q">${nRep} · by next due</span></div>` + empty
914
+ + (nRep ? `<div class="ins-tbl" id="repAsks">${rhead}<div role="list">${repRows}</div></div>` : !empty ? '<div class="ins-empty"><b>No report is set up and no report file is on record.</b> Reports are made in Home.</div>' : '');
915
+ const dashBlock = listF === 'rep' ? '' : `<div class="ins-sec"><h3>Dashboards</h3><span class="q">${dashes.length} · a dashboard is a saved view of Goals</span></div><div class="ins-dgrid" role="list">${dashes.map(dashCard).join('')}</div>`;
916
+ $('#repBody').innerHTML = `<div id="listRows" aria-label="Dashboards and reports">${repBlock}${dashBlock}</div>`;
917
+ }
918
+ $('#listSeg').addEventListener('click', (e) => { const b = e.target.closest('[data-f]'); if (!b || b.dataset.f === listF) return; listF = b.dataset.f; drawList(); });
919
+ $('#sugB').addEventListener('click', openFound);
920
+ /* Ask for a report is not on the Library bar (AgInsLibrary: reports are made in Home); it stays usable under the suggestions, waiting for design */
275
921
  $('#repBody').addEventListener('click', (e) => {
276
- const pin = e.target.closest('[data-pin]');
277
- if (pin) { pin.disabled = true; pinDash(M.pinned === pin.dataset.pin ? null : pin.dataset.pin, 'list'); return; }
278
- const d = e.target.closest('[data-d]');
279
- if (d) { dash = d.dataset.d; drawDash(); drawList(); try { $('#cDash').scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch { /* no scroll */ } return; }
922
+ const d = e.target.closest('[data-d]'); if (d) { setView(d.dataset.d); return; }
280
923
  const rp = e.target.closest('[data-rpt]');
281
924
  if (rp) { const g = reportGroups().find((x) => x.kind === 'file' && x.x.id === rp.dataset.rpt); if (g) openReport(g.x.files.find((x) => !x.archived), { ws: M.board.ws, name: g.x.setup ? g.x.setup.name : null, cycles: g.x.files, onIssue: () => load(), onChange: () => load() }); return; }
282
- const f = e.target.closest('[data-found]'), a = e.target.closest('[data-ask]'), s = e.target.closest('[data-setup]');
283
- if (f) openFound((M.reports.found || []).find((x) => x.id === f.dataset.found));
284
- else if (a) openAsk((M.reports.asks || []).find((x) => x.id === a.dataset.ask));
285
- else if (s) openSetup((M.reports.setups || []).find((x) => x.id === s.dataset.setup));
286
- });
287
- $('#repAsk').addEventListener('submit', async (e) => {
288
- e.preventDefault();
289
- const inp = $('#repAskIn'), text = inp.value.trim(), go = $('#repAskGo');
290
- if (!text) { toast('Say what the report is for, then press Ask.'); inp.focus(); return; }
291
- go.disabled = true;
292
- const res = await repPost('ask', { text });
293
- go.disabled = false;
294
- if (!res || res.ok !== true) { toast((res && res.error) || 'The request could not start.'); return; }
295
- inp.value = ''; toast('Asked. A background run is working on a proposal. Nothing is set up yet.'); await load();
925
+ const su = e.target.closest('[data-setup]'); if (su) { openSetup(su.dataset.setup); return; }
926
+ const ak = e.target.closest('[data-ask]'); if (ak) openRequest(ak.dataset.ask);
296
927
  });
297
928
 
298
- /* ── the report dialogs: each press is one existing /api/report-setups/* route (PRD R2 to R4) ─────────────────────────────────────────────── */
299
- const repPost = (sub, body) => pmPost('/api/report-setups/' + sub, Object.assign({ ws: M.board.ws }, body));
300
- function repDlg(o) {
301
- openDlg({ eye: o.eye + ' · real data', title: o.title, sub: o.sub || M.board.name, say: o.say, stream: turnA(ptx(o.say)), noteKey: popKey('report', M.board.ws, o.title), facts: o.facts, label: 'Report',
302
- pane: `<article class="paper doc">${o.html}<p class="note" id="rxM" role="status" style="margin:12px 0 0;min-height:1.2em"></p><div class="cact">${o.acts.map(([id, t, alt]) => `<button class="cta${alt ? ' alt' : ''}" data-rx="${id}">${esc(t)}</button>`).join('')}</div></article>` });
303
- $('#oMain').onchange = null;
304
- $('#oMain').onclick = async (e) => {
305
- const b = e.target.closest('[data-rx]'); if (!b) return;
306
- const m = $('#rxM'), fn = o.on[b.dataset.rx]; if (!fn) return;
307
- $$('#oMain [data-rx]').forEach((x) => { x.disabled = true; });
308
- const after = await fn(m, b);
309
- if (after === 'keep') { $$('#oMain [data-rx]').forEach((x) => { x.disabled = false; }); return; }
310
- if (after === 'keep-off') return;
311
- closeDlg(); await load();
312
- };
929
+ /* ── Library flows the Agreed design does not draw: each a plain minimal form in the Viewer card, with the "Waiting for design" marker. They post to
930
+ * the console's own report-setups routes (lib/routes-report-setups.js); none opens the old dialog or the Chat page. ─────────────────────────────── */
931
+ const kvHtml = (rows) => `<dl class="ins-kv">${rows.filter(Boolean).map(([a, b]) => `<dt>${esc(a)}</dt><dd>${esc(b)}</dd>`).join('')}</dl>`;
932
+ function actionsHtml(acts) { return `<div class="ins-mact">${acts.map(([k, t, primary]) => `<button type="button" class="${primary ? 'ins-primary' : 'cz-chip'}" data-act="${k}">${esc(t)}</button>`).join('')}<span class="note" data-msg></span></div>`; }
933
+ async function postSetup(el, route, body, said) {
934
+ const msg = el.querySelector('[data-msg]'); if (msg) msg.textContent = 'Sending.';
935
+ const res = await pmPost('/api/report-setups/' + route, Object.assign({ ws: M.board.ws }, body));
936
+ if (!res || res.ok !== true) { if (msg) msg.textContent = (res && res.error) || 'It could not be done. Nothing changed.'; return false; }
937
+ toast(typeof said === 'function' ? said(res) : said); await load(); return true;
313
938
  }
314
- /* Words for a refused press: what the server said, then how to go on. A reason (set-up | dismissed | gone) means the list this window came from is out of date, so it is read again and a retry would only repeat the refusal. */
315
- const pressFailed = (res, plain) => {
316
- const e = res && res.error ? String(res.error) : plain;
317
- if (res && res.reason) return e + ' This window is out of date. Close it; the list has been read again.';
318
- return e + ' Nothing was recorded. Press the button to try again.';
319
- };
320
- /* A press: post, then say the result in words, or keep the dialog open with the server's refusal. */
321
- const press = (sub, body, said) => async (m) => {
322
- m.textContent = 'Recording.';
323
- const res = await repPost(sub, body);
324
- if (!res || res.ok !== true) { m.textContent = pressFailed(res, 'That did not go through.'); if (res && res.reason) load(); return 'keep'; }
325
- toast(typeof said === 'function' ? said(res) : said); return null;
326
- };
327
- const setupSaid = (res) => { const d = res.drafted || {}; return 'Set up. ' + (d.path ? 'The first draft is ' + d.path + '.' : 'The first draft was not written' + (d.error ? ': ' + d.error : '') + '. Draft it now on the report tries again.'); };
328
- const propHtml = (p) => p && p.rows.length ? kv(p.rows) : '<p class="note" style="margin:0">The proposal holds no fields yet.</p>';
329
- function openFound(f) {
330
- if (!f) return;
331
- repDlg({ eye: 'Found in your work', title: f.name, say: f.why + ' Set it up, or say it is not a report.',
332
- html: `<p class="lede" style="margin:0 0 12px">${esc(f.why)}</p>${propHtml(f.proposal)}<h3 class="h2">What PMOS saw · ${f.evidence.length}</h3><ul class="pdev">${f.evidence.map((x) => `<li>${esc(x.text)}${x.kind ? ` <small>${esc(x.kind)}</small>` : ''}</li>`).join('')}</ul><p class="note">Set it up records the report in the report ledger and drafts its first cycle as a file. Not a report hides it; you can undo for 5 seconds.</p>`,
333
- acts: [['set', 'Set it up'], ['no', 'Not a report', 1]],
334
- on: {
335
- set: press('setup', { finding: f.id, name: f.name }, setupSaid),
336
- no: (m) => {
337
- const t = setTimeout(async () => { dismissing.delete(f.id); const res = await repPost('dismiss', { finding: f.id, name: f.name }); if (!res || res.ok !== true) toast(pressFailed(res, 'Not a report did not go through.')); await load(); }, 5000);
338
- dismissing.set(f.id, t); drawList();
339
- m.innerHTML = 'Hidden. It is recorded as not a report in 5 seconds. <button class="lk" id="rxUndo">Undo</button>';
340
- $('#rxUndo').onclick = () => { clearTimeout(dismissing.get(f.id)); dismissing.delete(f.id); drawList(); m.textContent = 'Undone. Nothing was recorded.'; $$('#oMain [data-rx]').forEach((x) => { x.disabled = false; }); };
341
- return 'keep-off';
342
- },
343
- } });
344
- }
345
- function openAsk(a) {
346
- if (!a) return;
347
- if (a.state === 'running') {
348
- repDlg({ eye: 'Your request', title: a.text, say: 'A background run is working on a proposal. It proposes only; nothing is set up until you press Set it up.', html: `<p class="lede" style="margin:0">A background run is working on this request. This page checks again every 5 seconds.</p>`, acts: [['cancel', 'Cancel the request', 1]], on: { cancel: press('cancel', { id: a.id }, 'Request cancelled.') } });
349
- return;
350
- }
351
- if (a.state === 'failed') {
352
- repDlg({ eye: 'Your request', title: a.text, say: 'The run ended without a proposal.', html: `<p class="lede" style="margin:0">${esc(a.error || 'The run ended without a proposal.')}</p>`, acts: [['cancel', 'Remove the request', 1]], on: { cancel: press('cancel', { id: a.id }, 'Request removed.') } });
353
- return;
354
- }
355
- repDlg({ eye: 'Your request', title: (a.proposal && a.proposal.name) || a.text, say: 'Here is the proposal. Set it up, ask for a change, or cancel.',
356
- html: `<p class="note" style="margin:0 0 10px">You asked: ${esc(a.text)}</p>${propHtml(a.proposal)}<div class="addf" style="margin-top:14px"><label>A change to ask for<input id="rxChg" maxlength="500" placeholder="For example: monthly, not weekly"></label></div><p class="note">Change it starts the run again with your words. Set it up records the report and drafts its first cycle as a file.</p>`,
357
- acts: [['set', 'Set it up'], ['chg', 'Change it', 1], ['cancel', 'Cancel', 1]],
358
- on: {
359
- set: press('setup', { ask: a.id }, setupSaid),
360
- chg: (m) => { const t = $('#rxChg').value.trim(); if (!t) { m.textContent = 'Say what to change.'; $('#rxChg').focus(); return 'keep'; } return press('change', { id: a.id, text: t }, 'Asked for the change. The run is revising the proposal.')(m); },
361
- cancel: press('cancel', { id: a.id }, 'Request cancelled.'),
362
- } });
363
- }
364
- function openSetup(s) {
365
- if (!s) return;
366
- 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]];
367
- const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
368
- if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
369
- if (s.fromWork) acts.push(['studio', 'Shape it in a chat', 1]);
370
- 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.',
371
- 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>`,
372
- acts, on: {
373
- draft: press('draft', { id: s.id }, (res) => res.drafting ? 'Drafting started. The draft follows the saved structure.' : 'Drafted: ' + ((res.drafted && res.drafted.path) || 'the next cycle') + '.'),
374
- pause: press('pause', { id: s.id }, 'Paused. It is not drafted until you resume it.'),
375
- resume: press('resume', { id: s.id }, 'Resumed. It is drafted on its schedule again.'),
376
- studio: () => { openReportEdit(s); return 'keep-off'; },
377
- } });
939
+ function openSetup(id) {
940
+ const s = (M.reports.setups || []).find((x) => x.id === id); if (!s) return;
941
+ viewer({ kind: 'Report', title: s.name, icon: 'report', render: (el) => {
942
+ el.innerHTML = waitMark('A report setup') + kvHtml([['What it is for', s.purpose || '—'], s.audience ? ['For', s.audience] : null, ['Schedule', s.label || 'No schedule'], ['Next draft', s.paused ? 'Paused' : s.next || '—'], s.output ? ['Made as', s.output] : null])
943
+ + actionsHtml([['draft', 'Draft it now', true], s.paused ? ['resume', 'Resume'] : ['pause', 'Pause']]);
944
+ el.addEventListener('click', async (e) => { const b = e.target.closest('[data-act]'); if (!b) return;
945
+ if (b.dataset.act === 'draft') { if (await postSetup(el, 'draft', { id }, (r) => 'Drafting it now' + (r.drafted && r.drafted.path ? ': ' + r.drafted.path : '.'))) openSetup(id); }
946
+ else if (await postSetup(el, b.dataset.act, { id }, b.dataset.act === 'pause' ? 'Paused ' + s.name + '.' : 'Resumed ' + s.name + '.')) openSetup(id); });
947
+ } });
378
948
  }
379
-
380
- /* ── dock ─────────────────────────────────────────────────────────────────────────────────────────────────────── */
381
- function drawDock() { $('#dN').textContent = M.dock.needs; $('#dLab').textContent = M.dock.label; $('#dNext').innerHTML = M.dock.next ? `<i></i>First <b>${esc(M.dock.next)}</b>` : 'No measure is behind its line'; }
382
-
383
- /* ── the dialog: the measure's record, no press, the read-only agent beside it ───────────────────────────────── */
384
- function cardHtml(c) { return `<div class="acard" id="card"><p class="ct">What this page can do</p><p class="nodef" id="holdWhy">${esc(c.dialog.hold)} The switches under On your dashboards save a dashboard and change no record.</p></div>`; }
385
- function paneHtml(c) {
386
- const p = c.dialog.pane;
387
- return `<article class="paper doc"><p class="dpath">${esc(p.file)}</p><h3 class="d1">${esc(c.title)}</h3><p>${esc(c.dialog.say)}</p><div class="ntw pdchart">${tileHtml(c)}</div><div class="kv2">${c.dialog.facts.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div><h3 class="h2">All ${c.pts.length} readings</h3><div class="kv2">${p.rows.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div>${onDashHtml(c)}<p class="xn">Read from the KR metric record. The line status is the record's own: the straight line from its baseline to its target. Where this page says where a measure lands by its target date, that is a straight line through its last four readings, carried to that date. It is not drawn.</p></article>`;
388
- }
389
- /* Add to a dashboard (PRD D6): one switch per saved dashboard of the board. A press saves that dashboard with the chart added or taken off. */
390
- function onDashHtml(c) {
391
- if (!M.board.id) return '';
392
- const L = savedDash();
393
- return `<h3 class="h2">On your dashboards</h3>${L.length ? `<div class="dplist" role="group" aria-label="Add to a dashboard">${L.map((d) => { const on = d.charts.includes(c.id); return `<button role="switch" aria-checked="${on}" aria-pressed="${on}" data-pdsw="${esc(d.id)}"><span><b>${esc(d.name)}</b><small>${d.charts.length} ${d.charts.length === 1 ? 'chart' : 'charts'}</small></span><i>${on ? 'On it' : 'Add'}</i></button>`; }).join('')}</div>` : '<p class="note" style="margin:0 0 12px">No saved dashboard on this board yet. Make one with New dashboard.</p>'}<p class="note" id="pdSwM" role="status" style="min-height:1.2em"></p>`;
394
- }
395
- function openChart(c) {
396
- if (!c) return;
397
- const d = c.dialog;
398
- openDlg({ eye: d.eye + ' · real data', title: c.title, sub: c.sub + ' · ' + c.chip, say: d.say, stream: turnA(logHtml(d)) + turnA(ptx(d.say)) + cardHtml(c), noteKey: c.key, pane: paneHtml(c), label: 'KR metric record' });
399
- $('#oMain').onchange = null;
400
- $('#oMain').onclick = async (e) => {
401
- const b = e.target.closest('[data-pdsw]'); if (!b || b.disabled) return;
402
- const D = savedDash().find((x) => x.id === b.dataset.pdsw); if (!D) return;
403
- const on = D.charts.includes(c.id), charts = on ? D.charts.filter((x) => x !== c.id) : D.charts.concat(c.id);
404
- b.disabled = true; $('#pdSwM').textContent = 'Saving.';
405
- const res = await saveDash({ id: D.id, name: D.name, purpose: D.purpose, charts, main: D.main });
406
- b.disabled = false;
407
- if (!res || res.ok !== true) { $('#pdSwM').textContent = (res && res.error) || 'The dashboard could not be saved.'; return; }
408
- D.charts = charts; b.setAttribute('aria-checked', !on); b.setAttribute('aria-pressed', !on); $('i', b).textContent = on ? 'Add' : 'On it'; $('small', b).textContent = charts.length + ' ' + (charts.length === 1 ? 'chart' : 'charts');
409
- $('#pdSwM').textContent = on ? 'Taken off ' + D.name + '.' : 'Added to ' + D.name + '.';
410
- load();
411
- };
412
- loadThread(c.key);
413
- setTimeout(() => { const b = $('#dBody'); b.scrollTop = b.scrollHeight; }, 120);
949
+ function openFound() {
950
+ const F = M.reports.found || [];
951
+ viewer({ kind: 'Found in your work', title: F.length === 1 ? '1 suggestion' : F.length + ' suggestions', icon: 'report', render: (el) => {
952
+ el.innerHTML = waitMark('What PMOS found in your work') + (F.length ? F.map((f) => `<section class="ins-fnd" data-f="${esc(f.id)}"><b>${esc(f.name)}</b>${f.confidence ? ` <span class="cz-pill q">${esc(f.confidence)}</span>` : ''}<p class="note">${esc(f.why)}</p>`
953
+ + (f.evidence.length ? `<ul class="ins-ev">${f.evidence.map((x) => `<li>${esc(x.text)}</li>`).join('')}</ul>` : '') + (f.proposal ? kvHtml(f.proposal.rows || []) : '')
954
+ + `<div class="ins-mact"><button type="button" class="ins-primary" data-fx="setup">Set it up</button><button type="button" class="cz-chip" data-fx="dismiss">Not a report</button><span class="note" data-msg></span></div></section>`).join('') : '<p class="note">Nothing is waiting.</p>')
955
+ + '<div class="ins-mact"><button type="button" class="cz-chip" data-askr>Ask for a report</button></div>';
956
+ el.addEventListener('click', async (e) => { if (e.target.closest('[data-askr]')) { openAsk(); return; } const b = e.target.closest('[data-fx]'); if (!b) return; const sec = b.closest('[data-f]'), fid = sec.dataset.f;
957
+ if (await postSetup(sec, b.dataset.fx, { finding: fid }, b.dataset.fx === 'setup' ? (r) => 'Set up.' + (r.drafted && r.drafted.path ? ' The first draft is ' + r.drafted.path + '.' : '') : 'Marked as not a report.')) openFound(); });
958
+ } });
414
959
  }
415
- $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
416
-
417
- /* ── the Board measures card (initiative briefing-premium-metrics, option C) ─────────────────────────────────────────
418
- * The Board's four measures from GET /api/board-metrics-premium?ws=&weeks=, drawn with the Board's own tiles over 8, 26 or 52 weeks. A measure's dialog
419
- * holds the page's one target press: POST /api/board-metric-targets/save, which the Board then draws as the chip, the dashed line and the outline. */
420
- let BM = null, bmWeeks = 8, bmTimer = null;
421
- const BM_KEY = 'pmos.premium.bmWeeks';
422
- try { const w = Number(localStorage.getItem(BM_KEY)); if ([8, 26, 52].includes(w)) bmWeeks = w; } catch { /* a blocked store keeps 8 weeks */ }
423
- function bmDraw() {
424
- const card = $('#cBm'); card.hidden = false;
425
- $$('#bmRange button').forEach((b) => b.setAttribute('aria-pressed', String(+b.dataset.w === bmWeeks))); pillOf($('#bmRange'));
426
- if (!BM) return;
427
- $('#bmCap').textContent = BM.header;
428
- $('#bmHint').innerHTML = (BM.lead ? `<b class="mflag">${esc(BM.lead)}</b> ` : '') + esc(BM.body) + ' Press a measure to set its target. The Board draws the same target.';
429
- $('#bmBody').style.gridTemplateColumns = 'repeat(' + Math.min(4, BM.tiles.length) + ',minmax(0,1fr))';
430
- $('#bmBody').innerHTML = BM.tiles.map(MT.tileHtml).join('');
431
- $('#bmNote').textContent = BM.note;
432
- $('#bmLead').hidden = !BM.lead; $('#bmLead').textContent = BM.lead || ''; // the one line left in view; ⓘ opens the hint and the note
960
+ function openRequest(id) {
961
+ const a = (M.reports.asks || []).find((x) => x.id === id); if (!a) return;
962
+ viewer({ kind: 'Report request', title: a.proposal && a.proposal.name ? a.proposal.name : a.text, icon: 'report', render: (el) => {
963
+ const running = a.state === 'running';
964
+ el.innerHTML = waitMark('A report request and its proposal') + kvHtml([['You asked', a.text], ['State', running ? 'A background run is working on a proposal' : a.state === 'failed' ? 'The run failed' + (a.error ? ': ' + a.error : '') : 'Proposal ready, not set up']])
965
+ + (a.proposal ? kvHtml(a.proposal.rows || []) : '')
966
+ + (running ? actionsHtml([['cancel', 'Cancel']]) : `<label class="ins-fl">Change it<input class="ins-inp" data-chg maxlength="300" placeholder="What to change"></label>` + actionsHtml((a.state === 'ready' ? [['setup', 'Set it up', true]] : []).concat([['change', 'Send the change'], ['cancel', 'Cancel']])));
967
+ el.addEventListener('click', async (e) => { const b = e.target.closest('[data-act]'); if (!b) return; const k = b.dataset.act;
968
+ if (k === 'change') { const t = (el.querySelector('[data-chg]') || {}).value || ''; if (!t.trim()) { el.querySelector('[data-msg]').textContent = 'Say what to change.'; return; } if (await postSetup(el, 'change', { id, text: t.trim() }, 'Sent. A second run revises the proposal.')) openRequest(id); return; }
969
+ if (k === 'setup') { await postSetup(el, 'setup', { ask: id }, (r) => 'Set up.' + (r.drafted && r.drafted.path ? ' The first draft is ' + r.drafted.path + '.' : '')); return; }
970
+ if (await postSetup(el, 'cancel', { id }, 'Cancelled the request.') && window.czViewer) window.czViewer.close(); });
971
+ } });
433
972
  }
434
- async function bmLoad() {
435
- clearTimeout(bmTimer);
436
- if (!M || !M.board || !M.board.ws) { $('#cBm').hidden = true; return; }
437
- let r = null;
438
- try { const res = await fetch('/api/board-metrics-premium?ws=' + encodeURIComponent(M.board.ws) + '&weeks=' + bmWeeks, { credentials: 'same-origin' }); r = await res.json(); } catch { r = null; }
439
- if (!r || !r.ok || r.state !== 'ready') { BM = null; bmDraw(); $('#bmCap').textContent = 'not read'; $('#bmHint').textContent = 'The Board measures could not be read, so none is shown.' + (r && r.error ? ' The reason: ' + r.error : ''); $('#bmLead').hidden = false; $('#bmLead').textContent = $('#bmHint').textContent; $('#bmBody').innerHTML = ''; $('#bmNote').textContent = ''; return; }
440
- BM = r.model; bmDraw();
441
- if (BM.pending) bmTimer = setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
442
- }
443
- function bmOpen(i) {
444
- const t = BM && BM.tiles[i]; if (!t) return;
445
- const vals = t.ser ? `<h3 class="sh">Values</h3><div class="vtb">${t.ser.map((v, j) => `<div><span>${esc(t.wk[j])}</span><b>${v == null ? (t.since ? 'Not kept yet' : 'No runs') : esc(MT.fmt(t, v))}</b></div>`).join('')}</div>` : '';
446
- const form = t.absent ? `<p class="note" style="margin:12px 0 0">A target can be set once this measure is counted.</p>`
447
- : `<div class="addf" style="margin-top:14px"><label>Target (${t.lowBetter ? 'at most' : 'at least'})<input id="bmT" inputmode="decimal" maxlength="12" value="${t.tg != null ? esc(String(t.tg)) : ''}" placeholder="For example: ${t.key === 'corrections' ? '10' : t.key === 'merges' ? '5' : '0'}"></label>
448
- <p class="note" id="bmM" role="status" style="margin:0;min-height:1.2em"></p><div class="cact"><button class="cta" id="bmGo">Save target</button>${t.tg != null ? '<button class="cta alt" id="bmClr">Clear target</button>' : ''}</div></div>`;
449
- // popup context slice 5: the first line reads the numbers, and says when the trunk was fetched, so two empty weeks are not taken for a quiet trunk
450
- const lt = (iso) => { const d = new Date(iso); return Number.isNaN(d.getTime()) ? '' : d.getDate() + ' ' + d.toLocaleString('en-GB', { month: 'short' }) + ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0'); };
451
- const fetched = t.trunk ? (t.trunk.fetched_at ? `${t.trunk.ref} was last fetched ${lt(t.trunk.fetched_at)}` : `${t.trunk.ref} has no fetch on record`) : '';
452
- const tgt = t.tg != null ? ` The target is ${t.tg}; change it or clear it here.` : ' No target is set; type one and save it.';
453
- const say = t.absent ? `${t.label} is not shown: ${t.why}`
454
- : t.quiet ? `${t.label} was ${t.quiet.peak} in the week to ${t.quiet.week}, then 0 for the last two weeks. That is a quiet trunk or an old fetch: ${fetched || 'the fetch time is not known'}.${tgt}`
455
- : `${t.label} is ${t.value}, ${t.text}.${t.change ? ' ' + t.change.txt + '.' : ''}${fetched ? ' ' + fetched + '.' : ''}${tgt}`;
456
- const facts = MT.factRows(t, BM.repo, BM.weeks).concat(t.trunk ? [['Trunk read', t.trunk.ref + (t.trunk.fetched_at ? ', fetched ' + lt(t.trunk.fetched_at) : ', no fetch on record')]] : []);
457
- const pane = `<article class="paper doc"><p class="lede" style="margin:0 0 10px">${esc(t.def)}</p>${kv(facts)}${form}${vals}<p class="note" style="margin-top:12px">${esc(BM.note)}</p></article>`;
458
- openDlg({ eye: 'Board measure · real data', title: t.label, sub: BM.repo, say, stream: turnA(ptx(say)), noteKey: popKey('measure', BM.repo, t.key || t.label), facts, pane, label: 'Measure' });
459
- $('#oMain').onchange = null;
460
- $('#oMain').onclick = async (e) => {
461
- const go = e.target.closest('#bmGo'), clr = e.target.closest('#bmClr'); if (!go && !clr) return;
462
- const target = clr ? null : $('#bmT').value.trim();
463
- if (go && target === '') { $('#bmM').textContent = 'Type a number first.'; return; }
464
- (go || clr).disabled = true; $('#bmM').textContent = 'Saving.';
465
- const res = await pmPost('/api/board-metric-targets/save', { ws: M.board.ws, key: t.key, target });
466
- (go || clr).disabled = false;
467
- if (!res || res.ok !== true) { $('#bmM').textContent = (res && res.error) || 'The target could not be saved.'; return; }
468
- closeDlg(); toast(clr ? 'The target of ' + t.label + ' is cleared.' : 'The target of ' + t.label + ' is ' + target + '.');
469
- bmLoad();
470
- };
973
+ function openAsk() {
974
+ viewer({ kind: 'Library', title: 'Ask for a report', icon: 'report', render: (el) => {
975
+ el.innerHTML = waitMark('New report') + '<form class="ins-mf" data-ask><label class="ins-fl">What report do you want?<textarea class="ins-ta" name="t" maxlength="600" placeholder="For example: a weekly risk note for leadership"></textarea></label><p class="note">A background run proposes a report. Nothing is set up until you say so.</p><div class="ins-mact"><button type="submit" class="ins-primary">Ask</button><span class="note" data-msg></span></div></form>';
976
+ el.querySelector('[data-ask]').addEventListener('submit', async (e) => { e.preventDefault(); const t = e.target.t.value.trim(); if (!t) { el.querySelector('[data-msg]').textContent = 'Say what report you want.'; return; }
977
+ if (await postSetup(el, 'ask', { text: t }, 'Asked. The proposal shows in Library when it is ready. Nothing is set up yet.') && window.czViewer) window.czViewer.close(); });
978
+ } });
471
979
  }
472
- MT.wireTiles($('#bmBody'), () => (BM ? BM.tiles : []), bmOpen);
473
- $('#bmRange').addEventListener('click', (e) => { const b = e.target.closest('[data-w]'); if (!b || +b.dataset.w === bmWeeks) return; bmWeeks = +b.dataset.w; try { localStorage.setItem(BM_KEY, String(bmWeeks)); } catch { /* not kept */ } bmDraw(); bmLoad(); });
474
980
 
475
- /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────── */
476
- function draw() { drawHead(); if (!dash || !M.dashboards.some((d) => d.id === dash)) dash = M.pinned || 'all'; drawDash(); drawList(); drawDock(); onScroll(); }
981
+ /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
982
+ function redraw() { if (!M) return; drawBar(); drawStrip(); drawGoals(); drawOutcomes(); drawList(); }
983
+ function draw() {
984
+ if (!dash || !M.dashboards.some((d) => d.id === dash)) dash = M.pinned || 'all';
985
+ setPageGaps(((M.header && M.header.missing) || []).length);
986
+ redraw();
987
+ }
477
988
  async function load() {
478
989
  const p = new URLSearchParams(location.search), q = [p.get('ws') ? 'ws=' + encodeURIComponent(p.get('ws')) : '', p.get('board') ? 'board=' + encodeURIComponent(p.get('board')) : ''].filter(Boolean).join('&');
479
990
  let r = null, status = 0;
480
991
  try { const res = await fetch('/api/insights-premium' + (q ? '?' + q : ''), { credentials: 'same-origin' }); status = res.status; r = await res.json(); } catch { r = null; }
481
992
  if (!r || !r.ok) {
482
- $('#snap').textContent = 'The records could not be read';
483
- $('#insEye').textContent = 'Insight'; $('#insWhy').textContent = '';
993
+ $('#insEye').textContent = ''; $('#insWhy').textContent = ''; $('#askWhy').hidden = true;
484
994
  $('#brief').textContent = 'The KR metric records could not be read, so this page shows nothing rather than guess.' + (r && r.error ? ' The reason: ' + r.error : status ? ' (the server answered ' + status + ')' : ' The server did not answer.');
485
995
  setTimeout(load, 15000);
486
996
  return;
487
997
  }
488
- M = r.model; draw(); bmLoad();
998
+ const first = !M; M = r.model; draw(); if (first || !BM) bmLoad();
489
999
  }
490
- $('#brief').textContent = 'Reading the records.';
1000
+ { const t = new URLSearchParams(location.search).get('tab'); setTab(t === 'outcomes' || t === 'library' ? t : 'goals'); }
491
1001
  load();