create-pmos 0.427.0 → 0.429.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 (147) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/board-programs-test.js +16 -2
  7. package/workspace/briefing-premium-board-test.js +27 -22
  8. package/workspace/briefing-premium-insights-test.js +81 -60
  9. package/workspace/briefing-premium-metrics-test.js +5 -3
  10. package/workspace/briefing-premium-sources-test.js +5 -5
  11. package/workspace/briefing-premium-test.js +7 -5
  12. package/workspace/changelog.json +24 -0
  13. package/workspace/ev-everywhere-test.js +2 -2
  14. package/workspace/guide/briefing-premium.md +4 -2
  15. package/workspace/guide/home.md +34 -7
  16. package/workspace/guide/index.md +1 -0
  17. package/workspace/guide/metric-drafts.md +48 -0
  18. package/workspace/guide/programs.md +1 -0
  19. package/workspace/home-other-product-test.js +12 -2
  20. package/workspace/intel-report-ui-test.js +189 -0
  21. package/workspace/lib/board-metrics-premium.js +1 -1
  22. package/workspace/lib/headless.js +15 -2
  23. package/workspace/lib/insights-premium.js +5 -1
  24. package/workspace/lib/insights-records.js +14 -5
  25. package/workspace/lib/intel-report.js +419 -0
  26. package/workspace/lib/metric-draft-runs.js +193 -0
  27. package/workspace/lib/metric-drafts.js +231 -0
  28. package/workspace/lib/metrics-cli.js +104 -0
  29. package/workspace/lib/pmos-verbs.js +3 -0
  30. package/workspace/lib/report-setups.js +29 -13
  31. package/workspace/lib/route-modules.js +1 -0
  32. package/workspace/lib/routes-insights-premium.js +2 -2
  33. package/workspace/lib/routes-insights-records.js +13 -5
  34. package/workspace/lib/routes-meeting-material.js +22 -1
  35. package/workspace/lib/routes-metric-drafts.js +141 -0
  36. package/workspace/lib/routes-phone-day.js +13 -2
  37. package/workspace/lib/routes-report-setups.js +92 -3
  38. package/workspace/lib/routes-viewer.js +5 -2
  39. package/workspace/lib/settings-store.js +14 -0
  40. package/workspace/metric-drafts-ui-test.js +209 -0
  41. package/workspace/milestone-pins-test.js +13 -0
  42. package/workspace/milestone-suggest-test.js +10 -4
  43. package/workspace/package-lock.json +2 -2
  44. package/workspace/package.json +1 -1
  45. package/workspace/premium-board-actions-test.js +40 -13
  46. package/workspace/premium-phone-card-test.js +8 -5
  47. package/workspace/premium-rec-tab-test.js +8 -0
  48. package/workspace/premium-vw-item-test.js +7 -3
  49. package/workspace/premium-vw-jira-test.js +2 -1
  50. package/workspace/program-charter-test.js +1 -1
  51. package/workspace/program-leave-test.js +2 -2
  52. package/workspace/program-order-test.js +3 -2
  53. package/workspace/program-panel-test.js +2 -1
  54. package/workspace/public/pm/bd-acts.js +23 -29
  55. package/workspace/public/pm/bd-ini-panel.js +90 -32
  56. package/workspace/public/pm/bd-pin-card.css +4 -4
  57. package/workspace/public/pm/bd-pin-card.js +4 -1
  58. package/workspace/public/pm/bd-prog-panel.js +9 -4
  59. package/workspace/public/pm/bd-span.js +22 -12
  60. package/workspace/public/pm/cozy-aud.css +1 -1
  61. package/workspace/public/pm/cozy-board.css +256 -256
  62. package/workspace/public/pm/cozy-ev.css +45 -45
  63. package/workspace/public/pm/cozy-evmodel.js +1 -1
  64. package/workspace/public/pm/cozy-home-rows.css +23 -23
  65. package/workspace/public/pm/cozy-home.css +207 -207
  66. package/workspace/public/pm/cozy-insights.css +207 -108
  67. package/workspace/public/pm/cozy-live-pill.css +5 -5
  68. package/workspace/public/pm/cozy-mtg-present.css +23 -23
  69. package/workspace/public/pm/cozy-nav.js +1 -1
  70. package/workspace/public/pm/cozy-news.js +2 -2
  71. package/workspace/public/pm/cozy-panel.css +29 -29
  72. package/workspace/public/pm/cozy-pick.css +5 -5
  73. package/workspace/public/pm/cozy-rec-now.css +20 -20
  74. package/workspace/public/pm/cozy-rec-present.css +11 -11
  75. package/workspace/public/pm/cozy-rec-tab.css +13 -13
  76. package/workspace/public/pm/cozy-rec-tab.js +12 -3
  77. package/workspace/public/pm/cozy-settings.js +1 -1
  78. package/workspace/public/pm/cozy-steps.css +9 -9
  79. package/workspace/public/pm/cozy-today.css +107 -71
  80. package/workspace/public/pm/cozy-viewer.css +7 -7
  81. package/workspace/public/pm/cozy-viewer.js +157 -23
  82. package/workspace/public/pm/cozy-vw-mtg.css +81 -81
  83. package/workspace/public/pm/cozy-vw-rp.css +53 -53
  84. package/workspace/public/pm/cozy-vw-shell.css +34 -21
  85. package/workspace/public/pm/cozy-vw.css +117 -117
  86. package/workspace/public/pm/cozy-xv.css +11 -11
  87. package/workspace/public/pm/cozy.css +18 -15
  88. package/workspace/public/pm/hi-pop.css +82 -0
  89. package/workspace/public/pm/hi-pop.js +65 -0
  90. package/workspace/public/pm/home-app.js +83 -28
  91. package/workspace/public/pm/home-day.js +131 -26
  92. package/workspace/public/pm/home-ini.css +38 -108
  93. package/workspace/public/pm/home-ini.js +50 -68
  94. package/workspace/public/pm/home-line.css +7 -7
  95. package/workspace/public/pm/home-list.js +41 -4
  96. package/workspace/public/pm/home-phone-card.js +18 -15
  97. package/workspace/public/pm/home-today.js +18 -7
  98. package/workspace/public/pm/ini-more.js +67 -0
  99. package/workspace/public/pm/ini-view-model.js +3 -2
  100. package/workspace/public/pm/ini-view.css +104 -102
  101. package/workspace/public/pm/ini-view.js +16 -8
  102. package/workspace/public/pm/loose-props.css +13 -13
  103. package/workspace/public/pm/metric-drafts.css +82 -0
  104. package/workspace/public/pm/metric-drafts.js +165 -0
  105. package/workspace/public/pm/ms-suggest.css +8 -8
  106. package/workspace/public/pm/order-model.js +85 -0
  107. package/workspace/public/pm/ov-view.css +12 -12
  108. package/workspace/public/pm/premium-board.js +57 -11
  109. package/workspace/public/pm/premium-chart-tab.js +6 -6
  110. package/workspace/public/pm/premium-insights.js +306 -105
  111. package/workspace/public/pm/premium-report-intel.css +56 -0
  112. package/workspace/public/pm/premium-report-intel.js +232 -0
  113. package/workspace/public/pm/premium-shell.js +2 -2
  114. package/workspace/public/pm/premium-vw-file.js +2 -2
  115. package/workspace/public/pm/premium-vw-item.js +3 -1
  116. package/workspace/public/pm/premium-vw-jira.js +2 -0
  117. package/workspace/public/pm/premium.css +127 -128
  118. package/workspace/public/pm/prog-order.css +6 -6
  119. package/workspace/public/pm/prog-order.js +15 -2
  120. package/workspace/public/pm/program-charter.css +23 -23
  121. package/workspace/public/pm/rp-parts.js +2 -2
  122. package/workspace/public/pm/sort-order.css +17 -0
  123. package/workspace/public/pm/sort-order.js +108 -0
  124. package/workspace/public/pm/split-merge.css +15 -15
  125. package/workspace/public/pm/task-card.css +21 -21
  126. package/workspace/public/pm/tk-tasks.css +37 -37
  127. package/workspace/public/pm/tk-view.css +6 -6
  128. package/workspace/public/pm/tk-view.js +3 -2
  129. package/workspace/public/pm/wf-page.css +28 -28
  130. package/workspace/public/pm/wf-page.js +1 -1
  131. package/workspace/public/premium-board.html +1 -0
  132. package/workspace/public/premium-intelligence.html +82 -0
  133. package/workspace/server.js +38 -3
  134. package/workspace/skills/metric-draft.skill +47 -0
  135. package/workspace/sort-order-test.js +201 -0
  136. package/workspace/stage-card-test.js +1 -0
  137. package/workspace/task-card-test.js +1 -1
  138. package/workspace/test-lists/intel-report-ui.json +5 -0
  139. package/workspace/test-lists/intel-report.json +9 -0
  140. package/workspace/test-lists/metric-drafts-ui.json +5 -0
  141. package/workspace/test-lists/metric-drafts.json +9 -0
  142. package/workspace/test-lists/sort-order.json +6 -0
  143. package/workspace/test-lists/viewer-trail.json +5 -0
  144. package/workspace/test-run.js +3 -0
  145. package/workspace/tk-tasks-test.js +5 -3
  146. package/workspace/viewer-trail-test.js +145 -0
  147. package/workspace/public/premium-insights.html +0 -81
@@ -1,4 +1,10 @@
1
- /* pm/premium-insights.js — the premium Insights page, drawn to the Agreed design's frames (initiative premium-agreed-design): AgInsGoals, AgInsPeriod,
1
+ /* pm/premium-insights.js — Intelligence (batch 15 item 1; it was Insights): ONE page with no tabs, drawn to Iq8Overview, Iq8Suggest and Iq8Phone.
2
+ * Top to bottom: the ✦ strip (one finding at a time, its drafted move when it has one), the North Star with its inputs (KR metric records with role
3
+ * north-star, input or guardrail), what Claude drafted for this product (GET /api/metric-drafts, one ✓ to keep each), the key results grouped by
4
+ * objective with the health budgets, then "Did it work?" (to judge and in their window; a drafted verdict with ✓ Keep and Undo, POST
5
+ * /api/insights-records/verdict and /verdict-undo; decided ones fold). ⋯ holds Reports and dashboards (the old Library, in a side panel), Delivery
6
+ * trends, Sources, Export and About. The old ?tab=goals|outcomes|library links land on the matching section or panel; ?goal= and ?dash= still work.
7
+ * Before it, the premium Insights in the Agreed design's frames (initiative premium-agreed-design): AgInsGoals, AgInsPeriod,
2
8
  * AgInsNewGoal, AgInsNewDash, AgInsChart, AgInsOutcomes, AgInsVerdict, AgInsLibrary and AgInsPhone.
3
9
  *
4
10
  * 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
@@ -28,11 +34,11 @@ import * as PK from './cozy-pick.js'; // the one product picker Home, Board an
28
34
  import { openReport } from './premium-report-read.js';
29
35
  import { mountNav } from './cozy-nav.js';
30
36
  import { mountLivePill } from './cozy-live-pill.js';
37
+ import * as RI from './premium-report-intel.js'; // a report made from Intelligence (batch 15 item 4): the header icon, the ✦ proposals, the draft panel
31
38
 
32
39
  let M = null; // the model
33
40
  let BM = null, bmErr = ''; // the Board measures (Delivery trends)
34
41
  let dash = null; // the view: a dashboard id; 'all' is every goal
35
- let tab = 'goals';
36
42
  let per = null; // the period { key, label, name, from, to }
37
43
  let find = '';
38
44
  let filt = { status: [], owner: [], kind: [] }; // the Filter (IsMenus): each group holds the chips that are on
@@ -53,7 +59,7 @@ const I = {
53
59
  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',
54
60
  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',
55
61
  chart: 'M4 20V10M10 20V4M16 20v-8M22 20H2', ext: 'M14 4h6v6M20 4l-9 9M18 14v5H5V6h5', down: 'M7 10l5 5 5-5', pen: 'M4 20h4L19 9l-4-4L4 16zM13 7l4 4',
56
- pause: 'M9 5v14M15 5v14', play: 'M7 5l12 7-12 7z',
62
+ pause: 'M9 5v14M15 5v14', play: 'M7 5l12 7-12 7z', undo: 'M9 14L4 9l5-5M4 9h11a5 5 0 0 1 0 10h-3',
57
63
  };
58
64
  const byKey = (k) => (PF && PF.charts[k]) || (M && (M.charts || []).find((c) => c.key === k)) || null;
59
65
  const savedDash = () => (M.dashboards || []).filter((d) => d.saved);
@@ -78,7 +84,7 @@ const closeViewer = () => { if (window.czViewer && typeof window.czViewer.close
78
84
  // The Viewer floats over the page (XvAInsight); the page does not move for it.
79
85
 
80
86
  /* ── small menus: one open at a time, Escape and an outside press close it ─────────────────────────────────────────────────────── */
81
- const MENUS = [['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#newB', '#newMenu'], ['#moreB', '#moreMenu']];
87
+ const MENUS = [['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#moreB', '#moreMenu']];
82
88
  function menu(btn, box, open) { $(box).hidden = !open; $(btn).setAttribute('aria-expanded', String(open)); }
83
89
  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; if (!$('#findRow').hidden) closeFind(false); }
84
90
  for (const [b, m] of MENUS) {
@@ -100,7 +106,8 @@ document.addEventListener('keydown', (e) => {
100
106
  if ($('#repSheet')) { closeSheet(); return; }
101
107
  for (const [b, m] of MENUS) if (!$(m).hidden) { menu(b, m, false); $(b).focus(); return; }
102
108
  const om = $('#ngObjMenu'); if (om && !om.hidden) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); $('#ngObjB').focus(); return; }
103
- if (!$('#side').hidden) closeSide();
109
+ if (!$('#side').hidden) { closeSide(); return; }
110
+ if (!$('#libSide').hidden) closeLib(true);
104
111
  });
105
112
 
106
113
  /* ── dates and the period (AgInsPeriod) ─────────────────────────────────────────────────────────────────────────────────────────── */
@@ -131,8 +138,7 @@ function drawPeriod() {
131
138
  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));
132
139
  per.gone = t >= per.from && t <= per.to ? gone : 0; per.total = total;
133
140
  $('#perName').textContent = per.label;
134
- $('#perSub').innerHTML = tab === 'outcomes' ? `<span class="ins-perr">shipped or judged ${esc(per.said || 'in these dates')}</span>`
135
- : `<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>` : ''}`;
141
+ $('#perSub').innerHTML = `<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>` : ''}`;
136
142
  const n = (p) => M.goals.filter((g) => inPer(g, p)).length, goals = (k) => k + (k === 1 ? ' goal' : ' goals');
137
143
  /* a closed period: the goals due in it, and how many reached their target by their date (a reading on or before it) */
138
144
  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 }; };
@@ -163,14 +169,13 @@ const dashName = (D) => (D.id === 'all' ? 'All goals' : D.name);
163
169
  const nGoals = (k) => k + (k === 1 ? ' goal' : ' goals');
164
170
  function drawBar() {
165
171
  drawPick();
166
- $('#nGoals').textContent = String(dash === TRENDS ? 0 : goalsShown().length);
167
- $('#nOutcomes').textContent = String(outcomesShown().length);
168
172
  const D = curDash();
169
173
  $('#viewName').textContent = dash === TRENDS ? 'Delivery trends' : dashName(D);
170
- /* the Dashboard menu: every view, the default one marked; Delivery trends; then New dashboard */
174
+ /* View (Iq8Overview): every view, the default one marked; Delivery trends; then Pin, New dashboard and Edit chart */
171
175
  $('#viewMenu').innerHTML = '<p class="ins-mh">Dashboard</p>' + M.dashboards.map((d) => `<button type="button" role="menuitemradio" aria-checked="${dash !== TRENDS && d.id === D.id}" data-view="${esc(d.id)}" title="${esc(d.id === 'all' ? 'Every goal and budget' : d.saved ? 'Saved dashboard · ' + nGoals(d.charts.length) : 'The goals of one objective')}">${esc(dashName(d))}<span class="k">${M.pinned === d.id ? 'default' : ''}</span></button>`).join('')
172
176
  + (M.board.ws ? `<button type="button" role="menuitemradio" aria-checked="${dash === TRENDS}" data-view="${TRENDS}" title="The Board’s measures, with their targets">Delivery trends</button>` : '')
173
- + `<div class="ins-hr"></div><button type="button" role="menuitem" data-newdash>${SV(I.plus)}New dashboard</button>`;
177
+ + '<div class="ins-hr"></div>' + (dash !== TRENDS && M.board.id ? `<button type="button" role="menuitem" data-pin${M.pinned === D.id ? ' disabled' : ''}>${SV(I.pin)}${M.pinned === D.id ? 'Pinned: it opens first' : 'Pin, so it opens first'}</button>` : '')
178
+ + `<button type="button" role="menuitem" data-newdash>${SV(I.plus)}New dashboard</button><button type="button" role="menuitem" data-newchart>${SV(I.chart)}Edit chart</button>`;
174
179
  drawPeriod(); drawFilter();
175
180
  }
176
181
  /* the product chip (canvas XhpA5Pages): the same chip and list as Home's. It replaces the one-product menu and "Portfolio · all products" */
@@ -181,35 +186,39 @@ function shownPick() {
181
186
  }
182
187
  function drawPick() {
183
188
  const P = shownPick(), host = $('#prodHost');
184
- host.innerHTML = P ? PK.chipHtml(P, { id: 'prodPick', label: 'Products' }) : `<span class="ins-ttl">${esc(M.board.name || 'Insights')}</span>`;
189
+ host.innerHTML = P ? PK.chipHtml(P, { id: 'prodPick', label: 'Products' }) : `<span class="ins-ttl">${esc(M.board.name || 'Intelligence')}</span>`;
185
190
  const chip = $('#prodPick'); if (!chip) return;
186
191
  // a product's line: its goals, from what this page read (zero is silence)
187
192
  const lines = (ws) => { const n = PF ? PF.goals.filter((g) => g.ws === ws).length : ws === M.board.ws ? M.goals.length : 0; return n ? nGoals(n) : ''; };
188
- chip.onclick = (e) => { e.stopPropagation(); closeMenus(); PK.openPicker(chip, { P: shownPick(), label: 'Products', lines, note: 'One pick for Home, Board and Insights: unticking a product here also takes it off Home.', onApply: async (on) => { const r = await PK.savePick(on); if (!r.ok) toast(r.error); } }); };
193
+ chip.onclick = (e) => { e.stopPropagation(); closeMenus(); PK.openPicker(chip, { P: shownPick(), label: 'Products', lines, note: 'One pick for Home, Board and Intelligence: unticking a product here also takes it off Home.', onApply: async (on) => { const r = await PK.savePick(on); if (!r.ok) toast(r.error); } }); };
189
194
  }
190
195
  // a saved pick (this chip, or Settings): Insights opens on the ticked products, without a one-off link's ws or board
191
196
  addEventListener('pp:changed', () => { const q = new URLSearchParams(location.search); ['ws', 'board'].forEach((k) => q.delete(k)); const s = q.toString(); location.assign(location.pathname + (s ? '?' + s : '')); });
192
197
  $('#viewMenu').addEventListener('click', (e) => {
193
198
  if (e.target.closest('[data-newdash]')) { closeMenus(); openNewDash(); return; }
199
+ if (e.target.closest('[data-newchart]')) { closeMenus(); const D = curDash(), first = goalsShown().find((g) => g.key) || M.goals[0]; openChartEdit(first ? first.id : null, D); return; }
200
+ const pn = e.target.closest('[data-pin]'); if (pn) { if (pn.disabled) return; closeMenus(); pinView(); return; }
194
201
  const b = e.target.closest('[data-view]'); if (!b) return; closeMenus(); setView(b.dataset.view);
195
202
  });
196
203
  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 : ''); };
204
+ /** The old tabs are sections now (Iq8Overview): an old ?tab= link, Find or a dashboard card lands on the matching part of the one page. goals is the
205
+ * top; outcomes scrolls to "Did it work?"; library opens Reports and dashboards. An old link's tab leaves the address once it has landed. */
197
206
  function setTab(t) {
198
- tab = t;
199
- 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; }
200
- $('#pGoals').hidden = t !== 'goals'; $('#pOutcomes').hidden = t !== 'outcomes'; $('#pLibrary').hidden = t !== 'library';
201
- for (const x of $$('.ins-vw')) x.hidden = t !== 'goals';
202
- document.body.dataset.tab = t;
203
- if (M) drawPeriod(); // the period chip says "shipped or judged" on Outcomes
204
- try { history.replaceState(null, '', setQ({ tab: t === 'goals' ? null : t })); } catch { /* no history */ }
205
- }
206
- $('.ins-tabs').addEventListener('click', (e) => { const b = e.target.closest('[role="tab"]'); if (b) setTab(b.dataset.tab); });
207
- $('.ins-tabs').addEventListener('keydown', (e) => {
208
- if (!/^Arrow(Left|Right)$/.test(e.key)) return;
209
- 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];
210
- setTab(n.dataset.tab); n.focus();
207
+ if (t === 'library') openLib();
208
+ else if (t === 'outcomes') { const o = $('#pOutcomes'); if (o && !o.hidden) o.scrollIntoView({ block: 'start' }); }
209
+ if (new URLSearchParams(location.search).has('tab')) addr({ tab: null });
210
+ }
211
+ /** The address follows the goal open in the Viewer, so Back from another page comes back to it (batch 14 item 7). It goes
212
+ * through the Viewer, which writes it once the history has settled on the entry this page shows, and keeps that entry's trail. */
213
+ function addr(o) {
214
+ const u = setQ(o), V = window.czViewer;
215
+ if (V && typeof V.replaceUrl === 'function') V.replaceUrl(u); else try { history.replaceState(history.state, '', u); } catch { /* no history */ }
216
+ }
217
+ document.addEventListener('cz-viewer', (e) => {
218
+ const d = e.detail || {}, id = d.open && /^goal:/.test(d.id || '') ? d.id.slice(5) : null;
219
+ if ((new URLSearchParams(location.search).get('goal') || null) !== id) addr({ goal: id });
211
220
  });
212
- function setView(id) { dash = id; setTab('goals'); redraw(); }
221
+ function setView(id) { dash = id; closeLib(); redraw(); }
213
222
 
214
223
  /* Portfolio: the goals of the ticked products (several ticked, batch 12 item 5), each product's model read once through GET /api/insights-premium,
215
224
  * grouped by product. A goal of another product keeps its own workspace, so a reading added to it goes there. Budgets, Outcomes and Library stay
@@ -298,12 +307,20 @@ $('#findRes').addEventListener('click', (e) => {
298
307
  });
299
308
 
300
309
  /* ⋯ (IsMenus): Sources with how long ago the page read them, Export as CSV and About these numbers, each in the Viewer card */
301
- $('#moreB').addEventListener('click', () => { const m = Math.round((Date.now() - loadedAt) / 60000); $('#srcAge').textContent = !loadedAt ? '' : m < 1 ? 'read just now' : 'read ' + m + ' min ago'; });
310
+ $('#moreB').addEventListener('click', () => {
311
+ const m = Math.round((Date.now() - loadedAt) / 60000); $('#srcAge').textContent = !loadedAt ? '' : m < 1 ? 'read just now' : 'read ' + m + ' min ago';
312
+ if (!M) return;
313
+ const R = M.reports || {}, nr = reportGroups().length, nd = savedDash().length, nf = (R.found || []).length + (R.asks || []).filter((a) => a.state === 'ready').length;
314
+ $('#libSub').textContent = [nr ? nr + (nr === 1 ? ' report' : ' reports') : '', nd ? nd + (nd === 1 ? ' dashboard' : ' dashboards') : '', (R.found || []).length ? (R.found || []).length + ' found' : ''].filter(Boolean).join(' · ');
315
+ $('#libNew').innerHTML = nf ? `<span class="cz-pill you">${nf} new</span>` : ''; // zero is silence
316
+ });
302
317
  $('#moreMenu').addEventListener('click', (e) => {
303
318
  const b = e.target.closest('[data-more]'); if (!b || b.disabled) return; closeMenus();
304
- if (b.dataset.more === 'sources') viewer({ kind: 'Insights', title: 'Sources', icon: 'source', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
319
+ if (b.dataset.more === 'library') openLib();
320
+ else if (b.dataset.more === 'trends') setView(TRENDS);
321
+ else if (b.dataset.more === 'sources') viewer({ kind: 'Intelligence', title: 'Sources', icon: 'source', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
305
322
  else if (b.dataset.more === 'export') location.assign('/api/insights-records/export?' + wsQ() + (M.board.id ? 'board=' + encodeURIComponent(M.board.id) : ''));
306
- else if (b.dataset.more === 'about') viewer({ kind: 'Insights', title: 'About these numbers', icon: 'info', eye: 'Insights', render: (el) => { el.innerHTML = ABOUT; } });
323
+ else if (b.dataset.more === 'about') viewer({ kind: 'Intelligence', title: 'About these numbers', icon: 'info', eye: 'Intelligence', render: (el) => { el.innerHTML = ABOUT; } });
307
324
  });
308
325
  function sourcesHtml() {
309
326
  const miss = (M.header && M.header.missing) || [];
@@ -323,16 +340,173 @@ const ABOUT = '<div class="ins-about"><p>Every goal is a KR metric record of thi
323
340
  + '<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>'
324
341
  + '<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>';
325
342
 
326
- /* ── the strip ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
343
+ /* ── the ✦ strip (Iq8Overview): one finding at a time, said plainly with its reason; the dots page through up to three and × moves on to the
344
+ * next one. Ask why takes the finding to Home. A finding carries a drafted move only when the engine has one: then ✓ makes it and Undo takes it
345
+ * back. None has a move yet, so no ✓ is drawn rather than a press that does nothing. ── */
346
+ let insIdx = 0;
347
+ const insSkip = new Set(); // the findings put off with Not now, this visit only
348
+ function stripList() {
349
+ const I0 = M.insight || { none: true, text: '' };
350
+ if (I0.none) return [{ text: I0.text, why: I0.why || '', none: true }].concat(PF ? [] : RI.stripItems());
351
+ return [{ text: I0.text, why: I0.why || '', chart: I0.chart }].concat((I0.more || []).map((x) => ({ text: x.text, why: '', chart: x.chart })), PF ? [] : RI.stripItems());
352
+ }
327
353
  function drawStrip() {
328
- const I0 = M.insight, G = goalsShown();
329
- const behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
330
- $('#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.' : '.');
331
- if (PF) { $('#brief').textContent = 'Portfolio: ' + nGoals(G.length) + ' across ' + PF.products.length + (PF.products.length === 1 ? ' product' : ' products') + (behind ? ', ' + behind + ' behind.' : '.'); $('#insWhy').textContent = 'The insight under it is read one product at a time.'; $('#askWhy').href = homeAsk('insights', 'Which product needs me most this quarter?'); $('#askWhy').hidden = false; return; }
332
- $('#brief').textContent = I0.text;
333
- $('#insWhy').textContent = I0.none ? '' : I0.why || '';
334
- $('#askWhy').href = homeAsk('insights', I0.none ? 'Why is there no insight on my goals yet?' : 'Why? ' + I0.text);
335
- $('#askWhy').hidden = false;
354
+ const G = goalsShown(), behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
355
+ $('#insEye').textContent = ''; $('#insAct').innerHTML = ''; $('#insPg').innerHTML = '';
356
+ if (PF) { $('#brief').textContent = 'Portfolio: ' + nGoals(G.length) + ' across ' + PF.products.length + (PF.products.length === 1 ? ' product' : ' products') + (behind ? ', ' + behind + ' behind.' : '.'); $('#insWhy').textContent = 'The finding under it is read one product at a time.'; $('#askWhy').href = homeAsk('insights', 'Which product needs me most this quarter?'); $('#askWhy').hidden = false; return; }
357
+ const L = stripList(), open = L.map((f, i) => i).filter((i) => !insSkip.has(i));
358
+ if (!open.includes(insIdx)) insIdx = open.length ? open[0] : 0;
359
+ const f = L[insIdx];
360
+ $('#brief').textContent = f.text;
361
+ $('#insWhy').textContent = f.why || '';
362
+ $('#askWhy').href = homeAsk('insights', f.none ? 'Why is there no finding on my goals yet?' : 'Why? ' + f.text);
363
+ $('#askWhy').hidden = !!f.report; $('#askWhy').style.display = f.report ? 'none' : ''; // a report Claude proposes carries its own presses: See the draft, Not now, ✓ Set it up
364
+ if (f.report) $('#insAct').innerHTML = RI.stripActs(f.report);
365
+ if (open.length > 1) {
366
+ if (!f.report) $('#insAct').innerHTML = `<button type="button" class="cz-ib sm" id="insNo" aria-label="Not now" title="Not now">${SV(I.x)}</button>`;
367
+ $('#insPg').innerHTML = L.map((x, i) => `<button type="button" class="${i === insIdx ? 'on' : ''}" data-ins="${i}" aria-label="Finding ${i + 1} of ${L.length}" aria-pressed="${i === insIdx}"${insSkip.has(i) ? ' hidden' : ''}></button>`).join('');
368
+ }
369
+ }
370
+ $('#insHero').addEventListener('click', async (e) => {
371
+ if (e.target.closest('[data-rp]')) { await RI.stripPress(e); return; }
372
+ const d = e.target.closest('[data-ins]'); if (d) { insIdx = +d.dataset.ins; drawStrip(); return; }
373
+ if (e.target.closest('#insNo')) { insSkip.add(insIdx); const L = stripList(), n = L.findIndex((x, i) => i > insIdx && !insSkip.has(i)); insIdx = n >= 0 ? n : L.findIndex((x, i) => !insSkip.has(i)); drawStrip(); }
374
+ });
375
+
376
+ /* ── the North Star and its inputs (Iq8Overview): the KR metric record with role north-star, drawn as its number with the change against the
377
+ * span before it and its readings as a line; the records with role input (and guardrail) as a list beside it, each with its change over the same
378
+ * span. Every number is a reading. With no North Star the row is not drawn (zero is silence); Claude's drafts say what is missing. ── */
379
+ let nsSpan = '4';
380
+ const SPANS = [['4', '4 weeks', 28], ['12', '12 weeks', 84], ['q', 'This quarter vs last', null]];
381
+ const isOwnKr = (g) => !g.program && !g.initiative;
382
+ const nsGoal = () => (PF ? null : M.goals.find((g) => g.role === 'north-star' && isOwnKr(g)) || null);
383
+ const inputGoals = () => (PF ? [] : M.goals.filter((g) => (g.role === 'input' || g.role === 'guardrail') && isOwnKr(g)));
384
+ /** The reading at or before a day, from a goal's series; null when the series does not reach back that far. */
385
+ const atOrBefore = (g, t) => { const S = (g.series || []).filter((r) => day(r.at) <= t); return S.length ? S[S.length - 1] : null; };
386
+ /** The change of a goal over the span: the latest reading against the one a span before it (a quarter: the same day of the quarter before). */
387
+ function spanChange(g, span = nsSpan) {
388
+ const S = g.series || []; if (S.length < 2) return null;
389
+ const last = S[S.length - 1], tl = day(last.at), back = (SPANS.find((x) => x[0] === span) || SPANS[0])[2];
390
+ const t0 = back ? tl - back * DAY : (() => { const d = new Date(tl); return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - 3, d.getUTCDate()); })();
391
+ const prev = atOrBefore(g, t0); if (!prev || prev === last) return null;
392
+ const d = last.v - prev.v, pctd = prev.v ? d / Math.abs(prev.v) * 100 : null, better = d === 0 ? null : (g.direction === 'down' ? d < 0 : d > 0);
393
+ return { d, pct: pctd, prev, last, better, t0 };
394
+ }
395
+ const pctSay = (p) => (p === null ? '' : (p > 0 ? '+' : p < 0 ? '−' : '') + (Math.round(Math.abs(p) * 10) / 10) + '%');
396
+ /** The North Star's line: the readings of the span solid, the span before it dashed and laid under it, the latest a dot. Each reading has a
397
+ * title, so a hover says its value and day. */
398
+ function nsSvg(g, ch, W = 520, H = 120) {
399
+ const S = g.series || [], tl = day(S[S.length - 1].at), span = ch ? tl - ch.t0 : 28 * DAY;
400
+ const cur = S.filter((r) => day(r.at) >= tl - span), prev = S.filter((r) => day(r.at) >= tl - 2 * span && day(r.at) <= tl - span);
401
+ const ys = cur.concat(prev).map((r) => r.v), lo = Math.min(...ys), hi = Math.max(...ys), rg = hi - lo || 1, f = (n) => n.toFixed(1);
402
+ const x = (t) => 8 + (span ? (t - (tl - span)) / span : 1) * (W - 16), y = (v) => 10 + (1 - (v - lo) / rg) * (H - 26);
403
+ const path = (L, sh) => L.map((r, i) => (i ? 'L' : 'M') + f(x(day(r.at) + sh)) + ' ' + f(y(r.v))).join('');
404
+ const dots = cur.map((r) => `<circle class="pt" cx="${f(x(day(r.at)))}" cy="${f(y(r.v))}" r="3"><title>${esc(md(day(r.at)) + ' · ' + unitV(g, r.v))}</title></circle>`).join('');
405
+ const z = cur[cur.length - 1];
406
+ return `<svg class="ins-nsch" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="${esc(g.title + ': ' + cur.length + ' readings in the span' + (prev.length > 1 ? ', the span before it dashed' : ''))}">`
407
+ + (prev.length > 1 ? `<path class="pv" d="${path(prev, span)}"/>` : '') + (cur.length > 1 ? `<path class="ar" d="${path(cur, 0)}L${f(x(tl))} ${H}L${f(x(day(cur[0].at)))} ${H}Z"/><path class="ln" d="${path(cur, 0)}"/>` : '')
408
+ + dots + `<circle class="dt" cx="${f(x(day(z.at)))}" cy="${f(y(z.v))}" r="4.5"/></svg>`;
409
+ }
410
+ const RM = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
411
+ let nsCounted = false;
412
+ /** The North Star's number counts up once, on the first draw (principle 12 as amended for Intelligence: subtle, honest, reduced motion respected). */
413
+ function countUp(el, g) {
414
+ if (nsCounted || RM() || !el || g.now === null) { nsCounted = true; return; }
415
+ nsCounted = true;
416
+ const txt = g.nowTxt, m = /-?\d[\d,]*(\.\d+)?/.exec(txt); if (!m) return;
417
+ const dec = (m[1] || '').length - (m[1] ? 1 : 0), to = Number(m[0].replace(/,/g, '')), t0 = performance.now();
418
+ const step = (t) => { const k = Math.min(1, (t - t0) / 900), e = 1 - Math.pow(1 - k, 3), v = (to * e).toFixed(Math.max(0, dec)); el.textContent = txt.replace(m[0], m[0].includes(',') ? Number(v).toLocaleString('en-US', { minimumFractionDigits: dec, maximumFractionDigits: dec }) : v); if (k < 1) requestAnimationFrame(step); else el.textContent = txt; };
419
+ requestAnimationFrame(step);
420
+ }
421
+ function drawNs() {
422
+ const g = nsGoal(), box = $('#nsRow');
423
+ if (!g) { box.hidden = true; box.innerHTML = ''; return; }
424
+ const ch = spanChange(g), I0 = inputGoals(), src = srcOf(g), fr = freshOf(g);
425
+ const pill = ch && ch.pct !== null ? `<span class="cz-pill ${ch.better === null ? 'q' : ch.better ? 'ok' : 'late'}">${esc(pctSay(ch.pct))}</span><span class="note">vs ${esc(unitV(g, ch.prev.v))} ${nsSpan === 'q' ? 'last quarter, same day' : 'the previous ' + (SPANS.find((x) => x[0] === nsSpan) || SPANS[0])[1]}</span>` : '';
426
+ const card = `<div class="ins-nsc" data-goal="${esc(g.id)}"><div class="ins-nsh"><span class="ins-lbl2">North Star <span>${esc(g.title)}</span></span>`
427
+ + `<div class="cz-seg ins-seg" role="group" aria-label="Compare">${SPANS.map(([k, l]) => `<button type="button" aria-pressed="${nsSpan === k}" data-span="${k}">${esc(l)}</button>`).join('')}</div></div>`
428
+ + `<div class="ins-nsv"><button type="button" class="ins-big" data-nsopen aria-label="Open ${esc(g.title)}"><b id="nsNum">${esc(g.nowTxt || '—')}</b></button>${pill}<span class="note">${esc([src === 'Recorded' ? '' : src, fr].filter(Boolean).join(' · '))}</span></div>`
429
+ + ((g.series || []).length ? nsSvg(g, ch) : `<p class="note">${esc(nextReading(g))}</p>`) + '</div>';
430
+ const row = (x) => { const c = spanChange(x); return `<button type="button" class="ins-inr" data-goal="${esc(x.id)}"><span class="nm">${esc(x.title)}</span><span class="v"><b>${esc(x.nowTxt || '—')}</b>${c ? `<span class="${c.better === null ? 'q' : c.better ? 'up' : 'dn'}">${esc(sgn(c.d, x.unit))}</span>` : ''}</span></button>`; };
431
+ const ins = I0.filter((x) => x.role === 'input'), grd = I0.filter((x) => x.role === 'guardrail');
432
+ const side = ins.length || grd.length ? `<div class="ins-nsi">${ins.length ? `<span class="ins-lbl2">Inputs <span>what moves the North Star</span></span>${ins.map(row).join('')}` : ''}${grd.length ? `<span class="ins-lbl2">Guardrails <span>must not get worse</span></span>${grd.map(row).join('')}` : ''}</div>` : '';
433
+ box.innerHTML = card + side; box.hidden = false; box.classList.toggle('one', !side);
434
+ countUp($('#nsNum'), g);
435
+ }
436
+ $('#nsRow').addEventListener('click', (e) => {
437
+ const s = e.target.closest('[data-span]'); if (s) { nsSpan = s.dataset.span; drawNs(); return; }
438
+ if (e.target.closest('[data-nsopen]')) { const g = nsGoal(); if (g) openGoalDetail(g.id); return; }
439
+ const r = e.target.closest('.ins-inr[data-goal]'); if (r) openGoalDetail(r.dataset.goal);
440
+ });
441
+
442
+ /* ── what Claude drafted (Iq8Suggest, Iq9Draft): GET /api/metric-drafts for this product. While a run drafts, the five steps and what it read;
443
+ * once ready, each proposed metric with its Now, its Target, why that target and where it is measured, ✓ to track it and × to remove it, ✓ all for
444
+ * the rest. A ✓ writes a KR metric record (lib/routes-metric-drafts.js); Undo takes it back. Nothing drafted: the box is not drawn. ── */
445
+ let DR = null, drTimer = 0;
446
+ const DR_STEPS = ['Read', 'Shape', 'Measure', 'Target', 'Ready'];
447
+ async function draftsLoad() {
448
+ clearTimeout(drTimer);
449
+ if (!M || PF || !M.board.ws) { DR = null; drawDrafts(); return; }
450
+ let r = null;
451
+ try { const res = await fetch('/api/metric-drafts?ws=' + encodeURIComponent(M.board.ws) + '&scope=product&id=' + encodeURIComponent(M.board.ws), { credentials: 'same-origin' }); r = res.ok ? await res.json() : null; } catch { r = null; }
452
+ DR = r && r.ok ? r : null; drawDrafts();
453
+ if (DR && DR.run && DR.run.state === 'running') drTimer = setTimeout(draftsLoad, 4000);
454
+ }
455
+ const drOpen = () => (DR ? (DR.rows || []).filter((x) => x.state === 'open') : []);
456
+ function drawDrafts() {
457
+ const box = $('#draftBox'), run = DR && DR.run, rows = DR ? DR.rows || [] : [];
458
+ const busy = run && run.state === 'running';
459
+ if (!DR || (!rows.length && !busy)) { box.hidden = true; box.innerHTML = ''; return; }
460
+ const step = busy ? Math.max(0, Math.min(4, run.step || 0)) : 4, left = drOpen().length;
461
+ const steps = `<ol class="ins-drs" aria-label="Steps">${DR_STEPS.map((l, i) => `<li class="${i < step || (!busy && i === 4) ? 'dn' : i === step ? 'now' : ''}"><i>${i < step || !busy ? SV(I.chk, 3) : i + 1}</i>${l}</li>`).join('')}</ol>`;
462
+ const head = busy ? 'Drafting the metrics for ' + (DR.title || M.board.name || 'this product') + '…' : DR.head || 'I drafted metrics for ' + (DR.title || M.board.name || 'this product') + '.';
463
+ const tools = busy ? `<button type="button" class="cz-ib sm" data-dr="stop" aria-label="Stop" title="Stop">${SV(I.pause)}</button>`
464
+ : left ? `<button type="button" class="cz-ib sm solid" data-dr="keep-all" aria-label="Track all that are left" title="Track all that are left">${SV(I.chk)}</button>` : '<span class="cz-pill ok">Tracking. I check them every morning.</span>';
465
+ const reads = busy && (run.reads || []).length ? `<div class="ins-drr"><p class="ins-lbl2">What I read</p>${run.reads.map((x) => `<div class="${esc(x.state || 'done')}"><b>${esc(x.t)}</b><span class="note">${esc(x.state === 'now' ? 'Reading…' : x.f || '')}</span></div>`).join('')}</div>` : '';
466
+ let grp = '';
467
+ const body = rows.map((r) => {
468
+ const g = r.group !== grp ? `<div class="ins-grp" role="row"><span role="cell">${esc(r.group)}</span></div>` : ''; grp = r.group;
469
+ const src = r.ticket ? `<span class="cz-pill risk">${esc(r.ticket.text || (r.ticket.key + ' drafted'))}</span>` : r.source ? `<span class="note">${esc(r.source)}</span>` : '';
470
+ const act = r.state === 'open' ? `<button type="button" class="cz-ib sm" data-dr="drop" data-row="${esc(r.id)}" aria-label="Remove ${esc(r.name)}" title="Remove">${SV(I.x)}</button><button type="button" class="cz-ib sm solid" data-dr="keep" data-row="${esc(r.id)}" aria-label="Track ${esc(r.name)}" title="Track this metric">${SV(I.chk)}</button>`
471
+ : `<span class="cz-pill ${r.state === 'kept' ? 'ok' : 'q'}">${r.state === 'kept' ? 'Tracking' : 'Removed'}</span><button type="button" class="cz-ib sm" data-dr="undo" data-row="${esc(r.id)}" aria-label="Undo" title="Undo">${SV(I.undo)}</button>`;
472
+ return g + `<div class="ins-tr ins-row ins-dcols${r.state === 'dropped' ? ' gone' : ''}" role="row"><div class="nm" role="cell"><b>${esc(r.name)}</b>${r.type ? `<small><span class="cz-pill q ins-type">${esc(r.type)}</span></small>` : ''}</div>`
473
+ + `<div role="cell"><b>${esc(r.nowTxt || '—')}</b></div><div role="cell"><b>${esc(r.targetTxt || '—')}</b></div><div role="cell" class="note">${esc(r.why || '')}</div><div role="cell">${src}</div><div role="cell" class="ins-act">${act}</div></div>`;
474
+ }).join('');
475
+ const table = rows.length ? `<div class="ins-tbl"><div class="ins-tr ins-th ins-dcols" role="row"><div role="columnheader">Proposed metric <span>${left ? left + ' to review' : 'all reviewed'}</span></div><div role="columnheader">Now</div><div role="columnheader">Target</div><div role="columnheader">Why this target</div><div role="columnheader">Measured by</div><div></div></div>${body}</div>`
476
+ : '<p class="note">The metrics appear here as I find them.</p>';
477
+ box.innerHTML = `<div class="ins-drh"><span class="sp" aria-hidden="true">${SV(I.spark)}</span><div><b>${esc(head)}</b>${!busy && DR.sub ? `<span class="note">${esc(DR.sub)}</span>` : ''}</div>${tools}</div>${busy ? steps : ''}${reads}${table}${!busy && DR.src ? `<p class="note">Read: ${esc(DR.src)}</p>` : ''}`;
478
+ box.hidden = false;
479
+ }
480
+ $('#draftBox').addEventListener('click', async (e) => {
481
+ const b = e.target.closest('[data-dr]'); if (!b || b.disabled || !DR) return;
482
+ const k = b.dataset.dr, row = b.dataset.row || null, r0 = row ? (DR.rows || []).find((x) => x.id === row) : null;
483
+ b.disabled = true;
484
+ const res = await pmPost('/api/metric-drafts/' + k, Object.assign({ ws: M.board.ws, scope: 'product', id: M.board.ws }, row ? { row } : {}));
485
+ if (!res || res.ok !== true) { b.disabled = false; toast((res && res.error) || 'It could not be done. Nothing changed.'); return; }
486
+ const n = drOpen().length;
487
+ const said = k === 'keep' ? 'Tracking ' + (r0 ? r0.name : 'it') + (r0 && r0.ticket ? ' once the new event lands.' : '. I check it every morning.') : k === 'keep-all' ? 'Tracking ' + (res.kept || n) + '. I check them every morning.' : k === 'drop' ? 'Removed ' + (r0 ? r0.name : 'it') + '.' : k === 'undo' ? 'Undone.' : 'Stopped.';
488
+ toast(said, k === 'keep' || k === 'drop' ? { label: 'Undo', fn: async () => { await pmPost('/api/metric-drafts/undo', { ws: M.board.ws, scope: 'product', id: M.board.ws, row }); await load(); await draftsLoad(); } } : undefined);
489
+ await load(); await draftsLoad();
490
+ });
491
+
492
+ /* ── Reports and dashboards (⋯; the old Library tab) in a side panel: Found in your work, requests from Home, the reports, then the dashboards ── */
493
+ let libBack = null;
494
+ function openLib() {
495
+ if (!$('#side').hidden) closeSide();
496
+ libBack = document.activeElement; $('#libSide').hidden = false; document.body.classList.add('ins-sideon'); drawList(); $('#libSide').focus({ preventScroll: true });
497
+ }
498
+ function closeLib(focus) {
499
+ if ($('#libSide').hidden) return;
500
+ $('#libSide').hidden = true; if ($('#side').hidden) document.body.classList.remove('ins-sideon');
501
+ if (focus && libBack && libBack.focus && document.contains(libBack)) libBack.focus();
502
+ }
503
+ $('#libX').addEventListener('click', () => closeLib(true));
504
+ /** Pin (View): the view on screen opens first next time (POST /api/premium-dashboards/pin). */
505
+ async function pinView() {
506
+ const D = curDash(); if (!M.board.id) return;
507
+ const res = await pmPost('/api/premium-dashboards/pin', { ws: M.board.ws, board: M.board.id, id: D.id });
508
+ if (!res || res.ok !== true) { toast((res && res.error) || 'It could not be pinned. Nothing changed.'); return; }
509
+ toast('Pinned ' + dashName(D) + ': it opens first.'); await load();
336
510
  }
337
511
 
338
512
  /* ── Goals (AgInsGoals) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── */
@@ -342,10 +516,13 @@ function goalsShown() {
342
516
  if (dash === TRENDS) return [];
343
517
  if (filt.kind.length && !filt.kind.includes('goals')) return [];
344
518
  const D = PF ? M.dashboards[0] : curDash(), ids = D.saved ? D.charts : null;
345
- const L = allGoals().filter((g) => inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
519
+ const L = allGoals().filter((g) => isKr(g) && inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
346
520
  && (!filt.status.length || filt.status.includes(statusOf(g))) && ownerHit(ownersOf(g)) && hit(g.title, g.pillar, ...g.moves.map((m) => m.title)));
347
521
  return ids ? L.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)) : L;
348
522
  }
523
+ /** A key result: a KR metric record that is not the North Star, an input or a guardrail of it, nor a program's or an initiative's own measure. */
524
+ const NOT_KR = ['north-star', 'input', 'guardrail', 'program-goal', 'rollup', 'success', 'signal'];
525
+ const isKr = (g) => !NOT_KR.includes(g.role) && !g.program && !g.initiative;
349
526
  const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok', 'on hold': 'q' };
350
527
  /** 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
351
528
  * recorded as skipped (its "Skipped <stage>" warning) is a dashed ring. */
@@ -451,10 +628,10 @@ function drawGoals() {
451
628
  const G = goalsShown(), T = $('#goalTbl');
452
629
  document.body.classList.toggle('ins-trv', dash === TRENDS);
453
630
  if (dash === TRENDS) { T.innerHTML = bmHtml(true); drawCards([]); $('#goalCards').innerHTML = ''; return; }
454
- 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>`;
631
+ const head = `<div class="ins-tr ins-th ${COLS}" role="row"><div role="columnheader">Key results <span>${G.length} · ${esc(per ? per.label : '')}</span></div><div role="columnheader">Now, of target <span class="ins-lg"><span><i class="ins-tdk"></i>today</span></span></div><div role="columnheader">So far</div><div role="columnheader">By its date</div><div role="columnheader" class="ins-mvh">Moved by <span class="ins-lg"><span><i class="ins-trk"><i class="k"></i></i>Skipped</span><span><i class="ins-trk"><i class="p m"></i></i>Milestone</span></span></div></div>`;
455
632
  const D = curDash();
456
- if (!M.goals.length) {
457
- 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();
633
+ if (!M.goals.filter(isKr).length) {
634
+ T.innerHTML = '<div class="ins-empty"><b>No key result is recorded for this workspace.</b> A key result is a metric with a target and a date. Press + to add one.</div>' + budgetsHtml(D);
458
635
  drawCards([]); return;
459
636
  }
460
637
  /* by objective; Portfolio groups by product, each product's objectives said in its rows */
@@ -463,7 +640,7 @@ function drawGoals() {
463
640
  const objs = [...new Set(M.goals.map((g) => g.pillar || ''))];
464
641
  const head1 = (k) => (PF ? esc(k || 'A product') : k ? 'Objective ' + (objs.indexOf(k) + 1) + ' · ' + esc(k) : 'No objective');
465
642
  const groups = [...by.entries()].map(([k, L]) => `<div class="ins-grp" role="row"><span role="cell">${head1(k)}</span> <span class="q">${esc(per ? per.label : '')}</span>${GRP_PILL(L)}</div>` + L.map(goalRow).join('')).join('');
466
- 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();
643
+ 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);
467
644
  drawCards(G);
468
645
  }
469
646
  function budgetsHtml(D) {
@@ -546,12 +723,13 @@ function goalSummary(g) {
546
723
  const first = [now, tgt].filter(Boolean).join(', ');
547
724
  const pace = g.pace && g.pace.tone === 'late' && g.pace.head !== '—' ? g.pace.head + (g.pace.sub ? ', ' + g.pace.sub : '') + '.' : '';
548
725
  const text = [first ? first + '.' : '', sinceOf(g), pace].filter(Boolean).join(' ') || nextReading(g);
549
- return { line: st.line, tone: st.tone, right: [PF ? g.prod : '', srcOf(g) === 'Recorded' ? 'Insights' : srcOf(g), fr].filter(Boolean).join(' · '), text }; // a portfolio names the goal's product
726
+ return { line: st.line, tone: st.tone, right: [PF ? g.prod : '', srcOf(g) === 'Recorded' ? 'Intelligence' : srcOf(g), fr].filter(Boolean).join(' · '), text }; // a portfolio names the goal's product
550
727
  }
551
728
  function readingsHtml(g, o) {
552
729
  const steps = g.type === 'Done or not' && g.steps && g.steps.length, R = g.series.slice().reverse(), shown = o.more ? R : R.slice(0, 3);
553
730
  return (R.length ? `<div class="ins-th2"><span>Reading</span><span>Value</span><span>Source</span></div>` + shown.map((r) => `<div class="ins-trow ins-rd3"><span>${esc(md(day(r.at)) + ' ' + r.at.slice(0, 4))}</span><b>${esc(unitV(g, r.v))}</b><span class="note">${esc(srcOf(g))}</span></div>`).join('')
554
731
  + (R.length > shown.length ? `<div><button type="button" class="ins-btn sm ghost" data-gx="all">All ${R.length} readings</button></div>` : '') : `<p class="note">${esc(nextReading(g))}</p>`)
732
+ + (o.own && !steps && !o.adding ? `<div class="ins-trow"><span>Add a reading by hand</span><button type="button" class="cz-ib sm" data-gx="add" aria-label="Add a reading" title="Add a reading">${SV(I.plus)}</button></div>` : '')
555
733
  + (steps ? `<form class="ins-mf" data-stf><p class="ins-lbl">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-btn sm dark">Save steps</button><span class="note" data-msg role="status"></span></div></form>` : '');
556
734
  }
557
735
  const FLAG = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6 21V4M6 4h11l-2 4 2 4H6"/></svg>';
@@ -563,7 +741,8 @@ const movedHtml = (g) => (g.moves.length ? `<div class="ins-mvl">${g.moves.map(m
563
741
  function goalBodyHtml(g, o) {
564
742
  const V = window.czViewer, c = g.key ? byKey(g.key) : null, phone = isPhone(), steps = g.type === 'Done or not' && g.steps && g.steps.length;
565
743
  const chart = steps ? stepsHtml(g) : c ? detailSvg(g, c, phone ? 330 : 470, phone ? 140 : 160) : emptyTrend(g, o.own);
566
- const big = `<div class="ins-gbig">${g.nowTxt ? `<p class="ins-gnum"><b>${esc(g.nowTxt)}</b>${g.targetTxt ? `<span>target ${esc(g.targetTxt)}${g.byAt ? ' by ' + esc(md(day(g.byAt))) : ''}</span>` : ''}</p>` : ''}${chart}</div>`;
744
+ const by = g.pace && g.pace.head && g.pace.head !== '—' && g.type !== 'Done or not' ? `<span class="ins-gby">By its date <b style="color:${PACE_C[g.pace.tone]}">${esc(g.pace.head)}</b></span>` : ''; // Iq8Overview: Now, Target, By its date
745
+ const big = `<div class="ins-gbig">${g.nowTxt ? `<p class="ins-gnum"><b>${esc(g.nowTxt)}</b>${g.targetTxt ? `<span>target ${esc(g.targetTxt)}${g.byAt ? ' by ' + esc(md(day(g.byAt))) : ''}</span>` : ''}${by}</p>` : ''}${chart}</div>`;
567
746
  const form = !steps && o.adding ? `<form class="ins-mf ins-box" data-rdf><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${g.unit ? ' (' + esc(g.unit) + ')' : ''}<input class="ins-inp" name="v" inputmode="decimal" maxlength="16"></label></div><div class="ins-mact"><button type="submit" class="ins-btn sm dark">Add reading</button><button type="button" class="ins-btn sm ghost" data-gx="cancel">Cancel</button><span class="note" data-msg role="status"></span></div></form>` : '';
568
747
  const onDash = savedDash().filter((D) => D.charts.includes(g.id)).length;
569
748
  const moved = `<div class="ins-mvb"><p class="ins-mvh">Moved by${g.moves.length ? ` <span>${g.moves.length}</span>` : ''}</p>${movedHtml(g)}</div>`;
@@ -571,7 +750,8 @@ function goalBodyHtml(g, o) {
571
750
  { id: 'read', title: 'Readings', count: g.series.length, open: o.open === 'read', render: () => readingsHtml(g, o) },
572
751
  o.own && savedDash().length ? { id: 'dash', title: 'On dashboards', count: onDash, render: () => dashSwitches(g) } : null,
573
752
  ];
574
- return V.czSummary(goalSummary(g)) + form + big + moved + V.czSections(rows, { key: 'goal' }) + '<p class="note ins-gmsg" data-gmsg role="status"></p>';
753
+ const ask = `<form class="ins-askf" data-askf><input name="q" maxlength="300" autocomplete="off" placeholder="Ask about this goal" aria-label="Ask about this goal"><button type="submit" class="cz-ib sm solid" aria-label="Ask in Home" title="Ask in Home">${SV(I.up)}</button></form>`;
754
+ return V.czSummary(goalSummary(g)) + form + big + moved + V.czSections(rows, { key: 'goal' }) + '<p class="note ins-gmsg" data-gmsg role="status"></p>' + ask;
575
755
  }
576
756
  /** The goal as plain text, for Copy as text. */
577
757
  function goalText(g) {
@@ -591,8 +771,9 @@ function openGoalDetail(id, open0) {
591
771
  if (own && M.goals.some((x) => x.id === g.id)) more.push({ label: 'Edit chart', on: () => openChartEdit(g.id) });
592
772
  if (more.length) more.push({ sep: true });
593
773
  more.push({ label: 'Copy link', on: () => copyText(goalLink(g), 'Link copied.') }, { label: 'Copy as text', on: () => copyText(goalText(g), 'Copied as text.') });
774
+ const rp = own && !PF ? RI.viewerPress('goal:' + id) : null; // RfA1: a key result's panel makes a report too
594
775
  const body = vwOpen({ kind: 'Goal', title: (kr ? kr + ' · ' : '') + g.title, icon: 'goal', id: 'goal:' + id, more,
595
- discuss: true,
776
+ discuss: true, presses: rp ? [rp] : null, onPress: (act) => { if (rp && act === rp.act) rp.run(); },
596
777
  render: (el) => {
597
778
  el.classList.add('ins-vbody', 'ins-xv');
598
779
  const draw = () => { const top = el.scrollTop; el.innerHTML = goalBodyHtml(g, st); el.scrollTop = top; };
@@ -613,13 +794,15 @@ function openGoalDetail(id, open0) {
613
794
  }
614
795
  };
615
796
  el.onsubmit = async (e) => {
616
- const f = e.target; if (!f.matches('[data-rdf], [data-stf]')) return;
797
+ const f = e.target;
798
+ if (f.matches('[data-askf]')) { e.preventDefault(); const q = f.q.value.trim(); if (q) location.assign(homeAsk('goal', 'About ' + g.title + ': ' + q)); return; }
799
+ if (!f.matches('[data-rdf], [data-stf]')) return;
617
800
  e.preventDefault(); const m = f.querySelector('[data-msg]');
618
801
  if (f.matches('[data-rdf]')) {
619
802
  const v = f.v.value.trim(), at = f.at.value;
620
803
  if (!/^\d{4}-\d{2}-\d{2}$/.test(at) || v === '' || !Number.isFinite(Number(v))) { m.textContent = 'Pick a date and type a number.'; return; }
621
804
  m.textContent = 'Saving.';
622
- const res = await pmPost('/api/records/kr-metrics/reading', { ws: goalWs(g), rid: goalRid(g), at, value: Number(v), why: 'Reading from Insights' });
805
+ const res = await pmPost('/api/records/kr-metrics/reading', { ws: goalWs(g), rid: goalRid(g), at, value: Number(v), why: 'Reading from Intelligence' });
623
806
  if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'It could not be saved. Nothing changed.'; return; }
624
807
  st.adding = false; await fresh('Added the reading.');
625
808
  } else {
@@ -732,7 +915,7 @@ async function bmLoad() {
732
915
  let r = null;
733
916
  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; }
734
917
  if (!r || !r.ok || r.state !== 'ready') { BM = null; bmErr = (r && r.error) || '1'; } else { BM = r.model; bmErr = ''; }
735
- if (tab === 'goals') drawGoals();
918
+ drawGoals();
736
919
  if (BM && BM.pending) setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
737
920
  }
738
921
 
@@ -747,7 +930,7 @@ function rangeSay(ser) {
747
930
  }
748
931
  function closeTarget(focus) {
749
932
  const p = $('#tgPop'); if (!p) return; const k = tgOpen; p.remove(); tgOpen = null;
750
- if (tab === 'goals') drawGoals();
933
+ drawGoals();
751
934
  if (focus && k) { const t = $(`[data-tile="${k}"]`); if (t) t.focus(); }
752
935
  }
753
936
  function openTarget(key) {
@@ -810,14 +993,6 @@ function bulletHtml(P) {
810
993
  const col = P.state === 'met' ? 'var(--cz-dot-ok)' : P.state === 'part' ? 'var(--cz-dot-risk)' : 'var(--cz-dot-q)';
811
994
  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>`;
812
995
  }
813
- function promiseHtml(r) {
814
- const P = promiseOf(r);
815
- 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>`;
816
- const { g, moved, promised } = P, col = P.state === 'met' ? 'var(--cz-ok)' : P.state === 'part' ? 'var(--cz-risk)' : 'var(--cz-ink3)';
817
- const text = g.title + (promised !== null ? ' ' + sgn(promised, g.unit) : '') + (g.byAt ? ' by ' + md(day(g.byAt)) : '');
818
- 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);
819
- 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>`;
820
- }
821
996
  /** 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. */
822
997
  function guardOf(r) {
823
998
  const P = promiseOf(r), name = P && P.g.guardrail ? P.g.guardrail.replace(/ must not get worse$/, '') : '';
@@ -829,43 +1004,67 @@ function guardOf(r) {
829
1004
  const d = last.v - before.v, worse = gg.direction === 'down' ? d > 0 : d < 0;
830
1005
  return { name, state: worse ? 'worse' : 'held', text: (worse ? 'worse by ' : d === 0 ? 'held' : 'held, moved ') + (d === 0 ? '' : sgn(Math.abs(d), gg.unit).replace(/^\+/, '')) };
831
1006
  }
832
- /** Guardrail and overlap: the goal's guardrail, then the other initiatives that move the same goal. */
833
- function guardHtml(r) {
834
- const P = promiseOf(r), others = P ? P.g.moves.filter((m) => m.id !== r.id) : [], G = guardOf(r);
835
- 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>` : '')
836
- + (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>');
837
- }
838
- /** 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
839
- * before the window closed says the day it was judged. A verdict is due when the window closes. */
840
- 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)),
841
- 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' };
1007
+ /** A verdict is due when the outcome's window closes. */
842
1008
  const dueOf = (r) => (r && r.window && r.window.closes ? day(r.window.closes) : null);
843
- const OUT_G = { verdict: 'Needs your verdict', window: 'In their window', decided: 'Decided' };
1009
+ /** Claude's drafted verdict on a row to judge: Keep only when the readings met or beat the promise and no guardrail got worse; any other case
1010
+ * has no draft, and Decide opens the full verdict (Keep, Iterate or Stop, with what was learned). The line is the evidence said plainly. */
1011
+ function draftOf(r) {
1012
+ if (r.group !== 'verdict') return null;
1013
+ const P = promiseOf(r), G = guardOf(r);
1014
+ if (!P || P.state !== 'met' || (G && G.state === 'worse')) return null;
1015
+ const beat = P.share > 1.05, moved = sgn(P.moved, P.g.unit);
1016
+ return { verdict: 'Keep', text: (beat ? 'It beat the promise: ' : 'It met the promise: ') + moved + ' against ' + sgn(P.promised, P.g.unit) + '.' + (G && G.state === 'held' ? ' ' + G.name + ' held.' : '') };
1017
+ }
1018
+ let decOpen = false;
844
1019
  function outRow(r) {
845
- const due = dueOf(r);
846
- 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>`
847
- : 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>`
848
- : (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>')
849
- : `<span class="note">${r.idx === 6 ? (due !== null ? 'Opens ' + esc(md(due)) : 'Being monitored') : 'Too early'}</span>`; // the verdict opens when the window closes
850
- 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>`
851
- + `<div role="cell">${promiseHtml(r)}</div><div role="cell" class="ins-guard">${guardHtml(r)}</div>`
852
- + `<div role="cell">${winHtml(r)}</div><div role="cell">${verdict}</div></div>`;
853
- }
854
- function winHtml(r) {
855
- 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);
856
- 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>`;
857
- }
1020
+ const due = dueOf(r), P = promiseOf(r), dr = draftOf(r), ship = day(r.endAt);
1021
+ const promised = P ? `<b>${esc(P.g.title + (P.promised !== null ? ' ' + sgn(P.promised, P.g.unit) : ''))}</b><div class="note">${esc(P.g.byAt ? 'by ' + md(day(P.g.byAt)) : 'no date')}</div>` : `<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>`;
1022
+ const got = P ? `<span class="ins-gotw">${bulletHtml(P)}<b>${esc(P.moved === null ? 'no reading yet' : sgn(P.moved, P.g.unit))}</b></span>${guardOf(r) ? `<div class="note">${esc(guardOf(r).name + ': ' + guardOf(r).text)}</div>` : ''}` : '';
1023
+ let verdict, act = '';
1024
+ if (r.group === 'verdict') {
1025
+ verdict = dr ? `<span class="ins-dv"><span class="sp" aria-hidden="true">${SV(I.spark)}</span><span><b>${esc(dr.verdict)}.</b> ${esc(dr.text)}</span></span>` : `<span class="cz-pill you">To judge${due !== null ? ' · due ' + esc(md(due)) : ''}</span>`;
1026
+ act = `<button type="button" class="cz-ib sm" data-verdict="${esc(r.id)}" aria-haspopup="dialog" aria-label="Decide: Keep, Iterate or Stop" title="Decide">${SV(I.pen)}</button>`
1027
+ + (dr ? `<button type="button" class="cz-ib sm solid" data-keep="${esc(r.id)}" aria-label="Record the verdict: Keep" title="Record the verdict: Keep">${SV(I.chk)}</button>` : '');
1028
+ } else if (r.group === 'decided') {
1029
+ const v = r.verdict;
1030
+ verdict = v ? `<span class="cz-pill ${v.verdict === 'Stop' ? 'q' : 'ok'}">${v.verdict === 'Keep' ? SV(I.chk) + 'Kept' : v.verdict === 'Iterate' ? 'Changed' : 'Stopped'}${v.at ? ' · ' + esc(md(day(v.at))) : ''}</span><div class="note">${esc(v.learned)}</div>`
1031
+ : (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>';
1032
+ if (v && v.at === M.today) act = `<button type="button" class="cz-ib sm" data-vundo="${esc(r.id)}" aria-label="Undo the verdict" title="Undo">${SV(I.undo)}</button>`;
1033
+ } else verdict = `<span class="cz-pill q">${esc(due !== null ? 'Judged ' + md(due) : r.idx === 6 ? 'Being monitored' : 'Too early')}</span>`;
1034
+ 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><small>${esc(ship !== null ? 'shipped ' + md(ship) : 'no ship date recorded')}</small></div>`
1035
+ + `<div role="cell" class="pace">${promised}</div><div role="cell" class="pace">${got}</div><div role="cell" class="pace">${verdict}</div><div role="cell" class="ins-act">${act}</div></div>`;
1036
+ }
1037
+ /** Did it work? (Iq8Overview): only the work to judge and the work in its window; the decided ones fold under one line that counts them. The
1038
+ * section is not drawn when nothing has shipped. */
858
1039
  function drawOutcomes() {
859
- const L = outcomesShown(), need = L.filter((r) => r.group === 'verdict');
860
- 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;
861
- $('#outText').innerHTML = !M.initiativesRead ? 'The board’s initiatives are not read yet, so no shipped work is listed.'
862
- : !L.length ? 'No initiative is past Build yet. Shipped work shows here, with what its goal promised.'
863
- : (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.');
864
- 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>';
865
- 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('');
866
- $('#outTbl').innerHTML = oneNote() + head + (groups || '<div class="ins-empty">Nothing to judge yet.</div>');
867
- }
868
- $('#outTbl').addEventListener('click', (e) => { const b = e.target.closest('[data-verdict]'); if (b) openVerdict((M.outcomes || []).find((r) => r.id === b.dataset.verdict)); });
1040
+ const L = outcomesShown(), sec = $('#pOutcomes');
1041
+ const live = L.filter((r) => r.group !== 'decided'), dec = L.filter((r) => r.group === 'decided');
1042
+ if (!M.initiativesRead || (!live.length && !dec.length)) { sec.hidden = true; $('#outTbl').innerHTML = ''; return; }
1043
+ sec.hidden = false;
1044
+ const nj = live.filter((r) => r.group === 'verdict').length, nw = live.length - nj;
1045
+ const vOf = (r) => (r.verdict ? r.verdict.verdict : r.status === 'done' ? 'Keep' : 'Stop'), cnt = (k) => dec.filter((r) => vOf(r) === k).length;
1046
+ const head = `<div class="ins-tr ins-th ins-ocols" role="row"><div role="columnheader">Did it work? <span>${esc([nj ? nj + ' to judge' : '', nw ? nw + ' in window' : ''].filter(Boolean).join(' · '))}</span></div><div role="columnheader">Promised</div><div role="columnheader">Got</div><div role="columnheader">Verdict</div><div></div></div>`;
1047
+ const foot = dec.length ? `<button type="button" class="ins-foot" id="decFold" aria-expanded="${decOpen}">Decided <b>${dec.length}</b> · ${esc([cnt('Keep') + ' kept', cnt('Iterate') + ' changed', cnt('Stop') + ' stopped'].join(', '))}${SV(decOpen ? I.up : I.down)}</button>` : '';
1048
+ $('#outTbl').innerHTML = oneNote() + head + live.map(outRow).join('') + foot + (decOpen ? dec.map(outRow).join('') : '');
1049
+ }
1050
+ $('#outTbl').addEventListener('click', async (e) => {
1051
+ if (e.target.closest('#decFold')) { decOpen = !decOpen; drawOutcomes(); return; }
1052
+ const b = e.target.closest('[data-verdict]'); if (b) { openVerdict((M.outcomes || []).find((r) => r.id === b.dataset.verdict)); return; }
1053
+ const k = e.target.closest('[data-keep]');
1054
+ if (k) {
1055
+ const r = (M.outcomes || []).find((x) => x.id === k.dataset.keep), dr = r && draftOf(r); if (!dr || k.disabled) return;
1056
+ k.disabled = true;
1057
+ const res = await pmPost('/api/insights-records/verdict', { ws: M.board.ws, board: M.board.id, ini: r.id, verdict: 'Keep', learned: dr.text, goal: r.goal ? r.goal.id : null, drafted: true });
1058
+ if (!res || res.ok !== true) { k.disabled = false; toast((res && res.error) || 'The verdict could not be saved. Nothing changed.'); return; }
1059
+ toast('Kept ' + r.title + '.', { label: 'Undo', fn: () => undoVerdict(r) }); await load(); return;
1060
+ }
1061
+ const u = e.target.closest('[data-vundo]'); if (u) { const r = (M.outcomes || []).find((x) => x.id === u.dataset.vundo); if (r) undoVerdict(r); }
1062
+ });
1063
+ async function undoVerdict(r) {
1064
+ const res = await pmPost('/api/insights-records/verdict-undo', { ws: M.board.ws, board: M.board.id, ini: r.id });
1065
+ if (!res || res.ok !== true) { toast((res && res.error) || 'The verdict could not be taken back.'); return; }
1066
+ toast('Undone: ' + r.title + ' needs your verdict again.'); await load();
1067
+ }
869
1068
 
870
1069
  /* ── the side panel: New goal, New dashboard, Edit chart and the verdict ─────────────────────────────────────────────────────────── */
871
1070
  let sideKind = null, sideBack = null, SIDE_GO = null;
@@ -1147,13 +1346,8 @@ async function saveVerdict(r) {
1147
1346
  closeSide(); toast('Recorded: ' + (o ? o.dataset.vd : 'Iterate') + ' for ' + r.title + '.'); await load();
1148
1347
  }
1149
1348
 
1150
- /* the + menu */
1151
- $('#newMenu').addEventListener('click', (e) => {
1152
- const b = e.target.closest('[data-new]'); if (!b) return; closeMenus();
1153
- if (b.dataset.new === 'goal') openNewGoal();
1154
- else if (b.dataset.new === 'dash') openNewDash();
1155
- else { const D = curDash(), first = goalsShown().find((g) => g.key) || M.goals[0]; openChartEdit(first ? first.id : null, D); }
1156
- });
1349
+ /* + (Iq8Overview): a new metric or key result. New dashboard and Edit chart are in View. */
1350
+ $('#newB').addEventListener('click', (e) => { e.stopPropagation(); closeMenus(); openNewGoal(); });
1157
1351
 
1158
1352
  /* ── Library (IsLibrary; IsPhone right): what PMOS found in your work, the reports as Report · Next · Status, then the dashboards. Reports are
1159
1353
  * made in Home: New report and Change the setup hand off there. Every press posts to the console's report-setups routes
@@ -1350,9 +1544,9 @@ function openRequest(id) {
1350
1544
  }
1351
1545
 
1352
1546
  /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
1353
- function redraw() { if (!M) return; drawBar(); drawStrip(); drawGoals(); drawOutcomes(); drawList(); }
1547
+ function redraw() { if (!M) return; drawBar(); drawStrip(); drawNs(); drawGoals(); drawOutcomes(); drawList(); drawDrafts(); }
1354
1548
  function draw() {
1355
- if (!dash || !M.dashboards.some((d) => d.id === dash)) dash = M.pinned || 'all';
1549
+ if (!dash || (dash !== TRENDS && !M.dashboards.some((d) => d.id === dash))) dash = M.pinned || 'all'; // Delivery trends stays open across a reload
1356
1550
  setPageGaps(((M.header && M.header.missing) || []).length);
1357
1551
  redraw();
1358
1552
  }
@@ -1373,6 +1567,13 @@ async function load() {
1373
1567
  if (on.length > 1 && first) await openPortfolio(on, true);
1374
1568
  // A shared goal link (?goal=<id>, from "Copy link" in the goal's ⋯) opens that goal once, after the first read.
1375
1569
  if (first) { const gid = new URLSearchParams(location.search).get('goal'); if (gid && allGoals().some((g) => g.id === gid)) openGoalDetail(gid); }
1376
- }
1377
- { const t = new URLSearchParams(location.search).get('tab'); setTab(t === 'outcomes' || t === 'library' ? t : 'goals'); }
1570
+ // an old tab link (Insights had Goals, Outcomes and Library): it lands on the section or the panel, once
1571
+ if (first) { const t = new URLSearchParams(location.search).get('tab'); if (t === 'outcomes' || t === 'library') setTab(t); }
1572
+ if (first) draftsLoad();
1573
+ if (!PF) RI.loadProposals(M.board.ws, M.board.id).then(() => { if (M) drawStrip(); });
1574
+ }
1575
+ /* a report from Intelligence (batch 15 item 4): the view on screen is its first scope; a saved dashboard is its own */
1576
+ RI.mount({ model: () => (PF ? null : M), scope: () => { const D = curDash(); return D && D.saved ? 'dashboard:' + D.id : 'view'; }, viewer, close: () => closeMenus(), reload: () => load(),
1577
+ openFile: (setup, p) => { const sl = (/(\d{4}-\d{2}-\d{2})\.md$/.exec(p) || [])[1]; openReport({ cadence: setup, slot: sl, path: p, state: 'draft' }, { ws: M.board.ws, onIssue: () => load(), onChange: () => load() }); },
1578
+ toast, esc, redrawStrip: () => drawStrip() });
1378
1579
  load();