create-pmos 0.428.0 → 0.430.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 (134) hide show
  1. package/package.json +25 -25
  2. package/payload/KIT-VERSION +2 -2
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/payload/state/log.md +1 -1
  7. package/workspace/briefing-premium-board-test.js +4 -4
  8. package/workspace/briefing-premium-insights-test.js +82 -61
  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 +5 -4
  12. package/workspace/changelog.json +24 -0
  13. package/workspace/ev-everywhere-test.js +2 -2
  14. package/workspace/guide/adler.md +45 -0
  15. package/workspace/guide/briefing-premium.md +2 -0
  16. package/workspace/guide/home.md +4 -2
  17. package/workspace/guide/index.md +2 -0
  18. package/workspace/guide/metric-drafts.md +49 -0
  19. package/workspace/guide/programs.md +2 -0
  20. package/workspace/intel-report-ui-test.js +189 -0
  21. package/workspace/intelligence-gaps-ui-test.js +168 -0
  22. package/workspace/lib/board-metrics-premium.js +1 -1
  23. package/workspace/lib/headless.js +15 -2
  24. package/workspace/lib/initiative-writer.js +16 -2
  25. package/workspace/lib/insight-moves.js +135 -0
  26. package/workspace/lib/insights-premium.js +9 -4
  27. package/workspace/lib/insights-records.js +14 -5
  28. package/workspace/lib/intel-report.js +432 -0
  29. package/workspace/lib/metric-draft-runs.js +193 -0
  30. package/workspace/lib/metric-drafts.js +261 -0
  31. package/workspace/lib/metrics-cli.js +104 -0
  32. package/workspace/lib/page-opens.js +74 -0
  33. package/workspace/lib/pmos-verbs.js +3 -0
  34. package/workspace/lib/report-setups.js +29 -13
  35. package/workspace/lib/route-modules.js +3 -0
  36. package/workspace/lib/routes-insight-moves.js +119 -0
  37. package/workspace/lib/routes-insights-premium.js +12 -3
  38. package/workspace/lib/routes-insights-records.js +13 -5
  39. package/workspace/lib/routes-metric-drafts.js +150 -0
  40. package/workspace/lib/routes-page-opens.js +26 -0
  41. package/workspace/lib/routes-phone-day.js +13 -2
  42. package/workspace/lib/routes-report-setups.js +97 -3
  43. package/workspace/lib/routes-viewer.js +5 -2
  44. package/workspace/lib/settings-store.js +6 -0
  45. package/workspace/metric-drafts-ui-test.js +209 -0
  46. package/workspace/milestone-suggest-test.js +4 -4
  47. package/workspace/package-lock.json +2 -2
  48. package/workspace/package.json +1 -1
  49. package/workspace/premium-phone-card-test.js +8 -5
  50. package/workspace/premium-viewer-flicker-test.js +1 -1
  51. package/workspace/public/pm/bd-acts.js +3 -3
  52. package/workspace/public/pm/bd-pin-card.css +4 -4
  53. package/workspace/public/pm/bd-prog-panel.js +12 -7
  54. package/workspace/public/pm/bd-prog.js +2 -2
  55. package/workspace/public/pm/cozy-adler.css +82 -0
  56. package/workspace/public/pm/cozy-adler.js +270 -0
  57. package/workspace/public/pm/cozy-aud.css +1 -1
  58. package/workspace/public/pm/cozy-board.css +256 -256
  59. package/workspace/public/pm/cozy-ev.css +48 -45
  60. package/workspace/public/pm/cozy-evmodel.js +1 -1
  61. package/workspace/public/pm/cozy-home-rows.css +23 -23
  62. package/workspace/public/pm/cozy-home.css +211 -207
  63. package/workspace/public/pm/cozy-insights.css +221 -108
  64. package/workspace/public/pm/cozy-live-pill.css +5 -5
  65. package/workspace/public/pm/cozy-mtg-present.css +23 -23
  66. package/workspace/public/pm/cozy-nav.js +3 -1
  67. package/workspace/public/pm/cozy-news.js +2 -2
  68. package/workspace/public/pm/cozy-panel.css +29 -29
  69. package/workspace/public/pm/cozy-pick.css +5 -5
  70. package/workspace/public/pm/cozy-rec-now.css +20 -20
  71. package/workspace/public/pm/cozy-rec-present.css +11 -11
  72. package/workspace/public/pm/cozy-rec-tab.css +13 -13
  73. package/workspace/public/pm/cozy-search.js +4 -2
  74. package/workspace/public/pm/cozy-settings.js +16 -3
  75. package/workspace/public/pm/cozy-steps.css +9 -9
  76. package/workspace/public/pm/cozy-today.css +122 -71
  77. package/workspace/public/pm/cozy-viewer.css +7 -7
  78. package/workspace/public/pm/cozy-viewer.js +1 -1
  79. package/workspace/public/pm/cozy-vw-mtg.css +81 -81
  80. package/workspace/public/pm/cozy-vw-rp.css +53 -53
  81. package/workspace/public/pm/cozy-vw-shell.css +23 -23
  82. package/workspace/public/pm/cozy-vw.css +117 -117
  83. package/workspace/public/pm/cozy-xv.css +11 -11
  84. package/workspace/public/pm/cozy.css +34 -15
  85. package/workspace/public/pm/hi-pop.css +19 -19
  86. package/workspace/public/pm/home-app.js +33 -9
  87. package/workspace/public/pm/home-chat.js +10 -2
  88. package/workspace/public/pm/home-day.js +155 -27
  89. package/workspace/public/pm/home-ini.css +32 -32
  90. package/workspace/public/pm/home-line.css +7 -7
  91. package/workspace/public/pm/home-list.js +12 -1
  92. package/workspace/public/pm/home-phone-card.js +18 -15
  93. package/workspace/public/pm/home-today.js +5 -3
  94. package/workspace/public/pm/ini-view-model.js +1 -1
  95. package/workspace/public/pm/ini-view.css +108 -102
  96. package/workspace/public/pm/ini-view.js +22 -3
  97. package/workspace/public/pm/loose-props.css +13 -13
  98. package/workspace/public/pm/metric-drafts.css +89 -0
  99. package/workspace/public/pm/metric-drafts.js +204 -0
  100. package/workspace/public/pm/ms-suggest.css +8 -8
  101. package/workspace/public/pm/ms-suggest.js +2 -1
  102. package/workspace/public/pm/ov-view.css +12 -12
  103. package/workspace/public/pm/premium-board.js +2 -2
  104. package/workspace/public/pm/premium-chart-tab.js +6 -6
  105. package/workspace/public/pm/premium-insights.js +364 -107
  106. package/workspace/public/pm/premium-report-intel.css +56 -0
  107. package/workspace/public/pm/premium-report-intel.js +232 -0
  108. package/workspace/public/pm/premium-shell.js +2 -2
  109. package/workspace/public/pm/premium-vw-cal.js +1 -1
  110. package/workspace/public/pm/premium-vw-file.js +2 -2
  111. package/workspace/public/pm/premium-welcome.js +3 -2
  112. package/workspace/public/pm/premium.css +130 -128
  113. package/workspace/public/pm/prog-order.css +6 -6
  114. package/workspace/public/pm/program-charter.css +23 -23
  115. package/workspace/public/pm/program-model.js +7 -0
  116. package/workspace/public/pm/rp-parts.js +2 -2
  117. package/workspace/public/pm/sort-order.css +1 -1
  118. package/workspace/public/pm/split-merge.css +15 -15
  119. package/workspace/public/pm/split-merge.js +2 -1
  120. package/workspace/public/pm/task-card.css +21 -21
  121. package/workspace/public/pm/tk-tasks.css +37 -37
  122. package/workspace/public/pm/tk-view.css +6 -6
  123. package/workspace/public/pm/wf-page.css +28 -28
  124. package/workspace/public/premium-intelligence.html +82 -0
  125. package/workspace/server.js +38 -3
  126. package/workspace/skills/metric-draft.skill +47 -0
  127. package/workspace/test-lists/intel-report-ui.json +5 -0
  128. package/workspace/test-lists/intel-report.json +9 -0
  129. package/workspace/test-lists/intelligence-gaps-ui.json +5 -0
  130. package/workspace/test-lists/intelligence-gaps.json +5 -0
  131. package/workspace/test-lists/metric-drafts-ui.json +5 -0
  132. package/workspace/test-lists/metric-drafts.json +9 -0
  133. package/workspace/test-run.js +3 -0
  134. 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,12 @@ 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 AD from './cozy-adler.js'; // Adler in Claude's ✦ line only, never in a chart (batch 16 item 2, canvas AdH3, AdM3)
38
+ 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
39
 
32
40
  let M = null; // the model
33
41
  let BM = null, bmErr = ''; // the Board measures (Delivery trends)
34
42
  let dash = null; // the view: a dashboard id; 'all' is every goal
35
- let tab = 'goals';
36
43
  let per = null; // the period { key, label, name, from, to }
37
44
  let find = '';
38
45
  let filt = { status: [], owner: [], kind: [] }; // the Filter (IsMenus): each group holds the chips that are on
@@ -53,7 +60,7 @@ const I = {
53
60
  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
61
  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
62
  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',
63
+ pause: 'M9 5v14M15 5v14', play: 'M7 5l12 7-12 7z', undo: 'M9 14L4 9l5-5M4 9h11a5 5 0 0 1 0 10h-3',
57
64
  };
58
65
  const byKey = (k) => (PF && PF.charts[k]) || (M && (M.charts || []).find((c) => c.key === k)) || null;
59
66
  const savedDash = () => (M.dashboards || []).filter((d) => d.saved);
@@ -78,7 +85,7 @@ const closeViewer = () => { if (window.czViewer && typeof window.czViewer.close
78
85
  // The Viewer floats over the page (XvAInsight); the page does not move for it.
79
86
 
80
87
  /* ── 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']];
88
+ const MENUS = [['#viewChip', '#viewMenu'], ['#perChip', '#perMenu'], ['#filtB', '#filtMenu'], ['#moreB', '#moreMenu']];
82
89
  function menu(btn, box, open) { $(box).hidden = !open; $(btn).setAttribute('aria-expanded', String(open)); }
83
90
  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
91
  for (const [b, m] of MENUS) {
@@ -100,7 +107,8 @@ document.addEventListener('keydown', (e) => {
100
107
  if ($('#repSheet')) { closeSheet(); return; }
101
108
  for (const [b, m] of MENUS) if (!$(m).hidden) { menu(b, m, false); $(b).focus(); return; }
102
109
  const om = $('#ngObjMenu'); if (om && !om.hidden) { om.hidden = true; $('#ngObjB').setAttribute('aria-expanded', 'false'); $('#ngObjB').focus(); return; }
103
- if (!$('#side').hidden) closeSide();
110
+ if (!$('#side').hidden) { closeSide(); return; }
111
+ if (!$('#libSide').hidden) closeLib(true);
104
112
  });
105
113
 
106
114
  /* ── dates and the period (AgInsPeriod) ─────────────────────────────────────────────────────────────────────────────────────────── */
@@ -131,8 +139,7 @@ function drawPeriod() {
131
139
  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
140
  per.gone = t >= per.from && t <= per.to ? gone : 0; per.total = total;
133
141
  $('#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>` : ''}`;
142
+ $('#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
143
  const n = (p) => M.goals.filter((g) => inPer(g, p)).length, goals = (k) => k + (k === 1 ? ' goal' : ' goals');
137
144
  /* a closed period: the goals due in it, and how many reached their target by their date (a reading on or before it) */
138
145
  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 +170,13 @@ const dashName = (D) => (D.id === 'all' ? 'All goals' : D.name);
163
170
  const nGoals = (k) => k + (k === 1 ? ' goal' : ' goals');
164
171
  function drawBar() {
165
172
  drawPick();
166
- $('#nGoals').textContent = String(dash === TRENDS ? 0 : goalsShown().length);
167
- $('#nOutcomes').textContent = String(outcomesShown().length);
168
173
  const D = curDash();
169
174
  $('#viewName').textContent = dash === TRENDS ? 'Delivery trends' : dashName(D);
170
- /* the Dashboard menu: every view, the default one marked; Delivery trends; then New dashboard */
175
+ /* View (Iq8Overview): every view, the default one marked; Delivery trends; then Pin, New dashboard and Edit chart */
171
176
  $('#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
177
  + (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>`;
178
+ + '<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>` : '')
179
+ + `<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
180
  drawPeriod(); drawFilter();
175
181
  }
176
182
  /* the product chip (canvas XhpA5Pages): the same chip and list as Home's. It replaces the one-product menu and "Portfolio · all products" */
@@ -181,29 +187,29 @@ function shownPick() {
181
187
  }
182
188
  function drawPick() {
183
189
  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>`;
190
+ host.innerHTML = P ? PK.chipHtml(P, { id: 'prodPick', label: 'Products' }) : `<span class="ins-ttl">${esc(M.board.name || 'Intelligence')}</span>`;
185
191
  const chip = $('#prodPick'); if (!chip) return;
186
192
  // a product's line: its goals, from what this page read (zero is silence)
187
193
  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); } }); };
194
+ 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
195
  }
190
196
  // a saved pick (this chip, or Settings): Insights opens on the ticked products, without a one-off link's ws or board
191
197
  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
198
  $('#viewMenu').addEventListener('click', (e) => {
193
199
  if (e.target.closest('[data-newdash]')) { closeMenus(); openNewDash(); return; }
200
+ 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; }
201
+ const pn = e.target.closest('[data-pin]'); if (pn) { if (pn.disabled) return; closeMenus(); pinView(); return; }
194
202
  const b = e.target.closest('[data-view]'); if (!b) return; closeMenus(); setView(b.dataset.view);
195
203
  });
196
204
  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 : ''); };
205
+ /** 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
206
+ * 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
207
  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
- addr({ tab: t === 'goals' ? null : t });
205
- }
206
- /** The address follows the tab and the goal open in the Viewer, so Back from another page comes back to it (batch 14 item 7). It goes
208
+ if (t === 'library') openLib();
209
+ else if (t === 'outcomes') { const o = $('#pOutcomes'); if (o && !o.hidden) o.scrollIntoView({ block: 'start' }); }
210
+ if (new URLSearchParams(location.search).has('tab')) addr({ tab: null });
211
+ }
212
+ /** The address follows the goal open in the Viewer, so Back from another page comes back to it (batch 14 item 7). It goes
207
213
  * through the Viewer, which writes it once the history has settled on the entry this page shows, and keeps that entry's trail. */
208
214
  function addr(o) {
209
215
  const u = setQ(o), V = window.czViewer;
@@ -213,13 +219,16 @@ document.addEventListener('cz-viewer', (e) => {
213
219
  const d = e.detail || {}, id = d.open && /^goal:/.test(d.id || '') ? d.id.slice(5) : null;
214
220
  if ((new URLSearchParams(location.search).get('goal') || null) !== id) addr({ goal: id });
215
221
  });
216
- $('.ins-tabs').addEventListener('click', (e) => { const b = e.target.closest('[role="tab"]'); if (b) setTab(b.dataset.tab); });
217
- $('.ins-tabs').addEventListener('keydown', (e) => {
218
- if (!/^Arrow(Left|Right)$/.test(e.key)) return;
219
- 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];
220
- setTab(n.dataset.tab); n.focus();
221
- });
222
- function setView(id) { dash = id; setTab('goals'); redraw(); }
222
+ function setView(id) { dash = id; closeLib(); redraw(); noteOpen(); }
223
+ /* the view on screen, noted once a day per view (feedback batch 16 item 1; POST /api/page-opens, local only): it is what lets the ✦ strip say
224
+ * "You open this every week" from a record, never from a guess. Portfolio is no one product's view, so it is not noted. */
225
+ const NOTED = new Set();
226
+ async function noteOpen() {
227
+ if (!M || PF || !M.board.ws) return;
228
+ const D = curDash(), view = D && D.saved ? 'dashboard:' + D.id : 'view', k = M.board.ws + '|' + view;
229
+ if (NOTED.has(k)) return; NOTED.add(k);
230
+ await Promise.resolve(pmPost('/api/page-opens', { ws: M.board.ws, page: 'intelligence', view })).catch(() => null);
231
+ }
223
232
 
224
233
  /* Portfolio: the goals of the ticked products (several ticked, batch 12 item 5), each product's model read once through GET /api/insights-premium,
225
234
  * 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
@@ -308,12 +317,20 @@ $('#findRes').addEventListener('click', (e) => {
308
317
  });
309
318
 
310
319
  /* ⋯ (IsMenus): Sources with how long ago the page read them, Export as CSV and About these numbers, each in the Viewer card */
311
- $('#moreB').addEventListener('click', () => { const m = Math.round((Date.now() - loadedAt) / 60000); $('#srcAge').textContent = !loadedAt ? '' : m < 1 ? 'read just now' : 'read ' + m + ' min ago'; });
320
+ $('#moreB').addEventListener('click', () => {
321
+ const m = Math.round((Date.now() - loadedAt) / 60000); $('#srcAge').textContent = !loadedAt ? '' : m < 1 ? 'read just now' : 'read ' + m + ' min ago';
322
+ if (!M) return;
323
+ const R = M.reports || {}, nr = reportGroups().length, nd = savedDash().length, nf = (R.found || []).length + (R.asks || []).filter((a) => a.state === 'ready').length;
324
+ $('#libSub').textContent = [nr ? nr + (nr === 1 ? ' report' : ' reports') : '', nd ? nd + (nd === 1 ? ' dashboard' : ' dashboards') : '', (R.found || []).length ? (R.found || []).length + ' found' : ''].filter(Boolean).join(' · ');
325
+ $('#libNew').innerHTML = nf ? `<span class="cz-pill you">${nf} new</span>` : ''; // zero is silence
326
+ });
312
327
  $('#moreMenu').addEventListener('click', (e) => {
313
328
  const b = e.target.closest('[data-more]'); if (!b || b.disabled) return; closeMenus();
314
- if (b.dataset.more === 'sources') viewer({ kind: 'Insights', title: 'Sources', icon: 'source', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
329
+ if (b.dataset.more === 'library') openLib();
330
+ else if (b.dataset.more === 'trends') setView(TRENDS);
331
+ else if (b.dataset.more === 'sources') viewer({ kind: 'Intelligence', title: 'Sources', icon: 'source', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } });
315
332
  else if (b.dataset.more === 'export') location.assign('/api/insights-records/export?' + wsQ() + (M.board.id ? 'board=' + encodeURIComponent(M.board.id) : ''));
316
- else if (b.dataset.more === 'about') viewer({ kind: 'Insights', title: 'About these numbers', icon: 'info', eye: 'Insights', render: (el) => { el.innerHTML = ABOUT; } });
333
+ else if (b.dataset.more === 'about') viewer({ kind: 'Intelligence', title: 'About these numbers', icon: 'info', eye: 'Intelligence', render: (el) => { el.innerHTML = ABOUT; } });
317
334
  });
318
335
  function sourcesHtml() {
319
336
  const miss = (M.header && M.header.missing) || [];
@@ -333,16 +350,229 @@ const ABOUT = '<div class="ins-about"><p>Every goal is a KR metric record of thi
333
350
  + '<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>'
334
351
  + '<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>';
335
352
 
336
- /* ── the strip ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
353
+ /* ── 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
354
+ * next one. Ask why takes the finding to Home. A finding carries a drafted move only when the engine has one (feedback batch 16 item 1,
355
+ * lib/insight-moves.js: chase the owner, anchor an initiative, move the date): the move is said under the reason, ✓ makes it (POST
356
+ * /api/insight-moves/apply, the server finds the move again by its sig) and Undo takes it back (/undo). A finding with no move draws no ✓. ── */
357
+ let insIdx = 0;
358
+ const insSkip = new Set(); // the findings put off with Not now, this visit only
359
+ function stripList() {
360
+ const I0 = M.insight || { none: true, text: '' };
361
+ if (I0.none) return [{ text: I0.text, why: I0.why || '', none: true }].concat(PF ? [] : RI.stripItems());
362
+ return [{ text: I0.text, why: I0.why || '', chart: I0.chart, move: I0.move || null }].concat((I0.more || []).map((x) => ({ text: x.text, why: x.why || '', chart: x.chart, move: x.move || null })), PF ? [] : RI.stripItems());
363
+ }
337
364
  function drawStrip() {
338
- const I0 = M.insight, G = goalsShown();
339
- const behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
340
- $('#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.' : '.');
341
- 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; }
342
- $('#brief').textContent = I0.text;
343
- $('#insWhy').textContent = I0.none ? '' : I0.why || '';
344
- $('#askWhy').href = homeAsk('insights', I0.none ? 'Why is there no insight on my goals yet?' : 'Why? ' + I0.text);
345
- $('#askWhy').hidden = false;
365
+ const G = goalsShown(), behind = G.filter((g) => g.tone === 'late' || g.tone === 'red').length;
366
+ $('#insEye').textContent = ''; $('#insAct').innerHTML = ''; $('#insPg').innerHTML = ''; $('#insMv').hidden = true; $('#insMv').innerHTML = ''; $('#insHero').classList.remove('mv');
367
+ 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; }
368
+ const L = stripList(), open = L.map((f, i) => i).filter((i) => !insSkip.has(i));
369
+ if (!open.includes(insIdx)) insIdx = open.length ? open[0] : 0;
370
+ const f = L[insIdx];
371
+ $('#brief').textContent = f.text;
372
+ $('#insWhy').textContent = f.why || '';
373
+ // Claude's line carries Adler's face in the line's mood: honest when a goal is behind or the finding says so plainly, needs you on a
374
+ // proposal, handled otherwise. The charts and KR rows below stay pure data.
375
+ const sp = $('#insHero .sp');
376
+ if (sp) { sp.classList.add('ad'); sp.innerHTML = AD.adler(f.report ? 'needs-you' : behind || /^Straight answer/.test(f.text) || AD.moodOfText(f.text) === 'honest' ? 'honest' : 'handled', 40, { label: false }); }
377
+ $('#askWhy').href = homeAsk('insights', f.none ? 'Why is there no finding on my goals yet?' : 'Why? ' + f.text);
378
+ $('#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
379
+ if (f.report) $('#insAct').innerHTML = RI.stripActs(f.report);
380
+ const mv = !f.report && f.move ? f.move : null;
381
+ $('#insHero').classList.toggle('mv', !!mv);
382
+ if (mv) { $('#insMv').innerHTML = `${SV(I.spark)}<span>${esc(mv.text)}</span>`; $('#insMv').hidden = false; $('#insMv').classList.toggle('dn', !!mv.done); }
383
+ const mvAct = !mv ? '' : mv.done ? `<span class="cz-pill ok">Done</span><button type="button" class="cz-ib sm" data-mv="undo" aria-label="Undo: ${esc(mv.label)}" title="Undo">${SV(I.undo)}</button>`
384
+ : `<button type="button" class="cz-ib sm solid" data-mv="apply" aria-label="${esc(mv.label)}" title="${esc(mv.label)}">${SV(I.chk)}</button>`;
385
+ if (!f.report) $('#insAct').innerHTML = mvAct;
386
+ if (open.length > 1) {
387
+ 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>` + mvAct;
388
+ $('#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('');
389
+ }
390
+ }
391
+ $('#insHero').addEventListener('click', async (e) => {
392
+ if (e.target.closest('[data-rp]')) { await RI.stripPress(e); return; }
393
+ const b = e.target.closest('[data-mv]'); if (b) { await pressMove(b); return; }
394
+ const d = e.target.closest('[data-ins]'); if (d) { insIdx = +d.dataset.ins; drawStrip(); return; }
395
+ 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(); }
396
+ });
397
+
398
+ /** ✓ on a drafted move, or Undo on a made one. The server finds the move again by its sig; the toast carries Undo. */
399
+ async function pressMove(b) {
400
+ const f = stripList()[insIdx], mv = f && f.move; if (!mv || b.disabled) return;
401
+ b.disabled = true;
402
+ const undo = async () => { const r = await pmPost('/api/insight-moves/undo', { ws: M.board.ws, sig: mv.sig }); toast(r && r.ok ? 'Undone. It is as it was.' : (r && r.error) || 'It could not be undone.'); await load(); };
403
+ if (b.dataset.mv === 'undo') { await undo(); return; }
404
+ const r = await pmPost('/api/insight-moves/apply', { ws: M.board.ws, board: M.board.id, sig: mv.sig });
405
+ if (!r || r.ok !== true) { b.disabled = false; toast((r && r.error) || 'It could not be done. Nothing changed.'); return; }
406
+ toast(r.said || mv.said || 'Done.', { label: 'Undo', fn: undo });
407
+ await load();
408
+ }
409
+
410
+ /* ── the North Star and its inputs (Iq8Overview): the KR metric record with role north-star, drawn as its number with the change against the
411
+ * 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
412
+ * 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. ── */
413
+ let nsSpan = '4';
414
+ const SPANS = [['4', '4 weeks', 28], ['12', '12 weeks', 84], ['q', 'This quarter vs last', null]];
415
+ const isOwnKr = (g) => !g.program && !g.initiative;
416
+ const nsGoal = () => (PF ? null : M.goals.find((g) => g.role === 'north-star' && isOwnKr(g)) || null);
417
+ const inputGoals = () => (PF ? [] : M.goals.filter((g) => (g.role === 'input' || g.role === 'guardrail') && isOwnKr(g)));
418
+ /** The reading at or before a day, from a goal's series; null when the series does not reach back that far. */
419
+ const atOrBefore = (g, t) => { const S = (g.series || []).filter((r) => day(r.at) <= t); return S.length ? S[S.length - 1] : null; };
420
+ /** 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). */
421
+ function spanChange(g, span = nsSpan) {
422
+ const S = g.series || []; if (S.length < 2) return null;
423
+ const last = S[S.length - 1], tl = day(last.at), back = (SPANS.find((x) => x[0] === span) || SPANS[0])[2];
424
+ const t0 = back ? tl - back * DAY : (() => { const d = new Date(tl); return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() - 3, d.getUTCDate()); })();
425
+ const prev = atOrBefore(g, t0); if (!prev || prev === last) return null;
426
+ 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);
427
+ return { d, pct: pctd, prev, last, better, t0 };
428
+ }
429
+ const pctSay = (p) => (p === null ? '' : (p > 0 ? '+' : p < 0 ? '−' : '') + (Math.round(Math.abs(p) * 10) / 10) + '%');
430
+ /** 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
431
+ * title, so a hover says its value and day. */
432
+ function nsSvg(g, ch, W = 520, H = 120) {
433
+ const S = g.series || [], tl = day(S[S.length - 1].at), span = ch ? tl - ch.t0 : 28 * DAY;
434
+ 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);
435
+ 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);
436
+ const x = (t) => 8 + (span ? (t - (tl - span)) / span : 1) * (W - 16), y = (v) => 10 + (1 - (v - lo) / rg) * (H - 26);
437
+ const path = (L, sh) => L.map((r, i) => (i ? 'L' : 'M') + f(x(day(r.at) + sh)) + ' ' + f(y(r.v))).join('');
438
+ 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('');
439
+ const z = cur[cur.length - 1];
440
+ 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' : ''))}">`
441
+ + (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)}"/>` : '')
442
+ + dots + `<circle class="dt" cx="${f(x(day(z.at)))}" cy="${f(y(z.v))}" r="4.5"/></svg>`;
443
+ }
444
+ const RM = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
445
+ let nsCounted = false;
446
+ /** The North Star's number counts up once, on the first draw (principle 12 as amended for Intelligence: subtle, honest, reduced motion respected). */
447
+ function countUp(el, g) {
448
+ if (nsCounted || RM() || !el || g.now === null) { nsCounted = true; return; }
449
+ nsCounted = true;
450
+ const txt = g.nowTxt, m = /-?\d[\d,]*(\.\d+)?/.exec(txt); if (!m) return;
451
+ const dec = (m[1] || '').length - (m[1] ? 1 : 0), to = Number(m[0].replace(/,/g, '')), t0 = performance.now();
452
+ 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; };
453
+ requestAnimationFrame(step);
454
+ }
455
+ function drawNs() {
456
+ const g = nsGoal(), box = $('#nsRow');
457
+ if (!g) { box.hidden = true; box.innerHTML = ''; return; }
458
+ const ch = spanChange(g), I0 = inputGoals(), src = srcOf(g), fr = freshOf(g);
459
+ 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>` : '';
460
+ 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>`
461
+ + `<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>`
462
+ + `<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>`
463
+ + ((g.series || []).length ? nsSvg(g, ch) : `<p class="note">${esc(nextReading(g))}</p>`) + '</div>';
464
+ 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>`; };
465
+ const ins = I0.filter((x) => x.role === 'input'), grd = I0.filter((x) => x.role === 'guardrail');
466
+ 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>` : '';
467
+ box.innerHTML = card + side; box.hidden = false; box.classList.toggle('one', !side);
468
+ countUp($('#nsNum'), g);
469
+ }
470
+ $('#nsRow').addEventListener('click', (e) => {
471
+ const s = e.target.closest('[data-span]'); if (s) { nsSpan = s.dataset.span; drawNs(); return; }
472
+ if (e.target.closest('[data-nsopen]')) { const g = nsGoal(); if (g) openGoalDetail(g.id); return; }
473
+ const r = e.target.closest('.ins-inr[data-goal]'); if (r) openGoalDetail(r.dataset.goal);
474
+ });
475
+
476
+ /* ── what Claude drafted (Iq8Suggest, Iq9Draft): GET /api/metric-drafts for this product. While a run drafts, the five steps and what it read;
477
+ * once ready, each proposed metric with its Now, its Target, why that target and where it is measured, ✎ to edit its name, target and source in
478
+ * place (batch 16 item 1), ✓ to track it and × to remove it, ✓ all for the rest. A ✓ writes a KR metric record (lib/routes-metric-drafts.js); Undo takes it back. Nothing drafted: the box is not drawn. ── */
479
+ let DR = null, drTimer = 0;
480
+ const DR_STEPS = ['Read', 'Shape', 'Measure', 'Target', 'Ready'];
481
+ async function draftsLoad() {
482
+ clearTimeout(drTimer);
483
+ if (!M || PF || !M.board.ws) { DR = null; drawDrafts(); return; }
484
+ let r = null;
485
+ 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; }
486
+ DR = r && r.ok ? r : null; drawDrafts();
487
+ if (DR && DR.run && DR.run.state === 'running') drTimer = setTimeout(draftsLoad, 4000);
488
+ }
489
+ const drOpen = () => (DR ? (DR.rows || []).filter((x) => x.state === 'open') : []);
490
+ function drawDrafts() {
491
+ const box = $('#draftBox'), run = DR && DR.run, rows = DR ? DR.rows || [] : [];
492
+ const busy = run && run.state === 'running';
493
+ if (!DR || (!rows.length && !busy)) { box.hidden = true; box.innerHTML = ''; return; }
494
+ const step = busy ? Math.max(0, Math.min(4, run.step || 0)) : 4, left = drOpen().length;
495
+ 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>`;
496
+ 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') + '.';
497
+ const tools = busy ? `<button type="button" class="cz-ib sm" data-dr="stop" aria-label="Stop" title="Stop">${SV(I.pause)}</button>`
498
+ : 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>';
499
+ 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>` : '';
500
+ let grp = '';
501
+ const body = rows.map((r) => {
502
+ const g = r.group !== grp ? `<div class="ins-grp" role="row"><span role="cell">${esc(r.group)}</span></div>` : ''; grp = r.group;
503
+ if (r.state === 'open' && drEdit === r.id) return g + drEditRow(r);
504
+ 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>` : '';
505
+ const act = r.state === 'open' ? `<button type="button" class="cz-ib sm" data-dr="edit" data-row="${esc(r.id)}" aria-label="Edit ${esc(r.name)}" title="Edit">${SV(I.pen)}</button><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>`
506
+ : `<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>`;
507
+ 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>`
508
+ + `<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>`;
509
+ }).join('');
510
+ 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>`
511
+ : '<p class="note">The metrics appear here as I find them.</p>';
512
+ 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>` : ''}`;
513
+ box.hidden = false;
514
+ }
515
+ /* the inline edit of an open draft (batch 16 item 1): its name, its target and where it is measured, in place on the row; ✓ saves (POST
516
+ * /api/metric-drafts/edit), × puts it back, and the chat icon asks Claude in Home for anything else (the why, the group, a new metric). */
517
+ let drEdit = null;
518
+ function drEditRow(r) {
519
+ const askQ = 'Change the drafted metric ' + r.name + ': ';
520
+ const tgt = r.type === 'Done or not' ? `<b>${esc(r.targetTxt || 'Done')}</b>` : `<input class="ins-dri" data-drf="target" inputmode="decimal" value="${esc(r.target == null ? '' : String(r.target))}" aria-label="Target of ${esc(r.name)}"${r.unit || r.type === 'Percentage' ? ` placeholder="${esc(r.type === 'Percentage' ? '%' : r.unit)}"` : ''}>`;
521
+ return `<div class="ins-tr ins-row ins-dcols ins-dred" role="row" data-dred="${esc(r.id)}"><div class="nm" role="cell"><input class="ins-dri" data-drf="name" value="${esc(r.name)}" maxlength="80" aria-label="Name"></div>`
522
+ + `<div role="cell"><b>${esc(r.nowTxt || '—')}</b></div><div role="cell">${tgt}</div><div role="cell" class="note">${esc(r.why || '')}</div>`
523
+ + `<div role="cell"><input class="ins-dri" data-drf="source" value="${esc(r.source || '')}" maxlength="40" aria-label="Measured by" placeholder="Measured by"></div>`
524
+ + `<div role="cell" class="ins-act"><a class="cz-ib sm" href="${esc(homeAsk('insights', askQ))}" aria-label="Ask Claude in Home to change something else" title="Ask Claude in Home">${SV('M4 5h16v11H9l-5 4z')}</a>`
525
+ + `<button type="button" class="cz-ib sm" data-dr="cancel" data-row="${esc(r.id)}" aria-label="Cancel the edit" title="Cancel">${SV(I.x)}</button><button type="button" class="cz-ib sm solid" data-dr="save" data-row="${esc(r.id)}" aria-label="Save ${esc(r.name)}" title="Save">${SV(I.chk)}</button></div></div>`;
526
+ }
527
+ $('#draftBox').addEventListener('keydown', (e) => {
528
+ const f = e.target.closest('[data-drf]'); if (!f) return;
529
+ const ed = f.closest('[data-dred]');
530
+ if (e.key === 'Enter') { e.preventDefault(); const s = ed && ed.querySelector('[data-dr="save"]'); if (s) s.click(); }
531
+ if (e.key === 'Escape') { e.preventDefault(); drEdit = null; drawDrafts(); }
532
+ });
533
+ $('#draftBox').addEventListener('click', async (e) => {
534
+ const b = e.target.closest('[data-dr]'); if (!b || b.disabled || !DR) return;
535
+ const k = b.dataset.dr, row = b.dataset.row || null, r0 = row ? (DR.rows || []).find((x) => x.id === row) : null;
536
+ if (k === 'edit') { drEdit = row; drawDrafts(); const n = $('#draftBox').querySelector(`[data-dred="${CSS.escape(row)}"] [data-drf="name"]`); if (n) { n.focus(); n.select(); } return; }
537
+ if (k === 'cancel') { drEdit = null; drawDrafts(); return; }
538
+ if (k === 'save') {
539
+ const ed = b.closest('[data-dred]'), val = (f) => { const x = ed && ed.querySelector(`[data-drf="${f}"]`); return x ? x.value : undefined; };
540
+ const body = { ws: M.board.ws, scope: 'product', id: M.board.ws, row, name: val('name'), source: val('source') };
541
+ if (val('target') !== undefined) body.target = val('target');
542
+ b.disabled = true;
543
+ const res = await pmPost('/api/metric-drafts/edit', body);
544
+ if (!res || res.ok !== true) { b.disabled = false; toast((res && res.error) || 'It could not be saved. Nothing changed.'); return; }
545
+ drEdit = null; toast(res.changed ? 'Saved. Track it to keep it as you wrote it.' : 'Nothing changed.');
546
+ await draftsLoad();
547
+ return;
548
+ }
549
+ b.disabled = true;
550
+ const res = await pmPost('/api/metric-drafts/' + k, Object.assign({ ws: M.board.ws, scope: 'product', id: M.board.ws }, row ? { row } : {}));
551
+ if (!res || res.ok !== true) { b.disabled = false; toast((res && res.error) || 'It could not be done. Nothing changed.'); return; }
552
+ const n = drOpen().length;
553
+ 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.';
554
+ 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);
555
+ await load(); await draftsLoad();
556
+ });
557
+
558
+ /* ── Reports and dashboards (⋯; the old Library tab) in a side panel: Found in your work, requests from Home, the reports, then the dashboards ── */
559
+ let libBack = null;
560
+ function openLib() {
561
+ if (!$('#side').hidden) closeSide();
562
+ libBack = document.activeElement; $('#libSide').hidden = false; document.body.classList.add('ins-sideon'); drawList(); $('#libSide').focus({ preventScroll: true });
563
+ }
564
+ function closeLib(focus) {
565
+ if ($('#libSide').hidden) return;
566
+ $('#libSide').hidden = true; if ($('#side').hidden) document.body.classList.remove('ins-sideon');
567
+ if (focus && libBack && libBack.focus && document.contains(libBack)) libBack.focus();
568
+ }
569
+ $('#libX').addEventListener('click', () => closeLib(true));
570
+ /** Pin (View): the view on screen opens first next time (POST /api/premium-dashboards/pin). */
571
+ async function pinView() {
572
+ const D = curDash(); if (!M.board.id) return;
573
+ const res = await pmPost('/api/premium-dashboards/pin', { ws: M.board.ws, board: M.board.id, id: D.id });
574
+ if (!res || res.ok !== true) { toast((res && res.error) || 'It could not be pinned. Nothing changed.'); return; }
575
+ toast('Pinned ' + dashName(D) + ': it opens first.'); await load();
346
576
  }
347
577
 
348
578
  /* ── Goals (AgInsGoals) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── */
@@ -352,10 +582,13 @@ function goalsShown() {
352
582
  if (dash === TRENDS) return [];
353
583
  if (filt.kind.length && !filt.kind.includes('goals')) return [];
354
584
  const D = PF ? M.dashboards[0] : curDash(), ids = D.saved ? D.charts : null;
355
- const L = allGoals().filter((g) => inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
585
+ const L = allGoals().filter((g) => isKr(g) && inPer(g) && (!ids || ids.includes(g.id)) && (!D.id.startsWith('p:') || g.pillar === D.name)
356
586
  && (!filt.status.length || filt.status.includes(statusOf(g))) && ownerHit(ownersOf(g)) && hit(g.title, g.pillar, ...g.moves.map((m) => m.title)));
357
587
  return ids ? L.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id)) : L;
358
588
  }
589
+ /** 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. */
590
+ const NOT_KR = ['north-star', 'input', 'guardrail', 'program-goal', 'rollup', 'success', 'signal'];
591
+ const isKr = (g) => !NOT_KR.includes(g.role) && !g.program && !g.initiative;
359
592
  const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok', 'on hold': 'q' };
360
593
  /** 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
361
594
  * recorded as skipped (its "Skipped <stage>" warning) is a dashed ring. */
@@ -461,10 +694,10 @@ function drawGoals() {
461
694
  const G = goalsShown(), T = $('#goalTbl');
462
695
  document.body.classList.toggle('ins-trv', dash === TRENDS);
463
696
  if (dash === TRENDS) { T.innerHTML = bmHtml(true); drawCards([]); $('#goalCards').innerHTML = ''; return; }
464
- 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>`;
697
+ 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>`;
465
698
  const D = curDash();
466
- if (!M.goals.length) {
467
- 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();
699
+ if (!M.goals.filter(isKr).length) {
700
+ 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);
468
701
  drawCards([]); return;
469
702
  }
470
703
  /* by objective; Portfolio groups by product, each product's objectives said in its rows */
@@ -473,7 +706,7 @@ function drawGoals() {
473
706
  const objs = [...new Set(M.goals.map((g) => g.pillar || ''))];
474
707
  const head1 = (k) => (PF ? esc(k || 'A product') : k ? 'Objective ' + (objs.indexOf(k) + 1) + ' · ' + esc(k) : 'No objective');
475
708
  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('');
476
- 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();
709
+ 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);
477
710
  drawCards(G);
478
711
  }
479
712
  function budgetsHtml(D) {
@@ -556,12 +789,13 @@ function goalSummary(g) {
556
789
  const first = [now, tgt].filter(Boolean).join(', ');
557
790
  const pace = g.pace && g.pace.tone === 'late' && g.pace.head !== '—' ? g.pace.head + (g.pace.sub ? ', ' + g.pace.sub : '') + '.' : '';
558
791
  const text = [first ? first + '.' : '', sinceOf(g), pace].filter(Boolean).join(' ') || nextReading(g);
559
- 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
792
+ 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
560
793
  }
561
794
  function readingsHtml(g, o) {
562
795
  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);
563
796
  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('')
564
797
  + (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>`)
798
+ + (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>` : '')
565
799
  + (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>` : '');
566
800
  }
567
801
  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>';
@@ -573,7 +807,8 @@ const movedHtml = (g) => (g.moves.length ? `<div class="ins-mvl">${g.moves.map(m
573
807
  function goalBodyHtml(g, o) {
574
808
  const V = window.czViewer, c = g.key ? byKey(g.key) : null, phone = isPhone(), steps = g.type === 'Done or not' && g.steps && g.steps.length;
575
809
  const chart = steps ? stepsHtml(g) : c ? detailSvg(g, c, phone ? 330 : 470, phone ? 140 : 160) : emptyTrend(g, o.own);
576
- 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>`;
810
+ 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
811
+ 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>`;
577
812
  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>` : '';
578
813
  const onDash = savedDash().filter((D) => D.charts.includes(g.id)).length;
579
814
  const moved = `<div class="ins-mvb"><p class="ins-mvh">Moved by${g.moves.length ? ` <span>${g.moves.length}</span>` : ''}</p>${movedHtml(g)}</div>`;
@@ -581,7 +816,8 @@ function goalBodyHtml(g, o) {
581
816
  { id: 'read', title: 'Readings', count: g.series.length, open: o.open === 'read', render: () => readingsHtml(g, o) },
582
817
  o.own && savedDash().length ? { id: 'dash', title: 'On dashboards', count: onDash, render: () => dashSwitches(g) } : null,
583
818
  ];
584
- return V.czSummary(goalSummary(g)) + form + big + moved + V.czSections(rows, { key: 'goal' }) + '<p class="note ins-gmsg" data-gmsg role="status"></p>';
819
+ 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>`;
820
+ return V.czSummary(goalSummary(g)) + form + big + moved + V.czSections(rows, { key: 'goal' }) + '<p class="note ins-gmsg" data-gmsg role="status"></p>' + ask;
585
821
  }
586
822
  /** The goal as plain text, for Copy as text. */
587
823
  function goalText(g) {
@@ -601,8 +837,9 @@ function openGoalDetail(id, open0) {
601
837
  if (own && M.goals.some((x) => x.id === g.id)) more.push({ label: 'Edit chart', on: () => openChartEdit(g.id) });
602
838
  if (more.length) more.push({ sep: true });
603
839
  more.push({ label: 'Copy link', on: () => copyText(goalLink(g), 'Link copied.') }, { label: 'Copy as text', on: () => copyText(goalText(g), 'Copied as text.') });
840
+ const rp = own && !PF ? RI.viewerPress('goal:' + id) : null; // RfA1: a key result's panel makes a report too
604
841
  const body = vwOpen({ kind: 'Goal', title: (kr ? kr + ' · ' : '') + g.title, icon: 'goal', id: 'goal:' + id, more,
605
- discuss: true,
842
+ discuss: true, presses: rp ? [rp] : null, onPress: (act) => { if (rp && act === rp.act) rp.run(); },
606
843
  render: (el) => {
607
844
  el.classList.add('ins-vbody', 'ins-xv');
608
845
  const draw = () => { const top = el.scrollTop; el.innerHTML = goalBodyHtml(g, st); el.scrollTop = top; };
@@ -623,13 +860,15 @@ function openGoalDetail(id, open0) {
623
860
  }
624
861
  };
625
862
  el.onsubmit = async (e) => {
626
- const f = e.target; if (!f.matches('[data-rdf], [data-stf]')) return;
863
+ const f = e.target;
864
+ if (f.matches('[data-askf]')) { e.preventDefault(); const q = f.q.value.trim(); if (q) location.assign(homeAsk('goal', 'About ' + g.title + ': ' + q)); return; }
865
+ if (!f.matches('[data-rdf], [data-stf]')) return;
627
866
  e.preventDefault(); const m = f.querySelector('[data-msg]');
628
867
  if (f.matches('[data-rdf]')) {
629
868
  const v = f.v.value.trim(), at = f.at.value;
630
869
  if (!/^\d{4}-\d{2}-\d{2}$/.test(at) || v === '' || !Number.isFinite(Number(v))) { m.textContent = 'Pick a date and type a number.'; return; }
631
870
  m.textContent = 'Saving.';
632
- const res = await pmPost('/api/records/kr-metrics/reading', { ws: goalWs(g), rid: goalRid(g), at, value: Number(v), why: 'Reading from Insights' });
871
+ const res = await pmPost('/api/records/kr-metrics/reading', { ws: goalWs(g), rid: goalRid(g), at, value: Number(v), why: 'Reading from Intelligence' });
633
872
  if (!res || res.ok !== true) { m.textContent = (res && res.error) || 'It could not be saved. Nothing changed.'; return; }
634
873
  st.adding = false; await fresh('Added the reading.');
635
874
  } else {
@@ -742,7 +981,7 @@ async function bmLoad() {
742
981
  let r = null;
743
982
  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; }
744
983
  if (!r || !r.ok || r.state !== 'ready') { BM = null; bmErr = (r && r.error) || '1'; } else { BM = r.model; bmErr = ''; }
745
- if (tab === 'goals') drawGoals();
984
+ drawGoals();
746
985
  if (BM && BM.pending) setTimeout(bmLoad, 4000); // the workflow engine is still deriving Blocked and Idle
747
986
  }
748
987
 
@@ -757,7 +996,7 @@ function rangeSay(ser) {
757
996
  }
758
997
  function closeTarget(focus) {
759
998
  const p = $('#tgPop'); if (!p) return; const k = tgOpen; p.remove(); tgOpen = null;
760
- if (tab === 'goals') drawGoals();
999
+ drawGoals();
761
1000
  if (focus && k) { const t = $(`[data-tile="${k}"]`); if (t) t.focus(); }
762
1001
  }
763
1002
  function openTarget(key) {
@@ -820,14 +1059,6 @@ function bulletHtml(P) {
820
1059
  const col = P.state === 'met' ? 'var(--cz-dot-ok)' : P.state === 'part' ? 'var(--cz-dot-risk)' : 'var(--cz-dot-q)';
821
1060
  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>`;
822
1061
  }
823
- function promiseHtml(r) {
824
- const P = promiseOf(r);
825
- 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>`;
826
- const { g, moved, promised } = P, col = P.state === 'met' ? 'var(--cz-ok)' : P.state === 'part' ? 'var(--cz-risk)' : 'var(--cz-ink3)';
827
- const text = g.title + (promised !== null ? ' ' + sgn(promised, g.unit) : '') + (g.byAt ? ' by ' + md(day(g.byAt)) : '');
828
- 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);
829
- 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>`;
830
- }
831
1062
  /** 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. */
832
1063
  function guardOf(r) {
833
1064
  const P = promiseOf(r), name = P && P.g.guardrail ? P.g.guardrail.replace(/ must not get worse$/, '') : '';
@@ -839,43 +1070,67 @@ function guardOf(r) {
839
1070
  const d = last.v - before.v, worse = gg.direction === 'down' ? d > 0 : d < 0;
840
1071
  return { name, state: worse ? 'worse' : 'held', text: (worse ? 'worse by ' : d === 0 ? 'held' : 'held, moved ') + (d === 0 ? '' : sgn(Math.abs(d), gg.unit).replace(/^\+/, '')) };
841
1072
  }
842
- /** Guardrail and overlap: the goal's guardrail, then the other initiatives that move the same goal. */
843
- function guardHtml(r) {
844
- const P = promiseOf(r), others = P ? P.g.moves.filter((m) => m.id !== r.id) : [], G = guardOf(r);
845
- 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>` : '')
846
- + (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>');
847
- }
848
- /** 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
849
- * before the window closed says the day it was judged. A verdict is due when the window closes. */
850
- 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)),
851
- 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' };
1073
+ /** A verdict is due when the outcome's window closes. */
852
1074
  const dueOf = (r) => (r && r.window && r.window.closes ? day(r.window.closes) : null);
853
- const OUT_G = { verdict: 'Needs your verdict', window: 'In their window', decided: 'Decided' };
1075
+ /** 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
1076
+ * has no draft, and Decide opens the full verdict (Keep, Iterate or Stop, with what was learned). The line is the evidence said plainly. */
1077
+ function draftOf(r) {
1078
+ if (r.group !== 'verdict') return null;
1079
+ const P = promiseOf(r), G = guardOf(r);
1080
+ if (!P || P.state !== 'met' || (G && G.state === 'worse')) return null;
1081
+ const beat = P.share > 1.05, moved = sgn(P.moved, P.g.unit);
1082
+ 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.' : '') };
1083
+ }
1084
+ let decOpen = false;
854
1085
  function outRow(r) {
855
- const due = dueOf(r);
856
- 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>`
857
- : 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>`
858
- : (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>')
859
- : `<span class="note">${r.idx === 6 ? (due !== null ? 'Opens ' + esc(md(due)) : 'Being monitored') : 'Too early'}</span>`; // the verdict opens when the window closes
860
- 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>`
861
- + `<div role="cell">${promiseHtml(r)}</div><div role="cell" class="ins-guard">${guardHtml(r)}</div>`
862
- + `<div role="cell">${winHtml(r)}</div><div role="cell">${verdict}</div></div>`;
863
- }
864
- function winHtml(r) {
865
- 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);
866
- 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>`;
867
- }
1086
+ const due = dueOf(r), P = promiseOf(r), dr = draftOf(r), ship = day(r.endAt);
1087
+ 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>`;
1088
+ 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>` : ''}` : '';
1089
+ let verdict, act = '';
1090
+ if (r.group === 'verdict') {
1091
+ 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>`;
1092
+ 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>`
1093
+ + (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>` : '');
1094
+ } else if (r.group === 'decided') {
1095
+ const v = r.verdict;
1096
+ 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>`
1097
+ : (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>';
1098
+ 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>`;
1099
+ } else verdict = `<span class="cz-pill q">${esc(due !== null ? 'Judged ' + md(due) : r.idx === 6 ? 'Being monitored' : 'Too early')}</span>`;
1100
+ 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>`
1101
+ + `<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>`;
1102
+ }
1103
+ /** 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
1104
+ * section is not drawn when nothing has shipped. */
868
1105
  function drawOutcomes() {
869
- const L = outcomesShown(), need = L.filter((r) => r.group === 'verdict');
870
- 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;
871
- $('#outText').innerHTML = !M.initiativesRead ? 'The board’s initiatives are not read yet, so no shipped work is listed.'
872
- : !L.length ? 'No initiative is past Build yet. Shipped work shows here, with what its goal promised.'
873
- : (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.');
874
- 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>';
875
- 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('');
876
- $('#outTbl').innerHTML = oneNote() + head + (groups || '<div class="ins-empty">Nothing to judge yet.</div>');
877
- }
878
- $('#outTbl').addEventListener('click', (e) => { const b = e.target.closest('[data-verdict]'); if (b) openVerdict((M.outcomes || []).find((r) => r.id === b.dataset.verdict)); });
1106
+ const L = outcomesShown(), sec = $('#pOutcomes');
1107
+ const live = L.filter((r) => r.group !== 'decided'), dec = L.filter((r) => r.group === 'decided');
1108
+ if (!M.initiativesRead || (!live.length && !dec.length)) { sec.hidden = true; $('#outTbl').innerHTML = ''; return; }
1109
+ sec.hidden = false;
1110
+ const nj = live.filter((r) => r.group === 'verdict').length, nw = live.length - nj;
1111
+ const vOf = (r) => (r.verdict ? r.verdict.verdict : r.status === 'done' ? 'Keep' : 'Stop'), cnt = (k) => dec.filter((r) => vOf(r) === k).length;
1112
+ 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>`;
1113
+ 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>` : '';
1114
+ $('#outTbl').innerHTML = oneNote() + head + live.map(outRow).join('') + foot + (decOpen ? dec.map(outRow).join('') : '');
1115
+ }
1116
+ $('#outTbl').addEventListener('click', async (e) => {
1117
+ if (e.target.closest('#decFold')) { decOpen = !decOpen; drawOutcomes(); return; }
1118
+ const b = e.target.closest('[data-verdict]'); if (b) { openVerdict((M.outcomes || []).find((r) => r.id === b.dataset.verdict)); return; }
1119
+ const k = e.target.closest('[data-keep]');
1120
+ if (k) {
1121
+ const r = (M.outcomes || []).find((x) => x.id === k.dataset.keep), dr = r && draftOf(r); if (!dr || k.disabled) return;
1122
+ k.disabled = true;
1123
+ 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 });
1124
+ if (!res || res.ok !== true) { k.disabled = false; toast((res && res.error) || 'The verdict could not be saved. Nothing changed.'); return; }
1125
+ toast('Kept ' + r.title + '.', { label: 'Undo', fn: () => undoVerdict(r) }); await load(); return;
1126
+ }
1127
+ const u = e.target.closest('[data-vundo]'); if (u) { const r = (M.outcomes || []).find((x) => x.id === u.dataset.vundo); if (r) undoVerdict(r); }
1128
+ });
1129
+ async function undoVerdict(r) {
1130
+ const res = await pmPost('/api/insights-records/verdict-undo', { ws: M.board.ws, board: M.board.id, ini: r.id });
1131
+ if (!res || res.ok !== true) { toast((res && res.error) || 'The verdict could not be taken back.'); return; }
1132
+ toast('Undone: ' + r.title + ' needs your verdict again.'); await load();
1133
+ }
879
1134
 
880
1135
  /* ── the side panel: New goal, New dashboard, Edit chart and the verdict ─────────────────────────────────────────────────────────── */
881
1136
  let sideKind = null, sideBack = null, SIDE_GO = null;
@@ -1157,13 +1412,8 @@ async function saveVerdict(r) {
1157
1412
  closeSide(); toast('Recorded: ' + (o ? o.dataset.vd : 'Iterate') + ' for ' + r.title + '.'); await load();
1158
1413
  }
1159
1414
 
1160
- /* the + menu */
1161
- $('#newMenu').addEventListener('click', (e) => {
1162
- const b = e.target.closest('[data-new]'); if (!b) return; closeMenus();
1163
- if (b.dataset.new === 'goal') openNewGoal();
1164
- else if (b.dataset.new === 'dash') openNewDash();
1165
- else { const D = curDash(), first = goalsShown().find((g) => g.key) || M.goals[0]; openChartEdit(first ? first.id : null, D); }
1166
- });
1415
+ /* + (Iq8Overview): a new metric or key result. New dashboard and Edit chart are in View. */
1416
+ $('#newB').addEventListener('click', (e) => { e.stopPropagation(); closeMenus(); openNewGoal(); });
1167
1417
 
1168
1418
  /* ── Library (IsLibrary; IsPhone right): what PMOS found in your work, the reports as Report · Next · Status, then the dashboards. Reports are
1169
1419
  * made in Home: New report and Change the setup hand off there. Every press posts to the console's report-setups routes
@@ -1360,9 +1610,9 @@ function openRequest(id) {
1360
1610
  }
1361
1611
 
1362
1612
  /* ── load ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── */
1363
- function redraw() { if (!M) return; drawBar(); drawStrip(); drawGoals(); drawOutcomes(); drawList(); }
1613
+ function redraw() { if (!M) return; drawBar(); drawStrip(); drawNs(); drawGoals(); drawOutcomes(); drawList(); drawDrafts(); }
1364
1614
  function draw() {
1365
- if (!dash || !M.dashboards.some((d) => d.id === dash)) dash = M.pinned || 'all';
1615
+ if (!dash || (dash !== TRENDS && !M.dashboards.some((d) => d.id === dash))) dash = M.pinned || 'all'; // Delivery trends stays open across a reload
1366
1616
  setPageGaps(((M.header && M.header.missing) || []).length);
1367
1617
  redraw();
1368
1618
  }
@@ -1383,6 +1633,13 @@ async function load() {
1383
1633
  if (on.length > 1 && first) await openPortfolio(on, true);
1384
1634
  // A shared goal link (?goal=<id>, from "Copy link" in the goal's ⋯) opens that goal once, after the first read.
1385
1635
  if (first) { const gid = new URLSearchParams(location.search).get('goal'); if (gid && allGoals().some((g) => g.id === gid)) openGoalDetail(gid); }
1386
- }
1387
- { const t = new URLSearchParams(location.search).get('tab'); setTab(t === 'outcomes' || t === 'library' ? t : 'goals'); }
1636
+ // an old tab link (Insights had Goals, Outcomes and Library): it lands on the section or the panel, once
1637
+ if (first) { const t = new URLSearchParams(location.search).get('tab'); if (t === 'outcomes' || t === 'library') setTab(t); }
1638
+ if (first) draftsLoad();
1639
+ if (!PF) { await noteOpen(); RI.loadProposals(M.board.ws, M.board.id).then(() => { if (M) drawStrip(); }); }
1640
+ }
1641
+ /* a report from Intelligence (batch 15 item 4): the view on screen is its first scope; a saved dashboard is its own */
1642
+ RI.mount({ model: () => (PF ? null : M), scope: () => { const D = curDash(); return D && D.saved ? 'dashboard:' + D.id : 'view'; }, viewer, close: () => closeMenus(), reload: () => load(),
1643
+ 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() }); },
1644
+ toast, esc, redrawStrip: () => drawStrip() });
1388
1645
  load();