create-pmos 0.397.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 (145) hide show
  1. package/package.json +13 -13
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-adddoc-test.js +101 -52
  8. package/workspace/briefing-premium-board-test.js +252 -128
  9. package/workspace/briefing-premium-calendar-2-test.js +135 -198
  10. package/workspace/briefing-premium-calendar-3-test.js +143 -418
  11. package/workspace/briefing-premium-calendar-test.js +86 -196
  12. package/workspace/briefing-premium-doc-edit-test.js +95 -83
  13. package/workspace/briefing-premium-initiative-test.js +159 -296
  14. package/workspace/briefing-premium-insights-test.js +337 -219
  15. package/workspace/briefing-premium-metrics-test.js +53 -97
  16. package/workspace/briefing-premium-products-test.js +40 -27
  17. package/workspace/briefing-premium-sources-test.js +66 -48
  18. package/workspace/briefing-premium-test.js +150 -647
  19. package/workspace/briefing-premium-work-test.js +88 -283
  20. package/workspace/changelog.json +12 -0
  21. package/workspace/fixtures/board-premium-trail.js +32 -0
  22. package/workspace/fixtures/premium-viewer-fixtures.js +182 -0
  23. package/workspace/guide/briefing-premium.md +3 -1
  24. package/workspace/guide/home.md +47 -0
  25. package/workspace/guide/index.md +1 -0
  26. package/workspace/lib/agent-roles.js +71 -0
  27. package/workspace/lib/board-premium.js +85 -19
  28. package/workspace/lib/board-trail.js +223 -0
  29. package/workspace/lib/home-work-item.js +58 -0
  30. package/workspace/lib/insights-goals.js +196 -0
  31. package/workspace/lib/insights-premium.js +62 -14
  32. package/workspace/lib/insights-records.js +101 -0
  33. package/workspace/lib/jira-tickets.js +1 -1
  34. package/workspace/lib/route-modules.js +4 -0
  35. package/workspace/lib/routes-board-trail.js +33 -0
  36. package/workspace/lib/routes-home-desk.js +176 -0
  37. package/workspace/lib/routes-insights-premium.js +12 -3
  38. package/workspace/lib/routes-insights-records.js +129 -0
  39. package/workspace/lib/routes-notes.js +1 -0
  40. package/workspace/lib/routes-viewer.js +108 -0
  41. package/workspace/lib/transcript-steps.js +123 -0
  42. package/workspace/lib/viewer-meeting.js +205 -0
  43. package/workspace/lib/viewer-report.js +89 -0
  44. package/workspace/package-lock.json +2 -2
  45. package/workspace/package.json +1 -1
  46. package/workspace/premium-board-actions-test.js +85 -75
  47. package/workspace/premium-briefing-depth-test.js +66 -53
  48. package/workspace/premium-chat-attach-test.js +54 -63
  49. package/workspace/premium-chat-chart-tab-test.js +35 -37
  50. package/workspace/premium-chat-context-test.js +19 -18
  51. package/workspace/premium-chat-goal-view-test.js +23 -23
  52. package/workspace/premium-chat-notes-test.js +26 -31
  53. package/workspace/premium-chat-report-tab-test.js +32 -28
  54. package/workspace/premium-chat-term-test.js +16 -16
  55. package/workspace/premium-chat-viewer-test.js +60 -59
  56. package/workspace/premium-core-doc-issue-test.js +50 -43
  57. package/workspace/premium-html-viewer-test.js +14 -17
  58. package/workspace/premium-phone-card-test.js +7 -2
  59. package/workspace/premium-phone-room-test.js +41 -35
  60. package/workspace/premium-report-read-test.js +115 -197
  61. package/workspace/premium-viewer-download-test.js +19 -22
  62. package/workspace/premium-viewer-flicker-test.js +11 -16
  63. package/workspace/premium-viewer-share-test.js +6 -9
  64. package/workspace/premium-viewer-test.js +41 -60
  65. package/workspace/premium-vw-backlog-test.js +53 -33
  66. package/workspace/premium-vw-cal-test.js +82 -128
  67. package/workspace/premium-vw-copy-test.js +17 -33
  68. package/workspace/premium-vw-doc-test.js +11 -10
  69. package/workspace/premium-vw-item-test.js +50 -49
  70. package/workspace/premium-vw-jira-test.js +53 -27
  71. package/workspace/premium-vw-meet-test.js +118 -187
  72. package/workspace/premium-vw-notes-test.js +85 -108
  73. package/workspace/premium-vw-rec-test.js +72 -194
  74. package/workspace/premium-vw-slides-test.js +46 -50
  75. package/workspace/premium-welcome-test.js +3 -2
  76. package/workspace/premium-work-depth-test.js +61 -53
  77. package/workspace/public/pm/bd-acts.js +305 -0
  78. package/workspace/public/pm/bd-span.js +186 -82
  79. package/workspace/public/pm/bd-stages.js +25 -11
  80. package/workspace/public/pm/c3-doc-sheet.js +1 -1
  81. package/workspace/public/pm/c3-md.js +3 -395
  82. package/workspace/public/pm/c3-phone-detail.js +1 -1
  83. package/workspace/public/pm/c3-phone-model.js +3 -68
  84. package/workspace/public/pm/chat-term.js +3 -3
  85. package/workspace/public/pm/cozy-board.css +497 -230
  86. package/workspace/public/pm/cozy-home.css +570 -142
  87. package/workspace/public/pm/cozy-home.js +5 -3
  88. package/workspace/public/pm/cozy-insights.css +296 -167
  89. package/workspace/public/pm/cozy-md.js +396 -0
  90. package/workspace/public/pm/cozy-nav.js +17 -6
  91. package/workspace/public/pm/cozy-placeholder.js +26 -0
  92. package/workspace/public/pm/cozy-viewer.css +3 -3
  93. package/workspace/public/pm/cozy-viewer.js +144 -0
  94. package/workspace/public/pm/cozy-vw.css +485 -0
  95. package/workspace/public/pm/cozy.css +83 -1
  96. package/workspace/public/pm/home-adddoc.js +48 -0
  97. package/workspace/public/pm/home-app.js +905 -0
  98. package/workspace/public/pm/home-around.js +515 -0
  99. package/workspace/public/pm/home-chat.js +459 -0
  100. package/workspace/public/pm/home-data.js +312 -0
  101. package/workspace/public/pm/home-draft.js +68 -0
  102. package/workspace/public/pm/home-more.js +249 -0
  103. package/workspace/public/pm/home-phone-card.js +109 -0
  104. package/workspace/public/pm/home-work.js +519 -0
  105. package/workspace/public/pm/phone-moment.js +69 -0
  106. package/workspace/public/pm/pm-work-view.js +1 -1
  107. package/workspace/public/pm/premium-attach.js +4 -0
  108. package/workspace/public/pm/premium-board.js +423 -394
  109. package/workspace/public/pm/premium-chart-tab.js +110 -62
  110. package/workspace/public/pm/premium-deck.js +3 -3
  111. package/workspace/public/pm/premium-first.js +25 -21
  112. package/workspace/public/pm/premium-insights.js +792 -568
  113. package/workspace/public/pm/premium-meeting.js +61 -549
  114. package/workspace/public/pm/premium-notes.js +1 -1
  115. package/workspace/public/pm/premium-report-frame.css +20 -0
  116. package/workspace/public/pm/premium-report-read.js +509 -480
  117. package/workspace/public/pm/premium-report-tab.js +87 -63
  118. package/workspace/public/pm/premium-shell.js +72 -119
  119. package/workspace/public/pm/premium-viewer.js +22 -1
  120. package/workspace/public/pm/premium-vw-cal.js +187 -48
  121. package/workspace/public/pm/premium-vw-doc.css +6 -0
  122. package/workspace/public/pm/premium-vw-doc.js +40 -2
  123. package/workspace/public/pm/premium-vw-file.js +2 -2
  124. package/workspace/public/pm/premium-vw-meet.js +6 -83
  125. package/workspace/public/pm/premium-vw-mtg.js +731 -0
  126. package/workspace/public/pm/premium-vw-notes.js +56 -69
  127. package/workspace/public/pm/premium-vw-open.js +35 -0
  128. package/workspace/public/pm/premium-vw-page.js +16 -0
  129. package/workspace/public/pm/premium-vw-rec.js +11 -218
  130. package/workspace/public/pm/premium-vw-slides.css +5 -0
  131. package/workspace/public/pm/premium-vw-slides.js +44 -8
  132. package/workspace/public/pm/term-view.js +22 -0
  133. package/workspace/public/premium-board.html +28 -70
  134. package/workspace/public/premium-initiative.html +8 -48
  135. package/workspace/public/premium-insights.html +22 -60
  136. package/workspace/public/premium-viewer.html +20 -0
  137. package/workspace/public/premium.html +16 -107
  138. package/workspace/server.js +18 -3
  139. package/workspace/test-files.json +1 -0
  140. package/workspace/test-lists/home-libs.json +9 -0
  141. package/workspace/test-lists/premium-report-read.json +1 -1
  142. package/workspace/test-lists/premium-vw-agreed.json +9 -0
  143. package/workspace/test-lists/premium-vw-notes.json +1 -1
  144. package/workspace/public/pm/premium-work.js +0 -729
  145. package/workspace/public/pm/premium.js +0 -1146
@@ -1,141 +1,197 @@
1
- /* pm/premium-insights.js — the premium Insights page in the Agreed design (initiative premium-agreed-design, G1 and G2, N1 and N2).
2
- * Reads GET /api/insights-premium (lib/insights-premium.js: the KR metric records as goals, the board's initiatives that move them, the dashboards, the report
3
- * files and setups) and GET /api/board-metrics-premium for the Delivery trends tiles. One bar: the product picker, the tabs Goals, Outcomes and Library, the
4
- * view, the period and the icon tools; the floating place menu (pm/cozy-nav.js) replaces the rail.
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.
5
3
  *
6
- * Every press of the pages before it stays (briefing-premium-insights, briefing-premium-reports, insights-one-list): a saved dashboard (POST
7
- * /api/premium-dashboards/save), Pin (POST /api/premium-dashboards/pin), the report presses (POST /api/report-setups/ask | change | cancel | setup | dismiss |
8
- * pause | resume | draft), the report reader (pm/premium-report-read.js), a Delivery trends target (POST /api/board-metric-targets/save), and Edit, New chart
9
- * and Shape it, which open the chat with the item in the tab beside it. New here: New goal adds a KR metric record (POST /api/records/kr-metrics/add).
10
- * Ask why and a verdict are made in Home: they open /premium.html with the question in the box. Nothing is sent outward. */
11
- import { $, $$, esc, openDlg, popKey, closeDlg, toast, loadThread, wireRail, logHtml, turnA, ptx, pillOf, kv, setPageGaps, infoBtn } from './premium-shell.js';
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';
12
14
  import { pmPost } from './http.js';
13
15
  import { openReport } from './premium-report-read.js';
14
- import * as MT from './premium-metric-tiles.js';
15
- import { W, P, X, Y, tileHtml } from './premium-chart-draw.js';
16
16
  import { mountNav } from './cozy-nav.js';
17
17
 
18
18
  let M = null; // the model
19
+ let BM = null, bmErr = ''; // the Board measures (Delivery trends)
19
20
  let dash = null; // the view: a dashboard id; 'all' is every goal
20
21
  let tab = 'goals';
21
22
  let listF = 'all'; // the Library filter
22
- let per = null; // the period { key, label, sub, from, to }
23
- let find = '', filt = { obj: null, type: null };
24
- let selecting = false; const picked = new Set();
25
- let sugOpen = false;
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
26
27
  wireRail('rep');
27
28
  mountNav('insights');
29
+
28
30
  const SV = (d, sw) => `<svg viewBox="0 0 24 24" aria-hidden="true"${sw ? ` stroke-width="${sw}"` : ''}><path d="${d}"/></svg>`;
29
- const DOCI = 'M6 3h9l4 4v14H6zM14 3v5h5M9 13h6M9 17h4';
30
- const PINI = 'M9 3h6l-1 6 4 3v2H6v-2l4-3zM12 14v7';
31
- const CHK = 'M5 12l5 5 9-10';
32
- const byKey = (k) => (M && (M.charts || []).concat(M.mine || []) || []).find((c) => c.key === k) || null;
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;
33
38
  const savedDash = () => (M.dashboards || []).filter((d) => d.saved);
34
39
  const wsQ = () => (M && M.board.ws ? 'ws=' + encodeURIComponent(M.board.ws) + '&' : '');
35
- /** Home with a question in the box (PRD decision: Ask lands in Home). */
36
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>`;
47
+
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
+ } });
64
+ }
37
65
 
38
- /* ── small menus: one open at a time, Escape and an outside press close it ─────────────────────────────────────────────────────────────── */
39
- const MENUS = [['#prodPick', '#prodMenu'], ['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#newB', '#newMenu'], ['#helpB', '#helpPop'], ['#listNew', '#listMenu'], ['#dashMore', '#dashBar']];
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']];
40
68
  function menu(btn, box, open) { $(box).hidden = !open; $(btn).setAttribute('aria-expanded', String(open)); }
41
- function closeMenus(except) { for (const [b, m] of MENUS) if (m !== except && !$(m).hidden) menu(b, m, false); }
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; }
42
70
  for (const [b, m] of MENUS) {
43
71
  $(b).addEventListener('click', (e) => {
44
72
  e.stopPropagation(); const open = $(m).hidden; closeMenus(m); menu(b, m, open);
45
73
  if (open) { const f = $(m).querySelector('button:not([disabled]), input, a'); if (f) f.focus(); }
46
74
  });
47
75
  }
48
- document.addEventListener('click', (e) => { for (const [b, m] of MENUS) if (!$(m).hidden && !e.target.closest(m) && !e.target.closest(b)) menu(b, m, false); });
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
+ });
49
80
  document.addEventListener('keydown', (e) => {
50
81
  if (e.key !== 'Escape') return;
51
82
  for (const [b, m] of MENUS) if (!$(m).hidden) { menu(b, m, false); $(b).focus(); return; }
52
- if (!$('#side').hidden && !$('#dlg').classList.contains('on')) closeSide();
83
+ const om = $('#ngObjMenu'); if (om && !om.hidden) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); $('#ngObjB').focus(); return; }
84
+ if (!$('#side').hidden) closeSide();
85
+ });
86
+
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
+ ];
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();
53
138
  });
54
139
 
55
- /* ── the bar: product, tabs, view, period, filter, find ────────────────────────────────────────────────────────────────────────────────── */
140
+ /* ── the bar: product, tabs, view, filter, find, ⋯ ─────────────────────────────────────────────────────────────────────────────── */
141
+ const curDash = () => M.dashboards.find((d) => d.id === dash) || M.dashboards[0];
142
+ const dashName = (D) => (D.id === 'all' ? 'All goals' : D.name);
56
143
  function drawBar() {
57
144
  $('#prodName').textContent = M.board.name || 'Insights';
58
145
  const boards = M.board.switcher || [];
59
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('')
60
- : '<p class="note">One product is registered.</p>';
147
+ : '<p class="note ins-mnote">One product is registered.</p>';
61
148
  $('#nGoals').textContent = String(goalsShown().length);
62
- $('#nOutcomes').textContent = String((M.outcomes || []).length);
149
+ $('#nOutcomes').textContent = String(outcomesShown().length);
63
150
  const D = curDash();
64
- $('#viewName').textContent = D.id === 'all' ? 'All goals' : D.name;
65
- $('#viewMenu').innerHTML = M.dashboards.map((d) => `<button type="button" role="menuitemradio" aria-checked="${d.id === D.id}" data-view="${esc(d.id)}">${esc(d.id === 'all' ? 'All goals' : d.name)}<small>${d.id === 'all' ? 'Every goal and budget' : d.saved ? 'Saved dashboard · ' + d.charts.length + ' goals' : 'Objective'}${M.pinned === d.id ? ' · pinned' : ''}</small></button>`).join('');
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('');
66
153
  drawPeriod(); drawFilter();
67
154
  }
68
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)); });
69
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 : ''); };
70
158
  function setTab(t) {
71
159
  tab = t;
72
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; }
73
161
  $('#pGoals').hidden = t !== 'goals'; $('#pOutcomes').hidden = t !== 'outcomes'; $('#pLibrary').hidden = t !== 'library';
74
162
  for (const x of $$('.ins-vw')) x.hidden = t !== 'goals';
75
163
  document.body.dataset.tab = t;
164
+ if (M) drawPeriod(); // the period chip says "shipped or judged" on Outcomes
76
165
  try { history.replaceState(null, '', setQ({ tab: t === 'goals' ? null : t })); } catch { /* no history */ }
77
166
  }
78
- 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 : ''); };
79
167
  $('.ins-tabs').addEventListener('click', (e) => { const b = e.target.closest('[role="tab"]'); if (b) setTab(b.dataset.tab); });
80
168
  $('.ins-tabs').addEventListener('keydown', (e) => {
81
169
  if (!/^Arrow(Left|Right)$/.test(e.key)) return;
82
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];
83
171
  setTab(n.dataset.tab); n.focus();
84
172
  });
85
- function setView(id) { dash = id; setTab('goals'); drawGoals(); drawDash(); drawBar(); drawList(); }
173
+ function setView(id) { dash = id; setTab('goals'); redraw(); }
86
174
 
87
- /* the period (AgInsPeriod): this quarter, last quarter, this half, this year, or custom dates. A goal shows when its period overlaps the one picked. */
88
- const MON = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
89
- 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; };
90
- const iso = (t) => new Date(t).toISOString().slice(0, 10);
91
- const md = (t) => { const d = new Date(t); return MON[d.getUTCMonth()] + ' ' + d.getUTCDate(); };
92
- function periods() {
93
- const t = day(M.today) || Date.now(), d = new Date(t), y = d.getUTCFullYear(), q = Math.floor(d.getUTCMonth() / 3), h = d.getUTCMonth() < 6 ? 0 : 1;
94
- const span = (y0, m0, y1, m1) => ({ from: Date.UTC(y0, m0, 1), to: Date.UTC(y1, m1, 0) });
95
- const lq = q ? { y, q: q - 1 } : { y: y - 1, q: 3 };
96
- return [
97
- Object.assign({ key: 'q', label: 'Q' + (q + 1) + ' ' + y, name: 'This quarter' }, span(y, q * 3, y, q * 3 + 3)),
98
- Object.assign({ key: 'lq', label: 'Q' + (lq.q + 1) + ' ' + lq.y, name: 'Last quarter' }, span(lq.y, lq.q * 3, lq.y, lq.q * 3 + 3)),
99
- Object.assign({ key: 'h', label: 'H' + (h + 1) + ' ' + y, name: 'This half' }, span(y, h * 6, y, h * 6 + 6)),
100
- Object.assign({ key: 'y', label: String(y), name: 'This year' }, span(y, 0, y + 1, 0)),
101
- ];
102
- }
103
- const inPer = (g) => {
104
- if (!per) return true;
105
- const a = day(g.fromAt) ?? day(g.byAt), b = day(g.byAt) ?? day(g.fromAt);
106
- return a === null ? true : a <= per.to && b >= per.from;
107
- };
108
- function drawPeriod() {
109
- const P = periods(); if (!per) per = P[0];
110
- const t = day(M.today) || Date.now(), total = Math.round((per.to - per.from) / 864e5) + 1, gone = Math.max(0, Math.min(total, Math.round((t - per.from) / 864e5) + 1));
111
- per.gone = gone; per.total = total;
112
- $('#perName').textContent = per.label;
113
- $('#perSub').textContent = tab === 'outcomes' ? 'shipped or judged' : md(per.from) + ' – ' + md(per.to) + (t >= per.from && t <= per.to ? ' · day ' + gone + ' of ' + total : '');
114
- const n = (p) => M.goals.filter((g) => { const o = per; per = p; const r = inPer(g); per = o; return r; }).length;
115
- $('#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(CHK) : '<i class="ins-ck"></i>'}<span>${esc(p.name + ' · ' + p.label)}<small>${esc(md(p.from) + ' – ' + md(p.to) + ' · ' + n(p) + (n(p) === 1 ? ' goal' : ' goals'))}</small></span></button>`).join('')
116
- + `<button type="button" role="menuitemradio" aria-checked="${per.key === 'c'}" data-per="c">${per.key === 'c' ? SV(CHK) : '<i class="ins-ck"></i>'}<span>Custom<small>Pick a start and end date</small></span></button>`
117
- + `<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>`
118
- + '<p class="note ins-mnote">A goal shows here when its period overlaps the one you pick. A goal with no date always shows.</p>';
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
+ };
119
185
  }
120
- $('#perMenu').addEventListener('click', (e) => {
121
- if (e.target.closest('#perGo')) {
122
- const a = day($('#perFrom').value), b = day($('#perTo').value);
123
- if (a === null || b === null || b < a) { toast('Pick a start date before the end date.'); return; }
124
- per = { key: 'c', label: 'Custom', from: a, to: b }; closeMenus(); redraw(); return;
125
- }
126
- const b = e.target.closest('[data-per]'); if (!b) return;
127
- if (b.dataset.per === 'c') { $('#perCust').hidden = false; $('#perFrom').focus(); return; }
128
- per = periods().find((p) => p.key === b.dataset.per); closeMenus(); redraw();
129
- });
130
186
  function drawFilter() {
131
- const objs = [...new Set(M.goals.map((g) => g.pillar || ''))], types = [...new Set(M.goals.map((g) => g.type))];
132
- 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(CHK) : '<i class="ins-ck"></i>'}<span>${esc(label)}</span></button>`;
133
- $('#filtMenu').innerHTML = '<p class="ins-mh">Objective</p>' + objs.map((o) => row('obj', o, o || 'No objective')).join('') + '<p class="ins-mh">Type</p>' + types.map((t) => row('type', t, t)).join('')
134
- + (filt.obj !== null || filt.type !== null ? '<button type="button" data-fclr>Clear the filter</button>' : '');
135
- $('#filtDot').hidden = filt.obj === null && filt.type === null;
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();
136
192
  }
137
193
  $('#filtMenu').addEventListener('click', (e) => {
138
- if (e.target.closest('[data-fclr]')) { filt = { obj: null, type: null }; closeMenus(); redraw(); return; }
194
+ if (e.target.closest('[data-fclr]')) { filt = { obj: null, owner: null, type: null, lane: null }; closeMenus(); redraw(); return; }
139
195
  const b = e.target.closest('[data-fk]'); if (!b) return;
140
196
  filt[b.dataset.fk] = filt[b.dataset.fk] === b.dataset.fv ? null : b.dataset.fv; redraw(); menu('#filtB', '#filtMenu', true);
141
197
  });
@@ -144,41 +200,77 @@ $('#findIn').addEventListener('input', () => { find = $('#findIn').value.trim().
144
200
  $('#findX').addEventListener('click', () => { $('#findIn').value = ''; find = ''; $('#findRow').hidden = true; $('#findB').setAttribute('aria-expanded', 'false'); redraw(); $('#findB').focus(); });
145
201
  const hit = (...s) => !find || s.some((x) => String(x || '').toLowerCase().includes(find));
146
202
 
147
- /* ── the strip: the strongest finding, and Ask why (Home) ─────────────────────────────────────────────────────────────────────────────── */
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 ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
148
229
  function drawStrip() {
149
- const I = M.insight, G = goalsShown();
230
+ const I0 = M.insight, G = goalsShown();
150
231
  const behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
151
- $('#insEye').textContent = per && per.gone && per.label !== 'Custom' ? per.gone + ' of ' + per.total + ' days gone in ' + per.label + '.' : G.length + (G.length === 1 ? ' goal' : ' goals') + (behind ? ', ' + behind + ' behind.' : '.');
152
- $('#brief').textContent = I.text;
153
- $('#insWhy').textContent = I.none ? '' : I.why || '';
154
- $('#insMore').innerHTML = (I.more || []).map((x) => `<li><button type="button" class="lk" data-open="${esc(x.chart)}" aria-haspopup="dialog">${esc(x.text)}</button></li>`).join('');
155
- $('#askWhy').href = homeAsk('insights', I.none ? 'Why is there no insight on my goals yet?' : 'Why? ' + I.text);
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);
156
236
  $('#askWhy').hidden = false;
157
237
  }
158
- $('#insHero').addEventListener('click', (e) => { const o = e.target.closest('[data-open]'); if (o) openChart(byKey(o.dataset.open)); });
159
238
 
160
- /* ── Goals (G1): the table, grouped by objective ──────────────────────────────────────────────────────────────────────────────────────── */
239
+ /* ── Goals (AgInsGoals) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── */
161
240
  const COLS = 'ins-cols';
162
- const curDash = () => M.dashboards.find((d) => d.id === dash) || M.dashboards[0];
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)); }
163
242
  function goalsShown() {
164
- const D = curDash(), ids = D.saved ? D.charts : D.id.startsWith('p:') ? null : null;
165
- return M.goals.filter((g) => inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
166
- && (filt.obj === null || (g.pillar || '') === filt.obj) && (filt.type === null || g.type === filt.type) && hit(g.title, g.pillar, ...g.moves.map((m) => m.title)));
167
- }
168
- const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok' };
169
- /** The lifecycle track: six stages and two milestones (◆); the current stage is the large dot in the initiative's status colour. */
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. */
170
251
  function trackHtml(r) {
171
- const tone = TRACK_TONE[r.status] || 'q';
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));
172
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">`
173
- + [0, 1, 2, 3, 4, 5, 6, 7].map((i) => `<i class="${[i < r.idx ? 'p' : '', i === r.idx ? 'c ' + tone : '', i === 5 || i === 7 ? 'm' : ''].filter(Boolean).join(' ')}"></i>`).join('') + '</span>';
174
- }
175
- const ST_PILL = { late: ['late', 'Late'], 'at risk': ['risk', 'At risk'], 'on hold': ['q', 'On hold'], done: ['ok', 'Done'], cancelled: ['q', 'Cancelled'], 'on track': ['q', 'On track'] };
176
- const initRow = (r) => { const p = ST_PILL[r.status]; return `<a class="ins-ini" href="/premium-initiative.html?${wsQ()}id=${encodeURIComponent(r.id)}">${trackHtml(r)}<span class="n">${esc(r.title)}</span>${p ? `<span class="cz-pill ${p[0]}">${esc(p[1])}</span>` : ''}</a>`; };
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>`; };
177
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)' };
178
- function barHtml(g) {
179
- return `<div class="ins-bar1" 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]}"></i>${g.timeGone === null ? '' : `<span class="today" title="today" style="left:${Math.round(g.timeGone * 100)}%"></span>`}</div>`;
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>`;
180
272
  }
181
- /** The so-far sparkline: the readings at their dates across the goal's span, the target as a dashed line, and the pace carried to the date, dashed. */
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. */
182
274
  function sparkHtml(g, w = 210, h = 40) {
183
275
  const c = g.key ? byKey(g.key) : null;
184
276
  if (!c) return `<span class="note">${esc(g.readings ? 'One reading, no series yet' : 'No reading yet')}</span>`;
@@ -190,391 +282,611 @@ function sparkHtml(g, w = 210, h = 40) {
190
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"/>` : '';
191
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>`;
192
284
  }
193
- const PACE_C = { ok: 'var(--cz-ok)', late: 'var(--cz-late)', q: 'var(--cz-ink3)' };
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);
305
+ }
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
+ }
194
319
  function goalRow(g) {
195
- const sel = selecting && picked.has(g.id);
196
- const sub = [g.dirTxt, g.baseTxt ? 'from ' + g.baseTxt + (g.from ? ' on ' + g.from : '') : ''].filter(Boolean).join(' · ');
197
- return `<div class="ins-tr ins-row ${COLS}${sel ? ' sel' : ''}" role="row" data-goal="${esc(g.id)}"${g.key ? ` data-open="${esc(g.key)}"` : ''} tabindex="0" aria-label="${esc(g.title)}">`
198
- + `<div class="nm" role="cell">${selecting ? `<span class="ins-cb${sel ? ' on' : ''}" role="checkbox" aria-checked="${sel}" aria-label="Select ${esc(g.title)}">${sel ? SV(CHK, 3) : ''}</span>` : ''}<span><b>${esc(g.title)}</b><small><span class="cz-pill q ins-type">${esc(g.type)}</span>${esc(sub)}</small></span></div>`
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>`
199
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>`
200
- + `<div class="spk" role="cell">${sparkHtml(g)}</div>`
324
+ + `<div class="sofar" role="cell">${soFarHtml(g)}</div>`
201
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>`
202
- + `<div class="mv" role="cell">${g.moves.length ? g.moves.slice(0, 3).map(initRow).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>`
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>`
203
327
  + '</div>';
204
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
+ };
205
349
  function drawGoals() {
206
350
  const G = goalsShown(), T = $('#goalTbl');
207
- if (!M.goals.length) { T.innerHTML = `<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>` + bmHtml(); bmDraw(); return; }
208
- 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"><i class="ins-tdk"></i>today</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="p m"></i></i>Milestone</span></span></div></div>`;
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
+ }
209
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); }
210
- let i = 0;
211
- const groups = [...by.entries()].map(([k, L]) => {
212
- const scored = L.filter((g) => g.tone !== 'q'), bad = scored.filter((g) => g.tone === 'late' || g.tone === 'red').length;
213
- const pill = !scored.length ? '' : bad ? `<span class="cz-pill late">${bad} of ${L.length} behind</span>` : '<span class="cz-pill ok">on track</span>';
214
- i++;
215
- return `<div class="ins-grp" role="row"><span role="cell">${k ? 'Objective ' + i + ' · ' + esc(k) : 'No objective'}</span> <span class="q">${esc(per ? per.label : '')}</span>${pill}</div>` + L.map(goalRow).join('');
216
- }).join('');
217
- T.innerHTML = head + (G.length ? groups : `<div class="ins-empty">No goal matches${find ? ' “' + esc(find) + '”' : ''}${filt.obj !== null || filt.type !== null ? ' this filter' : ''} in ${esc(per.label)}. <button type="button" class="lk" id="goalsAll">Show every goal</button></div>`) + bmHtml();
218
- bmDraw();
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>');
219
368
  }
220
369
  $('#goalTbl').addEventListener('click', (e) => {
221
- if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; filt = { obj: null, type: null }; per = periods()[3]; redraw(); return; }
222
- if (e.target.closest('a, #bmRange, #cBm')) return;
223
- const r = e.target.closest('[data-goal]'); if (!r) return;
224
- if (selecting) { const id = r.dataset.goal; if (picked.has(id)) picked.delete(id); else picked.add(id); drawGoals(); drawSel(); if (!$('#side').hidden && sideKind === 'dash') drawDashSide(); return; }
225
- if (r.dataset.open) openChart(byKey(r.dataset.open)); else toast('This goal has fewer than two readings, so it has no chart yet.');
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);
226
375
  });
227
- $('#goalTbl').addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; const r = e.target.closest && e.target.closest('.ins-row'); if (!r || e.target !== r) return; e.preventDefault(); r.click(); });
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
+ }
228
418
 
229
- /* ── Delivery trends: the Board's measures, a tile press sets a target (initiative briefing-premium-metrics) ──────────────────────────────── */
230
- let BM = null, bmWeeks = 8, bmTimer = null, bmErr = '';
231
- const BM_KEY = 'pmos.premium.bmWeeks';
232
- try { const w = Number(localStorage.getItem(BM_KEY)); if ([8, 26, 52].includes(w)) bmWeeks = w; } catch { /* a blocked store keeps 8 weeks */ }
233
- const bmHtml = () => `<section class="ins-trends" id="cBm" aria-labelledby="hBm" hidden><div class="ins-grp" role="row"><h2 id="hBm" role="cell">Delivery trends</h2> <span class="q" id="bmCap"></span><span class="q ins-bmlead" id="bmLead" hidden></span><button type="button" class="infob" aria-controls="bmFold" aria-expanded="false" aria-label="About the Delivery trends" title="About the Delivery trends"><i aria-hidden="true">i</i></button>`
234
- + `<div class="cz-seg mper" id="bmRange" role="group" aria-label="Range"><button data-w="8" aria-pressed="true">8w</button><button data-w="26" aria-pressed="false">26w</button><button data-w="52" aria-pressed="false">52w</button></div></div>`
235
- + '<div class="ifold" id="bmFold" hidden><p class="mhint" id="bmHint"></p><p class="note" id="bmNote"></p></div><div class="bt2 ibt ins-tiles" id="bmBody"></div></section>';
236
- function bmDraw() {
237
- const card = $('#cBm'); if (!card) return;
238
- card.hidden = !M || !M.board || !M.board.ws;
239
- $$('#bmRange button').forEach((b) => b.setAttribute('aria-pressed', String(+b.dataset.w === bmWeeks)));
240
- if (!BM) {
241
- $('#bmCap').textContent = bmErr ? 'not read' : 'reading';
242
- $('#bmHint').textContent = bmErr ? 'The Board measures could not be read, so none is shown.' + (bmErr !== '1' ? ' The reason: ' + bmErr : '') : '';
243
- $('#bmLead').hidden = !bmErr; $('#bmLead').textContent = $('#bmHint').textContent; $('#bmBody').innerHTML = ''; $('#bmNote').textContent = '';
244
- return;
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 };
245
447
  }
246
- $('#bmCap').textContent = 'the Board shows today’s counts as chips · press a tile to set its target · ' + BM.header;
247
- $('#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.';
248
- $('#bmBody').style.gridTemplateColumns = 'repeat(' + Math.max(1, Math.min(6, BM.tiles.length)) + ',minmax(0,1fr))';
249
- $('#bmBody').innerHTML = BM.tiles.map(MT.tileHtml).join('');
250
- $('#bmNote').textContent = BM.note;
251
- $('#bmLead').hidden = !BM.lead; $('#bmLead').textContent = BM.lead || '';
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>`;
252
465
  }
253
466
  async function bmLoad() {
254
- clearTimeout(bmTimer);
255
- if (!M || !M.board || !M.board.ws) { bmDraw(); return; }
467
+ if (!M || !M.board || !M.board.ws) return;
256
468
  let r = null;
257
- 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; }
258
- if (!r || !r.ok || r.state !== 'ready') { BM = null; bmErr = (r && r.error) || '1'; bmDraw(); return; }
259
- BM = r.model; bmErr = ''; bmDraw();
260
- if (BM.pending) bmTimer = setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
261
- }
262
- function bmOpen(i) {
263
- const t = BM && BM.tiles[i]; if (!t) return;
264
- 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>` : '';
265
- const form = t.absent ? '<p class="note" style="margin:12px 0 0">A target can be set once this measure is counted.</p>'
266
- : `<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>
267
- <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>`;
268
- const lt = (s) => { const d = new Date(s); 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'); };
269
- 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`) : '';
270
- 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.';
271
- const say = t.absent ? `${t.label} is not shown: ${t.why}`
272
- : 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}`
273
- : `${t.label} is ${t.value}, ${t.text}.${t.change ? ' ' + t.change.txt + '.' : ''}${fetched ? ' ' + fetched + '.' : ''}${tgt}`;
274
- 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')]] : []);
275
- 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>`;
276
- 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' });
277
- $('#oMain').onchange = null;
278
- $('#oMain').onclick = async (e) => {
279
- const go = e.target.closest('#bmGo'), clr = e.target.closest('#bmClr'); if (!go && !clr) return;
280
- const target = clr ? null : $('#bmT').value.trim();
281
- if (go && target === '') { $('#bmM').textContent = 'Type a number first.'; return; }
282
- (go || clr).disabled = true; $('#bmM').textContent = 'Saving.';
283
- const res = await pmPost('/api/board-metric-targets/save', { ws: M.board.ws, key: t.key, target });
284
- (go || clr).disabled = false;
285
- if (!res || res.ok !== true) { $('#bmM').textContent = (res && res.error) || 'The target could not be saved.'; return; }
286
- closeDlg(); toast(clr ? 'The target of ' + t.label + ' is cleared.' : 'The target of ' + t.label + ' is ' + target + '.');
287
- bmLoad();
288
- };
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
289
473
  }
290
- /* the tiles are redrawn inside #goalTbl, so their presses are delegated from it */
291
- MT.wireTiles($('#goalTbl'), () => (BM ? BM.tiles : []), bmOpen);
292
- $('#goalTbl').addEventListener('click', (e) => {
293
- const b = e.target.closest('#bmRange [data-w]'); if (!b || +b.dataset.w === bmWeeks) return;
294
- bmWeeks = +b.dataset.w; try { localStorage.setItem(BM_KEY, String(bmWeeks)); } catch { /* not kept */ } bmDraw(); bmLoad();
295
- });
296
474
 
297
- /* ── the view's charts (charts live only on dashboards): the pinned one first, Pin, Edit and New chart in its ⋯ ─────────────────────────── */
298
- function chartAt(t, j) {
299
- const c = byKey(t.dataset.key); if (!c) return;
300
- const n = c.pts.length; j = j == null ? n - 1 : Math.max(0, Math.min(n - 1, j));
301
- const p = c.pts[j], last = j === n - 1;
302
- const cx = $('.cx', t), dt = $('.dt', t);
303
- cx.setAttribute('x1', X(p.fx)); cx.setAttribute('x2', X(p.fx)); dt.setAttribute('cx', X(p.fx)); dt.setAttribute('cy', Y(p.fy));
304
- t.classList.toggle('hv', !last); t.dataset.j = j;
305
- const val = last ? c.v : p.txt, cap = last ? 'on ' + c.at + (c.targetTxt ? ' · ' + c.targetTxt : '') : 'on ' + p.d + (c.targetTxt ? ' · ' + c.targetTxt : '');
306
- $('.mval', t).textContent = val; $('.mwk', t).textContent = cap;
307
- t.setAttribute('aria-label', c.title + ', ' + (last ? 'now ' : '') + val + ', ' + cap + '. Use the arrow keys to read each reading.');
308
- }
309
- const pinnable = (D) => !!M.board.id && (D.id === 'all' || D.saved);
310
- function findingsHtml(D) {
311
- const I = D.insight; if (!I || I.none) return '';
312
- const all = I.finds, F = all.filter((f) => f.chart !== M.insight.chart), also = F.length < all.length;
313
- const label = also ? 'Also on this dashboard' : 'Insight';
314
- 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></button></li>`).join('')
315
- : `<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>`;
316
- return `<div class="nfd" role="region" aria-label="${esc(label)}"><p class="label">${esc(label)}</p><ul>${rows}</ul></div>`;
317
- }
318
- function drawDash() {
319
- const D = curDash(), L = D.keys.map(byKey).filter(Boolean), isPin = M.pinned === D.id;
320
- $('#hDash').textContent = 'Charts on ' + (D.id === 'all' ? 'All goals' : D.name);
321
- $('#dashTag').textContent = isPin ? 'Pinned' : 'Not pinned';
322
- $('#dashTag').className = 'cz-pill ' + (isPin ? 'you' : 'q');
323
- $('#dashCap').textContent = L.length ? (L.length - D.off) + ' of ' + L.length + ' on their line' : '';
324
- drawDashBar(D, isPin);
325
- $('#cDash').hidden = !D.saved && !M.charts.length;
326
- if (D.saved) { drawSaved(D, L); return; }
327
- if (!M.charts.length) { $('#dashBody').innerHTML = ''; return; }
328
- const off = D.off, tot = L.length;
329
- $('#dashBody').innerHTML = findingsHtml(D)
330
- + `<p class="mhint"><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 goal, drawn at the dates of its readings. A gap between readings is left as a gap. The dashed line is the target.</p></div>`
331
- + `<div class="ngrid">${L.map(tileWrap).join('')}</div>` + (D.id === 'all' ? mineHtml() + noSeriesHtml() : '');
332
- }
333
- function drawDashBar(D, isPin) {
334
- const bar = $('#dashBar');
335
- $('#dashPurpose').textContent = D.saved ? D.purpose : D.id === 'all' ? 'Every goal of this product. PMOS makes it, so it cannot be deleted.' : 'The goals of the ' + D.name + ' objective.';
336
- $('#dashMore').hidden = !M.board.id;
337
- if (!M.board.id) { bar.innerHTML = ''; return; }
338
- const Pd = M.pinned ? M.dashboards.find((d) => d.id === M.pinned) : null;
339
- bar.innerHTML = `<p class="note pdst">${isPin ? 'Pinned: it opens first on Goals' : 'Not pinned'}</p>`
340
- + (pinnable(D) ? `<button type="button" id="pdPin" data-pin="${esc(isPin ? '' : D.id)}" aria-pressed="${isPin}">${SV(PINI)}${isPin ? 'Unpin' : 'Pin'}</button>` : '')
341
- + (Pd && !isPin ? `<button type="button" id="pdBack">Back to ${esc(Pd.name)}</button>` : '')
342
- + (D.saved ? '<button type="button" id="pdEdit" aria-haspopup="dialog">Edit</button>' : '')
343
- + (M.charts.length ? '<button type="button" id="pcNew" aria-haspopup="dialog">New chart</button>' : '');
344
- }
345
- function drawSaved(D, L) {
346
- const off = D.off, tot = L.length;
347
- 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"><p><b>${esc(g.title)}</b><br>${esc(g.why)}</p></div>`).join('')}</div>` : '';
348
- const checks = D.checks.length ? `<p class="note pdck">${D.checks.map(esc).join(' ')}</p>` : '';
349
- $('#dashBody').innerHTML = (tot ? findingsHtml(D)
350
- + `<p class="mhint"><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>`
351
- + `<div class="ngrid">${L.map(tileWrap).join('')}</div>`
352
- : '<div class="nempty"><p><b>This dashboard draws no chart yet.</b> Press Edit to add a goal with a series.</p></div>') + checks + gone;
353
- }
354
- 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>`;
355
- function mineHtml() {
356
- const L = M.mine || [], G = M.mineGone || [];
357
- if (!L.length && !G.length) return '';
358
- return `<p class="label ngl">Your charts · ${L.length + G.length}</p>` + (L.length ? `<div class="ngrid">${L.map(tileWrap).join('')}</div>` : '')
359
- + G.map((g) => `<div class="nempty" role="listitem"><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('');
360
- }
361
- function noSeriesHtml() {
362
- const N = M.noSeries; if (!N.length) return '';
363
- return `<p class="label ngl">No series recorded · ${N.length}</p><div class="dplist" role="list">${N.map((n) => `<div class="nempty" role="listitem"><p><b>${esc(n.title)}</b>${n.pillar ? ' · ' + esc(n.pillar) : ''}<br>${esc(n.why)} It is not drawn.</p></div>`).join('')}</div>`;
364
- }
365
- async function pinDash(id) {
366
- const res = await pmPost('/api/premium-dashboards/pin', { ws: M.board.ws, board: M.board.id, id: id || null });
367
- if (!res || res.ok !== true) { toast((res && res.error) || 'The pin could not be saved. Nothing changed.'); return false; }
368
- const D = M.dashboards.find((d) => d.id === id);
369
- dash = res.pinned || 'all';
370
- toast(res.pinned ? 'Pinned ' + (D ? D.name : 'the dashboard') + '. It opens first on Goals.' : 'Unpinned. All goals opens first.');
371
- await load();
372
- return true;
373
- }
374
- $('#dashBar').addEventListener('click', (e) => {
375
- const pin = e.target.closest('#pdPin'); if (pin) { pin.disabled = true; closeMenus(); pinDash(pin.dataset.pin || null); return; }
376
- if (e.target.closest('#pdBack')) { closeMenus(); setView(M.pinned); return; }
377
- if (e.target.closest('#pdEdit')) openDashEdit(curDash()); else if (e.target.closest('#pcNew')) openChartEdit(null);
378
- });
379
- /* dashboards, charts and reports are shaped in a chat (premium-reports-from-chat): ?open= opens the item beside the chat, ?say= puts a first message in the box */
380
- async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
381
- function toChat(o) {
382
- const q = new URLSearchParams(); if (M.board.ws) q.set('ws', M.board.ws);
383
- if (o.open) q.set('open', o.open); if (o.say) q.set('say', o.say);
384
- location.href = '/premium-chat.html?' + q.toString();
385
- }
386
- const openDashEdit = (D) => toChat(D ? { open: 'dashboard:' + D.id } : { say: 'Make a dashboard of ' });
387
- const openChartEdit = (id) => toChat(id ? { open: 'chart:' + id } : { say: 'Make a chart of ' });
388
- const openReportEdit = (s) => toChat(s ? { open: 'report:' + s.id } : { say: 'Make a report of ' });
389
- $('#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); });
390
- $('#dashBody').addEventListener('keydown', (e) => {
391
- const t = e.target.closest && e.target.closest('.mch'); if (!t || !/^Arrow(Left|Right)$/.test(e.key)) return;
392
- 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));
393
- });
394
- $('#dashBody').addEventListener('pointermove', (e) => {
395
- const t = e.target.closest && e.target.closest('.mch'); $$('#dashBody .mch.hv').forEach((x) => { if (x !== t) chartAt(x); });
396
- if (!t) return; const c = byKey(t.dataset.key), r = $('svg', t).getBoundingClientRect(); if (!c || !r.width) return;
397
- const fx = Math.max(0, Math.min(1, ((e.clientX - r.left) / r.width * W - P) / (W - 2 * P)));
398
- 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);
399
- });
400
- $('#dashBody').addEventListener('pointerleave', () => $$('#dashBody .mch.hv').forEach((x) => chartAt(x)));
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>`);
401
496
 
402
- /* ── Outcomes (G2): shipped work against what it promised, and the verdict ──────────────────────────────────────────────────────────────── */
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);
403
552
  const OUT_G = { verdict: 'Needs your verdict', window: 'In their window', decided: 'Decided' };
404
553
  function outRow(r) {
405
- const g = r.goal;
406
- const promise = g ? `<div class="ins-prom"><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="pt">${esc(g.title)}${g.targetTxt ? ' ' + esc((g.baseTxt ? g.baseTxt + ' → ' : '') + g.targetTxt) : ''}${g.by ? ' by ' + esc(g.by) : ''}</span>${barHtml({ done: g.done, timeGone: null, tone: g.tone })}<b style="color:${PACE_C[g.pace.tone] || 'inherit'}">${esc(g.nowTxt ? g.nowTxt + (g.targetTxt ? ' of ' + g.targetTxt : '') : 'no reading')}</b></div>`
407
- : `<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>`;
408
- const verdict = r.group === 'verdict' ? `<button type="button" class="ins-dec" data-verdict="${esc(r.id)}" aria-haspopup="dialog">${SV(CHK)}Decide</button>`
409
- : r.group === 'decided' ? `<span class="cz-pill ${r.status === 'done' ? 'ok' : 'q'}">${r.status === 'done' ? 'Done' : 'Cancelled'}</span>` : `<span class="note">${r.idx === 6 ? 'Being monitored' : 'Too early'}</span>`;
410
- return `<div class="ins-tr ins-row ins-ocols" role="row" data-ini="${esc(r.id)}"><div class="nm" role="cell"><a href="/premium-initiative.html?${wsQ()}id=${encodeURIComponent(r.id)}"><b>${esc(r.title)}</b></a>${trackHtml(r)}</div>`
411
- + `<div role="cell">${promise}</div><div role="cell" class="note">${esc(r.stageLabel ? 'In ' + r.stageLabel : '')}${r.owner ? ' · ' + esc(r.owner) : ''}</div>`
412
- + `<div role="cell" class="note">${esc(r.end ? 'Ends ' + r.end : 'No end date')}</div><div role="cell">${verdict}</div></div>`;
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>`;
413
566
  }
414
567
  function drawOutcomes() {
415
- const L = (M.outcomes || []).filter((r) => hit(r.title, r.goal && r.goal.title));
416
- const need = L.filter((r) => r.group === 'verdict');
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;
417
570
  $('#outText').innerHTML = !M.initiativesRead ? 'The board’s initiatives are not read yet, so no shipped work is listed.'
418
571
  : !L.length ? 'No initiative is past Build yet. Shipped work shows here, with what its goal promised.'
419
- : (need.length ? `<b>${esc(need[0].title)} needs your verdict.</b> ` : '') + esc(L.length + (L.length === 1 ? ' initiative is' : ' initiatives are') + ' past Build: ' + need.length + ' to decide, ' + L.filter((r) => r.group === 'window').length + ' in their window, ' + L.filter((r) => r.group === 'decided').length + ' decided.');
420
- 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">Where it is</div><div role="columnheader">Window</div><div role="columnheader">Verdict</div></div>';
421
- 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">${OUT_G[k]}</span> <span class="q">${G.length}</span></div>` + G.map(outRow).join('') : ''; }).join('');
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('');
422
575
  $('#outTbl').innerHTML = head + (groups || '<div class="ins-empty">Nothing to judge yet.</div>');
423
576
  }
424
577
  $('#outTbl').addEventListener('click', (e) => { const b = e.target.closest('[data-verdict]'); if (b) openVerdict((M.outcomes || []).find((r) => r.id === b.dataset.verdict)); });
425
578
 
426
- /* ── the side panel: New goal, New dashboard, the verdict ───────────────────────────────────────────────────────────────────────────── */
427
- let sideKind = null, sideBack = null;
579
+ /* ── the side panel: New goal, New dashboard, Edit chart and the verdict ─────────────────────────────────────────────────────────── */
580
+ let sideKind = null, sideBack = null, SIDE_GO = null;
428
581
  function openSide(o) {
429
- sideKind = o.kind; sideBack = document.activeElement;
430
- $('#sideEye').textContent = o.eye; $('#sideTitle').textContent = o.title; $('#sideTools').innerHTML = o.tools || '';
431
- $('#sideBody').innerHTML = o.body; $('#sideNote').textContent = o.note; $('#sideMsg').textContent = '';
432
- $('#sideAct').innerHTML = `<button type="button" class="ins-primary" id="sideGo">${SV(CHK)}${esc(o.go)}</button>`;
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>` : '');
433
587
  $('#side').hidden = false; document.body.classList.add('ins-sideon');
434
- const f = $('#sideBody input, #sideBody textarea, #sideBody button'); if (f) f.focus();
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 });
435
591
  }
436
592
  function closeSide() {
437
- $('#side').hidden = true; document.body.classList.remove('ins-sideon'); sideKind = null;
438
- if (selecting) { selecting = false; picked.clear(); drawGoals(); drawSel(); }
439
- if (sideBack && sideBack.focus) sideBack.focus();
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();
440
596
  }
441
597
  $('#sideX').addEventListener('click', closeSide);
442
- $('#sideAct').addEventListener('click', (e) => { if (e.target.closest('#sideGo')) (SIDE_GO[sideKind] || (() => {}))(); });
443
- const seg = (name, opts, on) => `<div class="cz-seg" 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>`;
444
- $('#sideBody').addEventListener('click', (e) => {
445
- const b = e.target.closest('[data-seg] [data-v]'); 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(); return; }
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; }
446
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; }
447
- 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); return; }
448
- const rm = e.target.closest('[data-unpick]'); if (rm) { picked.delete(rm.dataset.unpick); drawGoals(); drawSel(); drawDashSide(); }
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)); } }
449
608
  });
450
- const segVal = (name) => { const b = $(`#sideBody [data-seg="${name}"] [aria-checked="true"]`); return b ? b.dataset.v : null; };
451
- const UNIT_OF = { Percentage: '%', Duration: 'days', Amount: '$', Count: '' };
452
- function goalHint() {
453
- const ty = segVal('Type'), u = $('#ngU'); if (u && !u.dataset.touched) u.value = UNIT_OF[ty] != null ? UNIT_OF[ty] : u.value;
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;
454
618
  }
455
619
  function openNewGoal() {
456
620
  const objs = [...new Set(M.goals.map((g) => g.pillar).filter(Boolean))];
457
- const p = periods()[0];
458
- openSide({ kind: 'goal', eye: 'New goal', title: 'A goal PMOS reads on a schedule', go: 'Save goal', note: 'Initiatives can anchor to it once it is saved.',
459
- body: `<label class="ins-fl">Name<input class="ins-inp" id="ngName" maxlength="120" placeholder="For example: Partner activation"></label>`
460
- + `<label class="ins-fl">Objective<input class="ins-inp" id="ngObj" maxlength="80" list="ngObjs" placeholder="The objective it serves"><datalist id="ngObjs">${objs.map((o) => `<option value="${esc(o)}">`).join('')}</datalist></label>`
461
- + `<p class="ins-fl">Type</p>${seg('Type', ['Percentage', 'Count', 'Amount', 'Duration'], 'Percentage')}`
462
- + `<div class="ins-2"><label class="ins-fl">Baseline<input class="ins-inp" id="ngBase" inputmode="decimal" maxlength="16" placeholder="24"></label><label class="ins-fl">Target<input class="ins-inp" id="ngTgt" inputmode="decimal" maxlength="16" placeholder="50"></label></div>`
463
- + `<div class="ins-2"><label class="ins-fl">Unit<input class="ins-inp" id="ngU" maxlength="12" value="%"></label><label class="ins-fl">By<input class="ins-inp" id="ngBy" type="date" value="${esc(iso(p.to))}"></label></div>`
464
- + '<p class="note">Better is read from the baseline and the target: a target above the baseline means up is better. Readings are added where the KR metrics are kept, or by a connected source. PMOS never guesses a missing reading.</p>'
465
- + '<div class="ins-box note">A <b>Done or not</b> goal and a <b>Stay within</b> budget are not KR metrics yet. Ask for one in Home, and PMOS proposes it as a health budget or a milestone.</div>' });
466
- $('#ngU').addEventListener('input', () => { $('#ngU').dataset.touched = '1'; });
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';
467
663
  }
468
664
  async function saveGoal() {
469
- const v = (id) => $(id).value.trim(), m = $('#sideMsg');
470
- const fields = { metric: v('#ngName'), baseline: Number(v('#ngBase')), target: Number(v('#ngTgt')), by: v('#ngBy'), unit: v('#ngU'), pillar: v('#ngObj') || undefined };
471
- if (!fields.metric) { m.textContent = 'Give the goal a name.'; $('#ngName').focus(); return; }
472
- if (v('#ngBase') === '' || !Number.isFinite(fields.baseline) || v('#ngTgt') === '' || !Number.isFinite(fields.target)) { m.textContent = 'Type a number for the baseline and the target.'; return; }
473
- if (fields.baseline === fields.target) { m.textContent = 'The target must differ from the baseline.'; return; }
474
- if (!/^\d{4}-\d{2}-\d{2}$/.test(fields.by)) { m.textContent = 'Pick the date it is due.'; return; }
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 };
475
675
  $('#sideGo').disabled = true; m.textContent = 'Saving.';
476
- const res = await pmPost('/api/records/kr-metrics/add', { ws: M.board.ws, fields, why: 'New goal from Insights' });
676
+ const res = await pmPost('/api/insights-records/goal', body);
477
677
  $('#sideGo').disabled = false;
478
678
  if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The goal could not be saved. Nothing changed.'; return; }
479
- closeSide(); toast('Saved ' + fields.metric + '. It shows on Goals; it is drawn after two readings.'); await load();
480
- }
481
- function drawSel() {
482
- $('#selBar').hidden = !selecting;
483
- $('#selN').textContent = picked.size + (picked.size === 1 ? ' goal selected' : ' goals selected');
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
484
681
  }
485
- $('#selCancel').addEventListener('click', closeSide);
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)
486
686
  function openNewDash() {
487
687
  if (!M.board.id) { toast('A dashboard is saved on a board, and this workspace has none.'); return; }
488
- selecting = true; picked.clear(); setTab('goals'); drawGoals(); drawSel();
489
- 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.', body: '' });
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: '' });
490
690
  drawDashSide();
491
691
  }
492
692
  function drawDashSide() {
493
- const keep = { n: ($('#ndName') || {}).value || '', q: ($('#ndQ') || {}).value || '', pin: $('#ndPin') ? $('#ndPin').getAttribute('aria-checked') === 'true' : false };
494
- const L = [...picked].map((id) => M.goals.find((g) => g.id === id)).filter(Boolean);
495
- $('#sideBody').innerHTML = `<form class="ins-desc" id="ndAsk"><svg viewBox="0 0 24 24" aria-hidden="true"><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"/></svg><input id="ndAskIn" maxlength="300" placeholder="Or describe it, and PMOS shapes it in a chat" aria-label="Describe the dashboard"><button type="submit" class="cz-ib solid" aria-label="Describe it in a chat" title="Describe it in a chat">${SV('M12 19V5M6 11l6-6 6 6')}</button></form>`
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>`
496
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>`
497
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>`
498
- + `<p class="ins-fl">Charts <span class="q">${L.length} picked on the left</span></p>`
499
- + (L.length ? `<div class="ins-picked">${L.map((g) => `<div class="ins-pk"><b>${esc(g.title)}</b><span class="note">${esc(g.key ? 'drawn as a line' : 'no series yet')}</span><button type="button" class="cz-ib" data-unpick="${esc(g.id)}" aria-label="Take ${esc(g.title)} off" title="Take it off">${SV('M6 6l12 12M18 6L6 18')}</button></div>`).join('')}</div>` : '<p class="note">Press goals in the table to add them.</p>')
500
- + `<div class="ins-pinrow"><button type="button" class="ins-tog${keep.pin ? ' on' : ''}" role="switch" aria-checked="${keep.pin}" id="ndPin" aria-label="Pin, so it opens first"></button><span>Pin, so it opens first</span></div>`
501
- + '<p class="note">A chart’s form (line, bars, number or meter) is set on the dashboard afterwards: Edit opens it beside a chat.</p>';
502
- $('#ndAsk').addEventListener('submit', (e) => { e.preventDefault(); const t = $('#ndAskIn').value.trim(); toChat({ say: 'Make a dashboard of ' + t }); });
503
- }
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;
730
+ });
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();
737
+ });
738
+ async function saveDash(body) { return pmPost('/api/premium-dashboards/save', Object.assign({ ws: M.board.ws, board: M.board.id }, body)); }
504
739
  async function saveNewDash() {
505
- const m = $('#sideMsg'), name = $('#ndName').value.trim();
740
+ const m = $('#sideMsg'), name = $('#ndName').value.trim(), purpose = $('#ndQ').value.trim();
506
741
  if (!name) { m.textContent = 'Give the dashboard a name.'; $('#ndName').focus(); return; }
507
- if (!picked.size) { m.textContent = 'Select at least one goal in the table.'; 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; }
508
744
  $('#sideGo').disabled = true; m.textContent = 'Saving.';
509
- const res = await saveDash({ name, purpose: $('#ndQ').value.trim(), charts: [...picked] });
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 });
510
747
  $('#sideGo').disabled = false;
511
748
  if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'The dashboard could not be saved. Nothing changed.'; return; }
512
- const id = res.id || (res.dashboard && res.dashboard.id) || null, pin = $('#ndPin').getAttribute('aria-checked') === 'true';
513
- closeSide(); toast('Saved ' + name + '. It shows under View and in Library.');
514
- if (pin && id) await pinDash(id); else await load();
515
- if (id) setView(id);
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
+ }
753
+
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();
516
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. */
517
830
  function openVerdict(r) {
518
831
  if (!r) return;
519
- const g = r.goal, c = g && g.key ? byKey(g.key) : null;
520
- openSide({ kind: 'verdict', eye: 'Evaluate · your verdict', title: r.title, go: 'Record verdict', note: 'Opens Home with your verdict; PMOS records the evaluation there. Nothing is sent.',
521
- tools: `<a class="cz-ib" href="/premium-initiative.html?${wsQ()}id=${encodeURIComponent(r.id)}" aria-label="Open the initiative" title="Open the initiative">${SV(DOCI)}</a>`,
522
- body: (g ? `<p class="ins-fl">${esc(g.title)} <span class="q">the goal it is anchored to</span></p>${c ? `<div class="ntw pdchart">${tileHtml(c)}</div>` : ''}<div class="ins-kv3"><span><small>Promised</small><b>${esc(g.targetTxt || '—')}${g.by ? ' by ' + esc(g.by) : ''}</b></span><span><small>So far</small><b style="color:${PACE_C[g.pace.tone] || 'inherit'}">${esc(g.nowTxt || '—')}</b></span><span><small>Pace</small><b>${esc(g.pace.head)}</b></span></div>`
523
- : '<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>')
524
- + '<p class="ins-fl">Your verdict</p><div class="ins-opts" role="radiogroup" aria-label="Your verdict">'
525
- + [['Keep', 'It stays as built. The Board moves it to Done.'], ['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.']]
526
- .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>'
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>'
527
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>' });
528
- SIDE_GO.verdict = () => {
529
- const v = ($('#sideBody .ins-opt.on') || {}).dataset || {}, learned = $('#vdLearn').value.trim();
530
- location.href = homeAsk('verdict', 'Record my verdict on ' + r.title + ' (' + r.id + '): ' + (v.vd || 'Iterate') + '.' + (learned ? ' What we learned: ' + learned : ''));
531
- };
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();
532
857
  }
533
- const SIDE_GO = { goal: saveGoal, dash: saveNewDash, verdict: () => {} };
534
858
 
535
859
  /* the + menu */
536
860
  $('#newMenu').addEventListener('click', (e) => {
537
861
  const b = e.target.closest('[data-new]'); if (!b) return; closeMenus();
538
862
  if (b.dataset.new === 'goal') openNewGoal();
539
863
  else if (b.dataset.new === 'dash') openNewDash();
540
- else if (b.dataset.new === 'chart') openChartEdit(null);
541
- else openReportEdit(null);
864
+ else { const D = curDash(), first = goalsShown().find((g) => g.key) || M.goals[0]; openChartEdit(first ? first.id : null, D); }
542
865
  });
543
866
 
544
- /* ── the help popover: what lives on Insights, and the goal types (AgInsConcepts, AgInsTypes) ─────────────────────────────────────────── */
545
- $('#helpPop').innerHTML = '<h2>What lives on Insights</h2><p class="note">Four things, each built from the one before. Only the first is data; the other three are ways of looking at it.</p><div class="ins-hc">'
546
- + [['Goal', 'A number PMOS reads on a schedule, with a target and a date: a KR metric. It shows as a row on Goals. Initiatives anchor to it.'], ['Chart', 'One goal drawn one way: line, bars, number or meter, with its target line. It lives on a dashboard.'], ['Dashboard', 'A saved view of Goals for one question. Always live, never sent. Pin one and it opens first.'], ['Report', 'A written update for an audience on a schedule. PMOS drafts each cycle; you review and issue it. Reports are made in Home and listed in Library.']]
547
- .map(([t, d]) => `<div><b>${t}</b><p>${d}</p></div>`).join('') + '</div>'
548
- + '<h3>Every goal has a type, a direction and a period</h3><div class="ins-ht">'
549
- + [['Percentage', 'Baseline, target, up or down is better.', 'Hit, or how many points short.'], ['Count', 'A target count.', 'Hit, or how many short.'], ['Amount', 'A unit (money, users, tickets), baseline, target.', 'Hit, or the gap.'], ['Duration', 'Baseline, target. Usually down is better.', 'Hit, or how far off.']]
550
- .map(([t, s, j]) => `<div><b>${t}</b><span>${s}</span><span>${j}</span></div>`).join('') + '</div>'
551
- + '<p class="note"><b>Period.</b> A goal has a start (its first reading) and an end (its date). On every goal, the bar under Now has a mark for how much of that time has gone, so ahead or behind is visible without reading a forecast.</p>';
552
-
553
- /* ── Library (G2): reports, then dashboards; asks and what PMOS found in your work ────────────────────────────────────────────────────── */
554
- let askTimer = 0;
555
- const dismissing = new Map();
556
- const ASKST = { running: ['Working', 'q'], ready: ['Proposal ready, not set up', 'you'], failed: ['Failed', 'red'] };
867
+ /* ── Library (AgInsLibrary): reports, then dashboards ───────────────────────────────────────────────────────────────────────────── */
557
868
  function reportGroups() {
558
869
  const R = M.reports, by = new Map();
559
870
  for (const f of R.missing ? [] : R.rows) { if (!by.has(f.cadence)) by.set(f.cadence, []); by.get(f.cadence).push(f); }
560
- const out = [];
561
- const shown = (fs) => fs && fs.some((x) => !x.archived);
871
+ const out = [], shown = (fs) => fs && fs.some((x) => !x.archived);
562
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 }); }
563
873
  for (const [id, fs] of by) if (shown(fs)) out.push({ kind: 'file', x: { id, name: id, setup: null, files: fs } });
564
874
  return out;
565
875
  }
566
- const dots = (fs) => `<span class="ins-dots" aria-hidden="true">${fs.slice(0, 8).reverse().map((x) => `<i class="${x.state === 'issued' ? 'is' : 'dr'}"></i>`).join('')}</span>`;
567
- 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} aria-haspopup="dialog"><span class="lic">${SV(DOCI)}</span><span class="nm"><b>${esc(name)}</b><small>${esc(sub)}</small></span><span class="note">${esc(when)}</span><span>${st}</span><span class="ins-from">${from}</span><span class="ins-act">${act}</span></button></div>`;
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>`;
568
880
  function repRow(g) {
569
- 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;
570
- const st = `${dots(live)}<small class="note">${[d ? d + ' draft' : '', i ? i + ' issued' : ''].filter(Boolean).join(' · ')}${s && !s.paused && s.next ? ' · next ' + esc(s.next) : s && s.paused ? ' · paused' : ''}</small>`;
571
- return lrow(`data-rpt="${esc(g.id)}"`, g.name, [L.lead ? '“' + L.lead + '”' : 'Latest: ' + (L.date || L.slot), s && s.audience ? s.audience : '', s && s.output ? s.output : ''].filter(Boolean).join(' · '),
572
- s && s.label ? s.label : 'No template', st, s && s.source ? `<span class="cz-pill q">${esc(s.source === 'work' ? 'Your work' : s.source)}</span>` : '', d ? '<span class="cz-pill you">Review draft</span>' : '');
573
- }
574
- const setupRow = (s) => { const L = s.latest; return lrow(`data-setup="${esc(s.id)}"`, s.name, [L && L.lead ? '“' + L.lead + '”' : L ? 'From the ' + L.date + ' file' : 'No draft is written yet', s.audience ? 'for ' + s.audience : ''].filter(Boolean).join(' · '), s.label || '',
575
- `<small class="note">${s.paused ? 'Paused' : s.drafting ? 'Drafting' : s.next ? 'First draft ' + esc(s.next) : 'Set up'}</small>`, s.source ? `<span class="cz-pill q">${esc(s.source === 'work' ? 'Your work' : s.source)}</span>` : '', '<span class="cz-pill q">Set up</span>'); };
576
- const askRow = (a) => lrow(`data-ask="${esc(a.id)}"`, a.proposal && a.proposal.name ? a.proposal.name : a.text, 'You asked: ' + a.text, a.changed ? 'Changed once' : '', `<small class="note">${esc(ASKST[a.state][0])}</small>`, '', a.state === 'ready' ? '<span class="cz-pill you">Review proposal</span>' : '');
577
- const foundRow = (f) => lrow(`data-found="${esc(f.id)}"`, f.name, f.why, f.confidence || '', `<small class="note">${f.evidence.length} ${f.evidence.length === 1 ? 'sign' : 'signs'} in your work</small>`, '', '<span class="cz-pill q">Review</span>');
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>`);
578
890
  function miniHtml(c) {
579
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];
580
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>`;
@@ -582,196 +894,108 @@ function miniHtml(c) {
582
894
  function dashCard(D) {
583
895
  const L = D.keys.map(byKey).filter(Boolean), on = M.pinned === D.id;
584
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>';
585
- const sub = D.id === 'all' ? 'Every goal · PMOS keeps it' : D.saved ? (D.purpose || D.charts.length + ' goals') : 'The goals of one objective';
586
- return `<div class="ins-dcard" role="listitem"><button type="button" class="ins-dopen" data-d="${esc(D.id)}" aria-label="Open ${esc(D.id === 'all' ? 'All goals' : D.name)} on Goals"><span class="ins-dh"><b>${esc(D.id === 'all' ? 'All goals' : D.name)}</b>${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>`
587
- + (pinnable(D) ? `<button type="button" class="cz-ib ins-pin${on ? ' on' : ''}" data-pin="${esc(D.id)}" aria-pressed="${on}" aria-label="${on ? 'Unpin' : 'Pin'} ${esc(D.name)}" title="${on ? 'Unpin' : 'Pin, so it opens first'}">${SV(PINI)}</button>` : '') + '</div>';
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>`;
588
899
  }
589
900
  function drawList() {
590
- const R = M.reports, found = (R.found || []).filter((f) => !dismissing.has(f.id) && hit(f.name, f.why)), asks = (R.asks || []).filter((a) => hit(a.text));
591
- const reps = reportGroups().filter((g) => hit(g.x.name)), dashes = M.dashboards.filter((d) => hit(d.name));
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)));
592
903
  const nRep = reps.length + asks.length;
593
904
  $('#repCap').textContent = String(nRep + dashes.length);
594
905
  const F3 = [['all', 'All', nRep + dashes.length], ['rep', 'Reports', nRep], ['dash', 'Dashboards', dashes.length]];
595
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('');
596
- $('#listF').textContent = F3.find((f) => f[0] === listF)[1];
597
- $('#sugB').hidden = !found.length;
598
- $('#sugB').innerHTML = SV('M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z') + found.length + (found.length === 1 ? ' suggestion' : ' suggestions') + ' from your work';
599
- $('#sugB').setAttribute('aria-expanded', String(sugOpen));
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');
600
909
  const empty = R.missing ? '<div class="ins-empty"><b>The report files could not be read</b>, so none is listed.</div>'
601
- : R.setupsOk === false ? '<div class="ins-empty"><b>The report setups could not be read</b>, so what PMOS found and what you set up are not 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>' : '';
602
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>';
603
- const repRows = reps.map((g) => g.kind === 'setup' ? setupRow(g.x) : repRow(g.x)).join('') + asks.map(askRow).join('');
604
- const sug = found.length && sugOpen ? `<div class="ins-sec"><h3>Found in your work</h3><span class="q">${found.length}</span></div><div class="ins-tbl" id="repFound" role="list">${found.map(foundRow).join('')}</div>` : '<span id="repFound" hidden></span>';
912
+ const repRows = reps.map((g) => (g.kind === 'setup' ? setupRow(g.x) : repRow(g.x))).join('') + asks.map(askRow).join('');
605
913
  const repBlock = listF === 'dash' ? '' : `<div class="ins-sec"><h3>Reports</h3><span class="q">${nRep} · by next due</span></div>` + empty
606
- + (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: press New, then New report.</div>' : '') + sug;
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>' : '');
607
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>`;
608
916
  $('#repBody').innerHTML = `<div id="listRows" aria-label="Dashboards and reports">${repBlock}${dashBlock}</div>`;
609
- $('#listPager').innerHTML = '';
610
- clearTimeout(askTimer);
611
- if ((R.asks || []).some((a) => a.state === 'running')) askTimer = setTimeout(load, 5000);
612
917
  }
613
918
  $('#listSeg').addEventListener('click', (e) => { const b = e.target.closest('[data-f]'); if (!b || b.dataset.f === listF) return; listF = b.dataset.f; drawList(); });
614
- $('#listF').addEventListener('click', () => { /* the chips are always shown; kept for the pages that press it */ });
615
- $('#sugB').addEventListener('click', () => { sugOpen = !sugOpen; drawList(); });
616
- $('#listMenu').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; closeMenus(); if (b.id === 'lmDash') openNewDash(); else if (b.id === 'lmRep') openReportEdit(null); });
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 */
617
921
  $('#repBody').addEventListener('click', (e) => {
618
- const pin = e.target.closest('[data-pin]');
619
- if (pin) { pin.disabled = true; pinDash(M.pinned === pin.dataset.pin ? null : pin.dataset.pin); return; }
620
- const d = e.target.closest('[data-d]');
621
- if (d) { setView(d.dataset.d); 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; }
622
923
  const rp = e.target.closest('[data-rpt]');
623
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; }
624
- const f = e.target.closest('[data-found]'), a = e.target.closest('[data-ask]'), s = e.target.closest('[data-setup]');
625
- if (f) openFound((M.reports.found || []).find((x) => x.id === f.dataset.found));
626
- else if (a) openAsk((M.reports.asks || []).find((x) => x.id === a.dataset.ask));
627
- else if (s) openSetup((M.reports.setups || []).find((x) => x.id === s.dataset.setup));
628
- });
629
- $('#repAsk').addEventListener('submit', async (e) => {
630
- e.preventDefault();
631
- const inp = $('#repAskIn'), text = inp.value.trim(), go = $('#repAskGo');
632
- if (!text) { toast('Say what the report is for, then press Ask.'); inp.focus(); return; }
633
- go.disabled = true;
634
- const res = await repPost('ask', { text });
635
- go.disabled = false;
636
- if (!res || res.ok !== true) { toast((res && res.error) || 'The request could not start.'); return; }
637
- 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);
638
927
  });
639
928
 
640
- /* ── the report dialogs: each press is one existing /api/report-setups/* route (briefing-premium-reports R2 to R4) ─────────────────────── */
641
- const repPost = (sub, body) => pmPost('/api/report-setups/' + sub, Object.assign({ ws: M.board.ws }, body));
642
- function repDlg(o) {
643
- 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',
644
- 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>` });
645
- $('#oMain').onchange = null;
646
- $('#oMain').onclick = async (e) => {
647
- const b = e.target.closest('[data-rx]'); if (!b) return;
648
- const m = $('#rxM'), fn = o.on[b.dataset.rx]; if (!fn) return;
649
- $$('#oMain [data-rx]').forEach((x) => { x.disabled = true; });
650
- const after = await fn(m, b);
651
- if (after === 'keep') { $$('#oMain [data-rx]').forEach((x) => { x.disabled = false; }); return; }
652
- if (after === 'keep-off') return;
653
- closeDlg(); await load();
654
- };
655
- }
656
- const pressFailed = (res, plain) => {
657
- const e = res && res.error ? String(res.error) : plain;
658
- if (res && res.reason) return e + ' This window is out of date. Close it; the list has been read again.';
659
- return e + ' Nothing was recorded. Press the button to try again.';
660
- };
661
- const press = (sub, body, said) => async (m) => {
662
- m.textContent = 'Recording.';
663
- const res = await repPost(sub, body);
664
- if (!res || res.ok !== true) { m.textContent = pressFailed(res, 'That did not go through.'); if (res && res.reason) load(); return 'keep'; }
665
- toast(typeof said === 'function' ? said(res) : said); return null;
666
- };
667
- 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.'); };
668
- const propHtml = (p) => p && p.rows.length ? kv(p.rows) : '<p class="note" style="margin:0">The proposal holds no fields yet.</p>';
669
- function openFound(f) {
670
- if (!f) return;
671
- repDlg({ eye: 'Found in your work', title: f.name, say: f.why + ' Set it up, or say it is not a report.',
672
- 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>`,
673
- acts: [['set', 'Set it up'], ['no', 'Not a report', 1]],
674
- on: {
675
- set: press('setup', { finding: f.id, name: f.name }, setupSaid),
676
- no: (m) => {
677
- 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);
678
- dismissing.set(f.id, t); drawList();
679
- m.innerHTML = 'Hidden. It is recorded as not a report in 5 seconds. <button class="lk" id="rxUndo">Undo</button>';
680
- $('#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; }); };
681
- return 'keep-off';
682
- },
683
- } });
684
- }
685
- function openAsk(a) {
686
- if (!a) return;
687
- if (a.state === 'running') {
688
- 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.') } });
689
- return;
690
- }
691
- if (a.state === 'failed') {
692
- 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.') } });
693
- return;
694
- }
695
- 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.',
696
- 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>`,
697
- acts: [['set', 'Set it up'], ['chg', 'Change it', 1], ['cancel', 'Cancel', 1]],
698
- on: {
699
- set: press('setup', { ask: a.id }, setupSaid),
700
- 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); },
701
- cancel: press('cancel', { id: a.id }, 'Request cancelled.'),
702
- } });
703
- }
704
- function openSetup(s) {
705
- if (!s) return;
706
- 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]];
707
- const acts = [s.paused ? ['resume', 'Resume'] : ['pause', 'Pause', 1]];
708
- if (s.fromWork && !s.paused) acts.unshift(['draft', 'Draft it now']);
709
- if (s.fromWork) acts.push(['studio', 'Shape it in a chat', 1]);
710
- 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.',
711
- 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>`,
712
- acts, on: {
713
- 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') + '.'),
714
- pause: press('pause', { id: s.id }, 'Paused. It is not drafted until you resume it.'),
715
- resume: press('resume', { id: s.id }, 'Resumed. It is drafted on its schedule again.'),
716
- studio: () => { openReportEdit(s); return 'keep-off'; },
717
- } });
718
- }
719
-
720
- /* ── the goal's dialog: its record and readings, the read-only agent beside it, and the switches that put it on a dashboard ─────────────── */
721
- 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>`; }
722
- function paneHtml(c) {
723
- const p = c.dialog.pane;
724
- 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 goal lands by its date, that is a straight line through its last four readings, carried to that date.</p></article>`;
725
- }
726
- function onDashHtml(c) {
727
- if (!M.board.id) return '';
728
- const L = savedDash();
729
- 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>`;
730
- }
731
- function openChart(c) {
732
- if (!c) return;
733
- const d = c.dialog;
734
- 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' });
735
- $('#oMain').onchange = null;
736
- $('#oMain').onclick = async (e) => {
737
- const b = e.target.closest('[data-pdsw]'); if (!b || b.disabled) return;
738
- const D = savedDash().find((x) => x.id === b.dataset.pdsw); if (!D) return;
739
- const on = D.charts.includes(c.id), charts = on ? D.charts.filter((x) => x !== c.id) : D.charts.concat(c.id);
740
- b.disabled = true; $('#pdSwM').textContent = 'Saving.';
741
- const res = await saveDash({ id: D.id, name: D.name, purpose: D.purpose, charts, main: D.main });
742
- b.disabled = false;
743
- if (!res || res.ok !== true) { $('#pdSwM').textContent = (res && res.error) || 'The dashboard could not be saved.'; return; }
744
- 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');
745
- $('#pdSwM').textContent = on ? 'Taken off ' + D.name + '.' : 'Added to ' + D.name + '.';
746
- load();
747
- };
748
- loadThread(c.key);
749
- setTimeout(() => { const b = $('#dBody'); b.scrollTop = b.scrollHeight; }, 120);
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;
938
+ }
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
+ } });
948
+ }
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
+ } });
959
+ }
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
+ } });
972
+ }
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
+ } });
750
979
  }
751
- $('#dBody').addEventListener('click', (e) => { const lt = e.target.closest('#logT'); if (lt) { const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); } });
752
980
 
753
- /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
754
- function drawDock() { $('#dN').textContent = M.dock.needs; $('#dLab').textContent = M.dock.label; $('#dNext').textContent = M.dock.next ? 'First ' + M.dock.next : 'No goal is behind its line'; }
755
- function redraw() { if (!M) return; drawBar(); drawStrip(); drawGoals(); drawDash(); drawOutcomes(); drawList(); }
981
+ /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
982
+ function redraw() { if (!M) return; drawBar(); drawStrip(); drawGoals(); drawOutcomes(); drawList(); }
756
983
  function draw() {
757
984
  if (!dash || !M.dashboards.some((d) => d.id === dash)) dash = M.pinned || 'all';
758
- $('#snap').textContent = M.header.text;
759
- $('#snap').title = 'Every figure on this page comes from a KR metric record. A goal with fewer than two readings is listed, not drawn.';
760
985
  setPageGaps(((M.header && M.header.missing) || []).length);
761
- redraw(); drawDock();
986
+ redraw();
762
987
  }
763
988
  async function load() {
764
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('&');
765
990
  let r = null, status = 0;
766
991
  try { const res = await fetch('/api/insights-premium' + (q ? '?' + q : ''), { credentials: 'same-origin' }); status = res.status; r = await res.json(); } catch { r = null; }
767
992
  if (!r || !r.ok) {
768
- $('#snap').textContent = 'The records could not be read';
769
993
  $('#insEye').textContent = ''; $('#insWhy').textContent = ''; $('#askWhy').hidden = true;
770
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.');
771
995
  setTimeout(load, 15000);
772
996
  return;
773
997
  }
774
- M = r.model; draw(); bmLoad();
998
+ const first = !M; M = r.model; draw(); if (first || !BM) bmLoad();
775
999
  }
776
- { const t = new URLSearchParams(location.search).get('tab'); if (t === 'outcomes' || t === 'library') setTab(t); else setTab('goals'); }
1000
+ { const t = new URLSearchParams(location.search).get('tab'); setTab(t === 'outcomes' || t === 'library' ? t : 'goals'); }
777
1001
  load();