create-pmos 0.432.0 → 0.434.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 (70) 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/briefing-premium-insights-test.js +63 -58
  7. package/workspace/changelog.json +24 -0
  8. package/workspace/guide/home.md +1 -1
  9. package/workspace/guide/index.md +1 -0
  10. package/workspace/guide/metric-drafts.md +21 -1
  11. package/workspace/guide/programs.md +1 -1
  12. package/workspace/guide/your-impact.md +58 -0
  13. package/workspace/impact-screens-test.js +149 -0
  14. package/workspace/intel-report-ui-test.js +1 -1
  15. package/workspace/intelligence-gaps-ui-test.js +13 -9
  16. package/workspace/lib/engine/outbox.js +1 -1
  17. package/workspace/lib/engine/records/index.js +11 -3
  18. package/workspace/lib/goal-status.js +199 -0
  19. package/workspace/lib/goal-watch.js +71 -0
  20. package/workspace/lib/headless.js +24 -2
  21. package/workspace/lib/impact-cli.js +72 -0
  22. package/workspace/lib/impact-runs.js +114 -0
  23. package/workspace/lib/impact.js +195 -0
  24. package/workspace/lib/insights-premium.js +43 -4
  25. package/workspace/lib/metric-draft-runs.js +33 -10
  26. package/workspace/lib/metric-drafts.js +118 -15
  27. package/workspace/lib/metric-read-runs.js +132 -0
  28. package/workspace/lib/metric-reads.js +129 -0
  29. package/workspace/lib/metrics-cli.js +100 -5
  30. package/workspace/lib/pmos-verbs.js +4 -1
  31. package/workspace/lib/route-modules.js +3 -0
  32. package/workspace/lib/routes-goal-status.js +111 -0
  33. package/workspace/lib/routes-impact-views.js +58 -0
  34. package/workspace/lib/routes-impact.js +91 -0
  35. package/workspace/lib/routes-insights-premium.js +20 -0
  36. package/workspace/lib/routes-metric-drafts.js +55 -4
  37. package/workspace/lib/routes-records.js +2 -0
  38. package/workspace/lib/settings-store.js +3 -0
  39. package/workspace/milestone-pins-test.js +8 -3
  40. package/workspace/okr-goals-ui-test.js +175 -0
  41. package/workspace/package-lock.json +2 -2
  42. package/workspace/package.json +1 -1
  43. package/workspace/product-lane-test.js +5 -5
  44. package/workspace/public/pm/bd-ini-panel.js +10 -2
  45. package/workspace/public/pm/bd-span.js +5 -4
  46. package/workspace/public/pm/cozy-adler.css +5 -0
  47. package/workspace/public/pm/cozy-adler.js +17 -9
  48. package/workspace/public/pm/cozy-insights.css +84 -0
  49. package/workspace/public/pm/cozy-settings.js +11 -1
  50. package/workspace/public/pm/home-app.js +61 -8
  51. package/workspace/public/pm/home-impact.css +16 -0
  52. package/workspace/public/pm/home-impact.js +72 -0
  53. package/workspace/public/pm/home-today.js +4 -2
  54. package/workspace/public/pm/impact.css +37 -0
  55. package/workspace/public/pm/impact.js +201 -0
  56. package/workspace/public/pm/okr-list.js +249 -0
  57. package/workspace/public/pm/premium-insights.js +222 -238
  58. package/workspace/public/pm/premium-vw-mtg.js +4 -1
  59. package/workspace/public/pm/stage-line.js +4 -3
  60. package/workspace/public/premium-intelligence.html +3 -2
  61. package/workspace/public/premium.html +1 -0
  62. package/workspace/server.js +56 -2
  63. package/workspace/skills/impact-detect.skill +46 -0
  64. package/workspace/skills/metric-read.skill +32 -0
  65. package/workspace/task-milestones-test.js +4 -3
  66. package/workspace/test-lists/goal-watch.json +9 -0
  67. package/workspace/test-lists/impact-screens.json +5 -0
  68. package/workspace/test-lists/impact-ui.json +9 -0
  69. package/workspace/test-lists/impact.json +9 -0
  70. package/workspace/test-lists/okr-goals-ui.json +5 -0
@@ -34,8 +34,10 @@ import * as PK from './cozy-pick.js'; // the one product picker Home, Board an
34
34
  import { openReport } from './premium-report-read.js';
35
35
  import { mountNav } from './cozy-nav.js';
36
36
  import { mountLivePill } from './cozy-live-pill.js';
37
+ import * as IM from './impact.js'; // Your impact's ✦ line (batch 16 item 7): a key result your work moved
37
38
  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
39
  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
40
+ import * as OK from './okr-list.js'; // Claude runs the OKRs (batch 16 item 6, 6-B): the goal list, its drafts, the ✦ line, ⋯ › Metrics, the notify choice
39
41
 
40
42
  let M = null; // the model
41
43
  let BM = null, bmErr = ''; // the Board measures (Delivery trends)
@@ -323,12 +325,34 @@ $('#moreB').addEventListener('click', () => {
323
325
  const R = M.reports || {}, nr = reportGroups().length, nd = savedDash().length, nf = (R.found || []).length + (R.asks || []).filter((a) => a.state === 'ready').length;
324
326
  $('#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
327
  $('#libNew').innerHTML = nf ? `<span class="cz-pill you">${nf} new</span>` : ''; // zero is silence
328
+ const nm = PF ? 0 : OK.metricsOf(M, today()).length; $('#metN').textContent = nm || '';
326
329
  });
330
+ /* ⋯ › Metrics (GsMetrics, GsMetricsTree): one list, goal metrics first, then the ones Claude watches with no goal (tagged "watch", no status).
331
+ * One switch shows the same list as a tree: the North Star, its inputs and the guardrails. A press opens the metric's goal in the Viewer. */
332
+ let metView = 'list';
333
+ try { metView = localStorage.getItem('pmos.okr.metrics.view') === 'tree' ? 'tree' : 'list'; } catch { metView = 'list'; }
334
+ function openMetrics() {
335
+ if (!M || PF) return;
336
+ viewer({ kind: 'Intelligence', title: 'Metrics', icon: 'chart', id: 'metrics', eye: 'Intelligence', render: (el) => {
337
+ const draw = () => {
338
+ const L = OK.metricsOf(M, today());
339
+ el.innerHTML = `<div class="okr-mbar" role="group" aria-label="View"><button type="button" class="cz-ib sm${metView === 'list' ? ' on' : ''}" data-mv2="list" aria-pressed="${metView === 'list'}" aria-label="As a list" title="As a list">${OK.SV(OK.P.list)}</button><button type="button" class="cz-ib sm${metView === 'tree' ? ' on' : ''}" data-mv2="tree" aria-pressed="${metView === 'tree'}" aria-label="As a tree" title="As a tree">${OK.SV(OK.P.tree)}</button></div><div class="okr-met">${OK.metricsHtml(L, metView)}</div>`;
340
+ };
341
+ draw();
342
+ el.addEventListener('click', (e) => {
343
+ const v = e.target.closest('[data-mv2]'); if (v) { metView = v.dataset.mv2; try { localStorage.setItem('pmos.okr.metrics.view', metView); } catch { /* a private window forgets it */ } draw(); return; }
344
+ const b = e.target.closest('[data-budget]'); if (b) { if (window.czViewer && window.czViewer.drill) window.czViewer.drill(); openBudget(b.dataset.budget); return; }
345
+ const g = e.target.closest('[data-goal]'); if (g && goalById(g.dataset.goal)) { if (window.czViewer && window.czViewer.drill) window.czViewer.drill(); openGoalDetail(g.dataset.goal); }
346
+ });
347
+ } });
348
+ }
327
349
  $('#moreMenu').addEventListener('click', (e) => {
328
350
  const b = e.target.closest('[data-more]'); if (!b || b.disabled) return; closeMenus();
329
351
  if (b.dataset.more === 'library') openLib();
330
352
  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(); } });
353
+ else if (b.dataset.more === 'metrics') openMetrics();
354
+ // Sources lives in Settings › Connectors (Fewer menus, brief 5; GsMore); with no Settings on the page, what this page reads in the Viewer
355
+ else if (b.dataset.more === 'sources') import('./cozy-settings.js').then((S) => S.openSettings('connectors')).catch(() => viewer({ kind: 'Intelligence', title: 'Sources', icon: 'source', eye: 'What this page reads', render: (el) => { el.innerHTML = sourcesHtml(); } }));
332
356
  else if (b.dataset.more === 'export') location.assign('/api/insights-records/export?' + wsQ() + (M.board.id ? 'board=' + encodeURIComponent(M.board.id) : ''));
333
357
  else if (b.dataset.more === 'about') viewer({ kind: 'Intelligence', title: 'About these numbers', icon: 'info', eye: 'Intelligence', render: (el) => { el.innerHTML = ABOUT; } });
334
358
  });
@@ -356,14 +380,27 @@ const ABOUT = '<div class="ins-about"><p>Every goal is a KR metric record of thi
356
380
  * /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
381
  let insIdx = 0;
358
382
  const insSkip = new Set(); // the findings put off with Not now, this visit only
383
+ /** The goals the list shows for this product: the North Star and the key results (its own, not a program's or an initiative's). */
384
+ const listGoals = () => (PF ? [] : M.goals.filter((g) => isOwnKr(g) && (g.role === 'north-star' || isKr(g))));
385
+ /** The ✦ line (GsM1–M5): the one thing that matters this week, from lib/goal-status.js (model.okr.line) or said from the goals and drafts. It is
386
+ * the strip's first item; the findings and the reports Claude proposes follow it. It never says "There is no insight yet". */
387
+ function okrLine() {
388
+ const run = DR && DR.run;
389
+ return OK.lineOf({ okr: M.okr, goals: listGoals(), budgets: M.budgets || [], drafts: drAll(), running: !!(run && run.state === 'running'), product: M.board.name });
390
+ }
359
391
  function stripList() {
360
392
  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());
393
+ // Your impact (batch 16 item 7, GmA4Moments): a key result that moved after your work, as one more ✦ line, with its source to open
394
+ const im = PF ? null : IM.intelItem(), mine = im ? [im] : [];
395
+ const ok = PF ? [] : [Object.assign({ okr: true, text: '', why: '' }, (() => { const L = okrLine(); return { text: L.head, why: L.sub, tone: L.tone, keepAll: L.keepAll, start: !!L.start }; })())];
396
+ if (I0.none) return ok.concat(PF ? [] : RI.stripItems(), mine);
397
+ const finds = [{ text: I0.text, why: I0.why || '', chart: I0.chart, move: I0.move || null, calm: !!I0.calm }].concat((I0.more || []).map((x) => ({ text: x.text, why: x.why || '', chart: x.chart, move: x.move || null })));
398
+ // a calm finding ("Nothing stands out") says what the ✦ line already says: it is left out
399
+ return ok.concat(finds.filter((f) => !(ok.length && f.calm)), PF ? [] : RI.stripItems(), mine);
363
400
  }
364
401
  function drawStrip() {
365
402
  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');
403
+ $('#insEye').textContent = ''; $('#insAct').innerHTML = ''; $('#insPg').innerHTML = ''; $('#insMv').hidden = true; $('#insMv').innerHTML = ''; $('#insHero').classList.remove('mv', 'crit');
367
404
  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
405
  const L = stripList(), open = L.map((f, i) => i).filter((i) => !insSkip.has(i));
369
406
  if (!open.includes(insIdx)) insIdx = open.length ? open[0] : 0;
@@ -371,25 +408,34 @@ function drawStrip() {
371
408
  $('#brief').textContent = f.text;
372
409
  $('#insWhy').textContent = f.why || '';
373
410
  // 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.
411
+ // proposal or drafts, handled otherwise. A broken limit is the one time the line turns red: it carries the alert, not a face (GsM4Break).
412
+ // The rows and charts below stay pure data.
413
+ const crit = f.okr && f.tone === 'crit';
414
+ $('#insHero').classList.toggle('crit', crit);
375
415
  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
416
+ if (sp && crit) { sp.classList.remove('ad'); sp.innerHTML = OK.SV(OK.P.alert, 20); }
417
+ else if (sp) { sp.classList.add('ad'); sp.innerHTML = AD.adler(f.report || (f.okr && f.tone === 'drafts') ? 'needs-you' : (f.okr ? f.tone === 'behind' : behind) || /^Straight answer/.test(f.text) || AD.moodOfText(f.text) === 'honest' ? 'honest' : 'handled', 40, { label: false }); }
418
+ $('#askWhy').href = homeAsk('insights', 'Why? ' + f.text);
419
+ $('#askWhy').hidden = !!(f.report || f.impact); $('#askWhy').style.display = f.report || f.impact ? 'none' : ''; // a report Claude proposes carries its own presses: See the draft, Not now, ✓ Set it up
379
420
  if (f.report) $('#insAct').innerHTML = RI.stripActs(f.report);
380
421
  const mv = !f.report && f.move ? f.move : null;
381
422
  $('#insHero').classList.toggle('mv', !!mv);
382
423
  if (mv) { $('#insMv').innerHTML = `${SV(I.spark)}<span>${esc(mv.text)}</span>`; $('#insMv').hidden = false; $('#insMv').classList.toggle('dn', !!mv.done); }
383
424
  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
425
  : `<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;
426
+ // the ✦ line's own press: ✓✓ keeps every draft (GsM1, GsM5); with nothing to read, ✦ asks Claude to draft the goals
427
+ const okAct = !f.okr ? '' : f.keepAll ? `<button type="button" class="cz-ib sm solid" data-okl="keep-all" aria-label="Keep all ${f.keepAll}" title="Keep all ${f.keepAll}">${OK.SV(OK.P.checks)}</button>`
428
+ : f.start && M.board.ws ? `<button type="button" class="cz-ib sm solid" data-okl="start" aria-label="Draft them" title="Draft them">${SV(I.spark)}</button>` : '';
429
+ if (!f.report) $('#insAct').innerHTML = mvAct + okAct;
386
430
  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;
431
+ 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 + okAct;
388
432
  $('#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
433
  }
434
+ if (f.impact && f.impact.url) $('#insAct').insertAdjacentHTML('beforeend', `<a class="cz-ib sm" href="${esc(f.impact.url)}"${/^https:/i.test(f.impact.url) ? ' target="_blank" rel="noopener noreferrer"' : ''} aria-label="Open the source: ${esc(f.impact.label)}" title="Open the source">${SV(I.open || 'M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5')}</a>`);
390
435
  }
391
436
  $('#insHero').addEventListener('click', async (e) => {
392
437
  if (e.target.closest('[data-rp]')) { await RI.stripPress(e); return; }
438
+ const k = e.target.closest('[data-okl]'); if (k) { await draftPress(k.dataset.okl, null, k); return; }
393
439
  const b = e.target.closest('[data-mv]'); if (b) { await pressMove(b); return; }
394
440
  const d = e.target.closest('[data-ins]'); if (d) { insIdx = +d.dataset.ins; drawStrip(); return; }
395
441
  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(); }
@@ -407,77 +453,39 @@ async function pressMove(b) {
407
453
  await load();
408
454
  }
409
455
 
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]];
456
+ /* ── the North Star (GsM1–M5; before it Iq8Overview's card with its inputs): the KR metric record with role north-star ── */
415
457
  const isOwnKr = (g) => !g.program && !g.initiative;
416
458
  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);
459
+ /** The North Star as the list's first row (GsM1–M5): its dot, its reading with the change since the quarter's first reading and its age; the
460
+ * chart is in the Viewer and its inputs are in the more menu, Metrics, as a tree. A drafted North Star (or a drafted input or guardrail) that is not a
461
+ * record yet is a hollow row with its keep press. Nothing to show: the card is not drawn (zero is silence). */
462
+ function nsMeta(g) {
463
+ if (g.reading && g.reading.txt) return OK.metaOf(g, today());
464
+ const S = g.series || [];
465
+ if (!S.length) return OK.metaOf(g, today());
466
+ const a = S[0], z = S[S.length - 1], d = z.v - a.v, pctU = /^%$/.test(String(g.unit || '').trim());
467
+ const ch = S.length > 1 && d !== 0 ? (d > 0 ? 'up ' : 'down ') + (Math.round(Math.abs(d) * 100) / 100) + (pctU ? '' : g.unit ? (/^[A-Za-z]/.test(g.unit) ? ' ' + g.unit : g.unit) : '') + ' since ' + md(day(a.at)) : '';
468
+ return [g.nowTxt, ch, OK.ageOf(z.at, today())].filter(Boolean).join(' · ');
454
469
  }
455
470
  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);
471
+ const box = $('#nsRow');
472
+ if (!M || PF) { box.hidden = true; box.innerHTML = ''; return; }
473
+ const g = nsGoal(), loose = looseDrafts().filter((r) => r.kind === 'metric' && (r.group === 'North Star' || r.group === 'Inputs' || r.group === 'Guardrails'));
474
+ if (!g && !loose.length) { box.hidden = true; box.innerHTML = ''; return; }
475
+ const rows = (g ? OK.rowHtml(g, { meta: nsMeta(g), drafts: draftsFor(g.id), drawDraft: drHtml, noOwner: !OK.whoOf(g), today: today() }) : '')
476
+ + loose.map((r) => (drEdit === r.id ? `<div class="okr-row">${drEditHtml(r)}</div>` : OK.draftRowHtml(r))).join('');
477
+ box.innerHTML = `<div class="okr-sec"><h2 class="okr-h">North Star</h2></div><div class="okr-card">${rows}</div>`;
478
+ box.hidden = false; box.classList.add('okr-ns');
469
479
  }
470
480
  $('#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);
481
+ const r = e.target.closest('[data-goal]'); if (r && e.target.closest('.okr-main')) openGoalDetail(r.dataset.goal);
474
482
  });
475
483
 
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. ── */
484
+ /* ── what Claude drafted (GsM1–M5; before it Iq8Suggest, Iq9Draft): GET /api/metric-drafts for this product. Each draft sits under the row it
485
+ * repairs (its `goal`), with drop / edit / keep as icon buttons; a drafted North Star or key result that is not a record yet is a hollow row of its own.
486
+ * keep-all in the ✦ line keeps them all. keep on a chase note or a ticket puts it in the outbox (it is sent from there); keep on Connect opens Settings ›
487
+ * Connectors. A keep that writes a record is lib/routes-metric-drafts.js; Undo takes it back. While a run drafts, the ✦ line says so. ── */
479
488
  let DR = null, drTimer = 0;
480
- const DR_STEPS = ['Read', 'Shape', 'Measure', 'Target', 'Ready'];
481
489
  async function draftsLoad() {
482
490
  clearTimeout(drTimer);
483
491
  if (!M || PF || !M.board.ws) { DR = null; drawDrafts(); return; }
@@ -486,73 +494,76 @@ async function draftsLoad() {
486
494
  DR = r && r.ok ? r : null; drawDrafts();
487
495
  if (DR && DR.run && DR.run.state === 'running') drTimer = setTimeout(draftsLoad, 4000);
488
496
  }
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). */
497
+ const drAll = () => OK.draftsOf(DR);
498
+ /** The drafts under one goal row. */
499
+ const draftsFor = (id) => drAll().filter((r) => r.goal === id);
500
+ /** A draft with no goal on the list: a drafted North Star or key result is drawn as its own hollow row; inputs and guardrails sit in the North
501
+ * Star card; anything else in the loose box under the ✦ line. */
502
+ const looseDrafts = () => { const ids = new Set(M.goals.map((g) => g.id).concat((M.budgets || []).map((b) => b.id))); return drAll().filter((r) => !r.goal || !ids.has(r.goal)); };
517
503
  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; }
504
+ /** ✎ on a draft: its words in place (and, on a drafted metric, its target and where it is measured); ✓ saves (POST /api/metric-drafts/edit), ✕
505
+ * or Escape puts it back. */
506
+ function drEditHtml(r) {
507
+ const raw = r.raw || {}, metric = r.kind === 'metric';
508
+ return `<div class="okr-dr okr-ed" data-dred="${esc(r.id)}"><span class="k">${OK.SV(OK.P.pen)}</span><div class="tx"><input class="ins-dri" data-drf="name" value="${esc(metric ? r.name : r.text)}" maxlength="${metric ? 120 : 400}" aria-label="What it says">`
509
+ + (r.kind === 'chase' ? `<textarea class="ins-dri" data-drf="body" rows="3" maxlength="2000" aria-label="The message">${esc(raw.body || '')}</textarea>` : '')
510
+ + (metric && raw.type !== 'Done or not' ? `<input class="ins-dri" data-drf="target" inputmode="decimal" value="${esc(raw.target == null ? '' : String(raw.target))}" aria-label="Target" placeholder="Target">` : '')
511
+ + (metric ? `<input class="ins-dri" data-drf="source" value="${esc(r.source || '')}" maxlength="40" aria-label="Measured by" placeholder="Measured by">` : '') + '</div>'
512
+ + `<div class="acts"><a class="cz-ib sm" href="${esc(homeAsk('insights', 'Change the draft ' + r.name + ': '))}" aria-label="Ask Claude in Home to change something else" title="Ask Claude in Home">${SV('M4 5h16v11H9l-5 4z')}</a>`
513
+ + `<button type="button" class="cz-ib sm" data-okd="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-okd="save" data-row="${esc(r.id)}" aria-label="Save ${esc(r.name)}" title="Save">${SV(I.chk)}</button></div></div>`;
514
+ }
515
+ const drHtml = (r) => (drEdit === r.id && r.state === 'open' ? drEditHtml(r) : OK.draftHtml(r));
516
+ /** The loose box: drafts that belong to no row on the list. Zero is silence. */
517
+ function drawDrafts() {
518
+ const box = $('#draftBox');
519
+ if (!M || PF) { box.hidden = true; box.innerHTML = ''; return; }
520
+ const placed = new Set(['North Star', 'Inputs', 'Guardrails', 'Key results']);
521
+ const L = looseDrafts().filter((r) => !(r.kind === 'metric' && placed.has(r.group)));
522
+ box.innerHTML = L.length ? `<div class="okr-card">${L.map((r) => `<div class="okr-row">${drHtml(r)}</div>`).join('')}</div>` : '';
523
+ box.hidden = !L.length;
524
+ if (M) { drawStrip(); drawNs(); drawGoals(); }
525
+ }
526
+ /** One press on a draft: keep (its act), drop, edit, save, cancel or undo; keep-all from the ✦ line; start asks Claude to draft the goals. */
527
+ async function draftPress(k, row, b) {
528
+ if (!M || !M.board.ws || (b && b.disabled)) return;
529
+ const r0 = row ? drAll().find((x) => x.id === row) : null, base = { ws: M.board.ws, scope: 'product', id: M.board.ws };
530
+ if (k === 'edit') { drEdit = row; drawDrafts(); const n = document.querySelector(`[data-dred="${CSS.escape(row)}"] [data-drf="name"]`); if (n) { n.focus(); n.select(); } return; }
537
531
  if (k === 'cancel') { drEdit = null; drawDrafts(); return; }
538
532
  if (k === 'save') {
539
533
  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') };
534
+ const fix = r0 && r0.kind !== 'metric';
535
+ const body = Object.assign({ row }, fix ? { text: val('name') } : { name: val('name') }, base);
536
+ if (val('body') !== undefined) body.body = val('body');
537
+ if (val('source') !== undefined) body.source = val('source');
541
538
  if (val('target') !== undefined) body.target = val('target');
542
539
  b.disabled = true;
543
540
  const res = await pmPost('/api/metric-drafts/edit', body);
544
541
  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;
542
+ drEdit = null; toast(res.changed === false ? 'Nothing changed.' : 'Saved. Keep it to use it as you wrote it.');
543
+ await draftsLoad(); return;
548
544
  }
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);
545
+ if (b) b.disabled = true;
546
+ const res = await pmPost('/api/metric-drafts/' + k, Object.assign({}, base, row ? { row } : {}));
547
+ if (!res || res.ok !== true) { if (b) b.disabled = false; toast((res && res.error) || 'It could not be done. Nothing changed.'); return; }
548
+ const name = r0 ? r0.text : 'it';
549
+ const said = k === 'start' ? 'I am drafting them. They appear under each goal.'
550
+ : k === 'keep-all' ? 'Kept ' + (res.kept || 'them all') + '. I read them from now on.'
551
+ : k === 'keep' ? (res.outbox ? (r0 && r0.kind === 'ticket' ? 'In the outbox for Jira.' : 'In the outbox. It goes as you.') : res.open === 'settings:connectors' ? 'Opening Connectors.' : 'Kept. I read it from now on.')
552
+ : k === 'drop' ? 'Not now: ' + name + '.' : k === 'undo' ? 'Undone.' : 'Done.';
553
+ toast(said, k === 'keep' || k === 'drop' ? { label: 'Undo', fn: async () => { await pmPost('/api/metric-drafts/undo', Object.assign({ row }, base)); await load(); await draftsLoad(); } } : undefined);
554
+ if (res.open === 'settings:connectors') import('./cozy-settings.js').then((S) => S.openSettings('connectors')).catch(() => {});
555
555
  await load(); await draftsLoad();
556
+ }
557
+ /* the draft presses, wherever a draft is drawn: under a row, in the North Star card, in the loose box */
558
+ document.addEventListener('click', (e) => {
559
+ const b = e.target.closest('[data-okd]'); if (!b || !b.closest('#stage')) return;
560
+ e.stopPropagation(); draftPress(b.dataset.okd, b.dataset.row || null, b);
561
+ }, true);
562
+ document.addEventListener('keydown', (e) => {
563
+ const f = e.target.closest && e.target.closest('[data-drf]'); if (!f) return;
564
+ const ed = f.closest('[data-dred]');
565
+ if (e.key === 'Enter' && !(f.tagName === 'TEXTAREA' && !e.metaKey && !e.ctrlKey)) { e.preventDefault(); const s = ed && ed.querySelector('[data-okd="save"]'); if (s) s.click(); }
566
+ if (e.key === 'Escape') { e.preventDefault(); drEdit = null; drawDrafts(); }
556
567
  });
557
568
 
558
569
  /* ── Reports and dashboards (⋯; the old Library tab) in a side panel: Found in your work, requests from Home, the reports, then the dashboards ── */
@@ -576,7 +587,6 @@ async function pinView() {
576
587
  }
577
588
 
578
589
  /* ── Goals (AgInsGoals) ─────────────────────────────────────────────────────────────────────────────────────────────────────────── */
579
- const COLS = 'ins-cols';
580
590
  const ownerHit = (L) => !filt.owner.length || L.some((o) => filt.owner.includes(o));
581
591
  function goalsShown() {
582
592
  if (dash === TRENDS) return [];
@@ -588,7 +598,7 @@ function goalsShown() {
588
598
  }
589
599
  /** 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
600
  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;
601
+ const isKr = (g) => !NOT_KR.includes(g.role) && !g.program && !g.initiative && !g.budget; // a budget's own reading record shows as its budget
592
602
  const TRACK_TONE = { late: 'late', 'at risk': 'risk', done: 'ok', 'on track': 'ok', 'on hold': 'q' };
593
603
  /** 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
594
604
  * recorded as skipped (its "Skipped <stage>" warning) is a dashed ring. */
@@ -611,25 +621,6 @@ function movePill(r) {
611
621
  }
612
622
  const initRow = (r, pill = true) => { const p = pill ? movePill(r) : null; return `<a class="ins-ini" href="${iniHref(r.id)}">${trackHtml(r)}<span class="n">${esc(r.title)}</span>${p ? `<span class="cz-pill ${p[0]}">${esc(p[1])}</span>` : ''}</a>`; };
613
623
  const TONE_BAR = { ok: 'var(--cz-dot-ok)', late: 'var(--cz-dot-late)', red: 'var(--cz-dot-red)', q: 'var(--cz-dot-q)', risk: 'var(--cz-dot-risk)' };
614
- function barHtml(g, cls = '') {
615
- return `<div class="ins-bar1${cls}" role="img" aria-label="${g.done === null ? 'No progress to read' : Math.round(g.done * 100) + '% of the way to the target'}${g.timeGone == null ? '' : ', ' + Math.round(g.timeGone * 100) + '% of its time gone'}"><i style="width:${g.done === null ? 0 : Math.round(g.done * 100)}%;background:${TONE_BAR[g.tone] || TONE_BAR.q}"></i>${g.timeGone == null ? '' : `<span class="today" title="today" style="left:${Math.round(g.timeGone * 100)}%"></span>`}</div>`;
616
- }
617
- /** The so-far sparkline: the readings at their dates across the goal's span, the target dashed, and the pace carried to the date, dashed. */
618
- function sparkHtml(g, w = 210, h = 40) {
619
- const c = g.key ? byKey(g.key) : null;
620
- if (!c) return g.readings ? `<span class="ins-one"><span class="note">${g.readings === 1 ? '1 reading' : g.readings + ' readings'}</span><span class="cz-pill ins-dash">No trend yet</span></span>` : '<span class="note">No reading yet</span>'; // IsMenus: the one value, never a flat line
621
- const t0 = day(c.pts[0].at), tl = day(c.pts[c.pts.length - 1].at), t1 = Math.max(tl, day(g.byAt) || tl);
622
- const ys = c.pts.map((p) => p.v).concat(g.target !== null ? [g.target] : [], g.proj ? [g.proj.atDue] : []), lo = Math.min(...ys), hi = Math.max(...ys), rg = hi - lo || 1;
623
- const x = (t) => 5 + (t1 > t0 ? (t - t0) / (t1 - t0) : 1) * (w - 10), y = (v) => 4 + (1 - (v - lo) / rg) * (h - 8);
624
- const pts = c.pts.map((p) => x(day(p.at)).toFixed(1) + ',' + y(p.v).toFixed(1)), last = pts[pts.length - 1].split(',');
625
- const fill = `${x(t0).toFixed(1)},${h} ${pts.join(' ')} ${last[0]},${h}`;
626
- const proj = g.proj && day(g.byAt) > tl ? `<polyline points="${last.join(',')} ${x(day(g.byAt)).toFixed(1)},${y(g.proj.atDue).toFixed(1)}" class="pj"/>` : '';
627
- return `<svg class="ins-spark" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="${esc(g.title + ': ' + c.pts.length + ' readings' + (g.targetTxt ? ', target ' + g.targetTxt : ''))}"><polygon points="${fill}" class="ar"/>${g.target !== null ? `<line x1="0" x2="${w}" y1="${y(g.target).toFixed(1)}" y2="${y(g.target).toFixed(1)}" class="tg"/>` : ''}${proj}<polyline points="${pts.join(' ')}" class="ln"/><circle cx="${last[0]}" cy="${last[1]}" r="3.6" class="dt" style="fill:${TONE_BAR[g.tone]}"/></svg>`;
628
- }
629
- /** A Count goal with a small whole target is drawn as blocks: one per unit of the target, the ones reached filled. */
630
- const isBlocks = (g) => g.type === 'Count' && Number.isInteger(g.target) && g.target >= 1 && g.target <= 12 && Number.isInteger(g.now) && g.now >= 0;
631
- const blocksHtml = (g, w, names = true) => `<div class="ins-blocks" style="width:${w}px" role="img" aria-label="${esc(g.now + ' of ' + g.target)}">${Array.from({ length: g.target }, (_, i) => `<i class="${i < g.now ? 'on' : ''}"></i>`).join('')}</div>`
632
- + (names && g.items && g.items.length ? `<div class="note ins-items">${esc(g.items.slice(0, g.now).join(', '))}</div>` : ''); // the reached items, when the goal records them
633
624
  /** Done or not: its steps as a checklist; Stay within: the readings over a green band that marks the budget, with no forecast. */
634
625
  const stepsHtml = (g) => `<div class="ins-steps">${(g.steps || []).map((s) => `<span class="${s.done ? 'on' : ''}"><i class="ins-cb${s.done ? ' on' : ''}">${s.done ? SV(I.chk, 3) : ''}</i>${esc(s.text)}</span>`).join('')}</div>`;
635
626
  /** pts [{ at, v }] over a band: the floor or ceiling `lim` to the chart's edge is green (inside the budget); the line has no target line and no
@@ -642,87 +633,50 @@ function bandSvg(pts, lim, ceil, tone, label, w = 210, h = 40) {
642
633
  const line = L.length > 1 ? `<polygon points="${L[0].split(',')[0]},${h} ${L.join(' ')} ${last[0]},${h}" class="ar"/><polyline points="${L.join(' ')}" class="ln"/>` : '';
643
634
  return `<svg class="ins-spark" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="${esc(label)}">${band}${line}<circle cx="${last[0]}" cy="${last[1]}" r="3.6" class="dt" style="fill:${TONE_BAR[tone] || TONE_BAR.q}"/></svg>`;
644
635
  }
645
- function soFarHtml(g, w = 210) {
646
- if (g.type === 'Done or not') return g.steps && g.steps.length ? stepsHtml(g) : '<span class="note">No steps recorded</span>';
647
- if (g.type === 'Stay within' && g.target !== null && g.series && g.series.length) {
648
- return bandSvg(g.series, g.target, g.limit !== 'floor', g.pace && g.pace.tone !== 'q' ? g.pace.tone : g.tone, g.title + ': ' + g.series.length + (g.series.length === 1 ? ' reading' : ' readings') + ', the green band is inside the budget', w);
649
- }
650
- if (isBlocks(g)) return blocksHtml(g, w);
651
- return sparkHtml(g, w);
652
- }
653
- const PACE_C = { ok: 'var(--cz-ok)', late: 'var(--cz-late)', risk: 'var(--cz-risk)', q: 'var(--cz-ink3)' };
654
- function goalSub(g) {
655
- const by = day(g.byAt), late = per && by !== null && by > per.to && per.key !== 'y' && per.key !== 'c';
656
- if (g.type === 'Done or not') return [g.steps && g.steps.length ? g.steps.filter((x) => x.done).length + ' of ' + g.steps.length + ' steps' : '', by !== null ? 'due ' + md(by) : ''].filter(Boolean).join(' · ');
657
- if (g.type === 'Stay within') return [g.dirTxt + ' ' + (g.targetTxt || ''), g.alwaysOn ? 'always on' : by !== null ? 'until ' + md(by) : ''].filter(Boolean).join(' · ');
658
- const from = g.baseTxt ? 'from ' + g.baseTxt + (g.fromAt && (g.type === 'Percentage' || g.type === 'Amount') ? ' on ' + md(day(g.fromAt)) : '') : '';
659
- const cp = late ? (g.checkpoints || []).find((c) => day(c.by) >= per.from && day(c.by) <= per.to) : null;
660
- const unitOf = (v) => { const u = String(g.unit || '').trim(); return v + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : ''); };
661
- return [g.dirTxt, from, late ? 'due ' + md(by) + ' ' + new Date(by).getUTCFullYear() + ' · ' + (cp ? per.short + ' checkpoint ' + unitOf(cp.target) : 'no ' + per.short + ' checkpoint recorded') : ''].filter(Boolean).join(' · ');
662
- }
663
- function goalRow(g) {
664
- const sel = selecting && picked.includes(g.id);
665
- return `<div class="ins-tr ins-row ${COLS}${sel ? ' sel' : ''}" role="row" data-goal="${esc(g.id)}" tabindex="0" aria-label="${esc(g.title)}"${selecting ? ` aria-selected="${sel}"` : ''}>`
666
- + `<div class="nm" role="cell"><span><b>${esc(g.title)}</b><small><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="ins-sub" title="${esc(goalSub(g))}">${esc(goalSub(g))}</span></small></span></div>`
667
- + `<div class="val" role="cell"><b>${esc(g.nowTxt || '—')}</b> <span class="note">${esc(g.targetTxt ? 'of ' + g.targetTxt : 'no target')}</span>${barHtml(g)}</div>`
668
- + `<div class="sofar" role="cell">${soFarHtml(g)}</div>`
669
- + `<div class="pace" role="cell"><b style="color:${PACE_C[g.pace.tone]}">${esc(g.pace.head)}</b><div class="note">${esc(g.pace.sub)}</div></div>`
670
- + `<div class="mv" role="cell">${g.moves.length ? g.moves.slice(0, 3).map((r) => initRow(r)).join('') + (g.moves.length > 3 ? `<span class="note">and ${g.moves.length - 3} more</span>` : '') : `<span class="note">${M.initiativesRead ? 'No initiative anchors to it' : 'The initiatives are not read yet'}</span>`}</div>`
671
- + '</div>';
672
- }
673
- /** A health budget (D59): always on. Its reading is its share of the board's open initiatives, against its quarterly cap (planning/okrs/health-budgets.md). */
674
- const pct = (v) => Math.round(v * 100) + '%';
675
- function budgetRow(b) {
676
- const R = b.reading, cap = b.cap;
677
- const val = R ? `<b>${R.n}</b> <span class="note">of ${R.total} open initiatives</span>` : '<b>—</b> <span class="note">' + (b.declared ? 'the initiatives are not read' : 'not in the budget registry') + '</span>';
678
- const scale = R && R.share !== null && cap !== null ? Math.max(cap * 1.5, R.share) || 1 : 1;
679
- const bar = R && R.share !== null && cap !== null ? `<div class="ins-bar1" role="img" aria-label="${esc(pct(R.share) + ' of open initiatives, cap ' + pct(cap))}"><i style="width:${Math.round(R.share / scale * 100)}%;background:${R.over ? TONE_BAR.late : TONE_BAR.ok}"></i><span class="today" title="cap" style="left:${Math.round(cap / scale * 100)}%"></span></div>` : barHtml({ done: null, timeGone: null, tone: 'q' });
680
- const pace = !R || R.share === null ? ['var(--cz-ink3)', '—', b.declared ? 'no open initiative to share' : 'add it to health-budgets.md to give it a cap']
681
- : R.over ? ['var(--cz-late)', 'Over its ' + pct(cap) + ' cap', pct(R.share) + ' of open initiatives'] : ['var(--cz-ok)', 'Within its ' + pct(cap) + ' cap', pct(R.share) + ' of open initiatives'];
682
- return `<div class="ins-tr ins-row ${COLS} ins-budget" role="row" data-budget="${esc(b.id)}" tabindex="0" aria-label="${esc(b.title)}">`
683
- + `<div class="nm" role="cell"><span><b>${esc(b.title)}</b><small><span class="cz-pill q ins-type">Stay within</span><span class="ins-sub">always on${cap !== null ? ' · cap ' + pct(cap) + ' of a quarter' : ''}</span></small></span></div>`
684
- + `<div class="val" role="cell">${val}${bar}</div>`
685
- + `<div class="sofar" role="cell">${R && R.share !== null && cap !== null ? bandSvg([{ at: M.today || iso(today()), v: R.share * 100 }], cap * 100, true, R.over ? 'late' : 'ok', b.title + ': ' + pct(R.share) + ' of open initiatives, the green band is inside its ' + pct(cap) + ' cap') : ''}<span class="note">${esc(b.covers ? 'Covers ' + b.covers : 'What it covers is not declared')}</span></div>`
686
- + `<div class="pace" role="cell"><b style="color:${pace[0]}">${esc(pace[1])}</b><div class="note">${esc(pace[2])}</div></div>`
687
- + `<div class="mv" role="cell">${b.moves.length ? b.moves.slice(0, 3).map((r) => initRow(r)).join('') : '<span class="note">No initiative anchors to it</span>'}</div></div>`;
688
- }
689
- const GRP_PILL = (L) => {
690
- const scored = L.filter((g) => g.tone !== 'q'), bad = scored.filter((g) => g.tone === 'late' || g.tone === 'red').length;
691
- return !scored.length ? '' : bad ? `<span class="cz-pill late">${bad} of ${L.length} behind</span>` : '<span class="cz-pill ok">on track</span>';
692
- };
636
+ /* the goal list (GsM1–M5): Key results, then Health budgets, one row per goal: the dot, the outcome, the reading with its age, and the owner. No
637
+ * sparkline and no initiative status on a row: the chart and what moves it are in the Viewer. The same list on a phone and a desktop. */
638
+ const okrRow = (g, o = {}) => OK.rowHtml(g, Object.assign({ today: today(), drafts: PF ? [] : draftsFor(g.id), drawDraft: drHtml, mark: markHtml,
639
+ selecting, sel: selecting && picked.includes(g.id), meta: PF ? [g.prod, OK.metaOf(g, today())].filter(Boolean).join(' · ') : undefined }, o));
640
+ const budgetOkr = (b) => OK.rowHtml(Object.assign({}, b, { title: b.outcome || b.title }), { budget: true, today: today(), meta: OK.budgetMeta(b, today()), dot: OK.dotOf(Object.assign({ anchor: b.anchor }, b)), drafts: draftsFor(b.id), drawDraft: drHtml, mark: markHtml });
693
641
  function drawGoals() {
694
642
  const G = goalsShown(), T = $('#goalTbl');
695
643
  document.body.classList.toggle('ins-trv', dash === TRENDS);
696
- if (dash === TRENDS) { T.innerHTML = bmHtml(true); drawCards([]); $('#goalCards').innerHTML = ''; return; }
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>`;
644
+ T.classList.toggle('okr-list', dash !== TRENDS);
645
+ $('#goalCards').innerHTML = '';
646
+ if (dash === TRENDS) { T.innerHTML = bmHtml(true); return; }
698
647
  const D = curDash();
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);
701
- drawCards([]); return;
648
+ const krDrafts = PF ? [] : looseDrafts().filter((r) => r.kind === 'metric' && r.group === 'Key results');
649
+ const sub = per ? per.label : '';
650
+ const head = `<div class="okr-sec"><h2 class="okr-h">Key results</h2><span class="note">${esc(sub)}</span></div>`;
651
+ if (!M.goals.filter(isKr).length && !krDrafts.length) {
652
+ T.innerHTML = head + '<div class="okr-card"><p class="okr-none">No key result is recorded for this workspace.</p></div>' + budgetsHtml(D);
653
+ return;
702
654
  }
703
- /* by objective; Portfolio groups by product, each product's objectives said in its rows */
655
+ /* by objective when there is more than one; Portfolio groups by product */
704
656
  const keyOf = (g) => (PF ? g.prod : g.pillar || '');
705
657
  const by = new Map(); for (const g of G) { const k = keyOf(g); if (!by.has(k)) by.set(k, []); by.get(k).push(g); }
706
- const objs = [...new Set(M.goals.map((g) => g.pillar || ''))];
707
- const head1 = (k) => (PF ? esc(k || 'A product') : k ? 'Objective ' + (objs.indexOf(k) + 1) + ' · ' + esc(k) : 'No objective');
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('');
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);
710
- drawCards(G);
658
+ const objs = [...new Set(M.goals.filter(isKr).map((g) => g.pillar || ''))];
659
+ const sub1 = by.size > 1 || PF ? (k) => `<p class="okr-obj">${PF ? esc(k || 'A product') : k ? 'Objective ' + (objs.indexOf(k) + 1) + ' · ' + esc(k) : 'No objective'}</p>` : () => '';
660
+ const groups = [...by.entries()].map(([k, L]) => sub1(k) + L.map((g) => okrRow(g)).join('')).join('');
661
+ const drafted = krDrafts.map((r) => (drEdit === r.id ? `<div class="okr-row">${drEditHtml(r)}</div>` : OK.draftRowHtml(r))).join('');
662
+ T.innerHTML = head + (G.length || drafted ? `<div class="okr-card">${groups}${drafted}</div>` : `<div class="okr-card"><p class="okr-none">No goal matches${find ? ' “' + esc(find) + '”' : ''}${noFilter() ? '' : ' this filter'} in ${esc(per.label)}. <button type="button" class="lk" id="goalsAll">Show every goal</button></p></div>`) + budgetsHtml(D);
711
663
  }
664
+ const pct = (v) => Math.round(v * 100) + '%';
712
665
  function budgetsHtml(D) {
713
- if (PF || D.saved || D.id.startsWith('p:') || !M.initiativesRead || (filt.kind.length && !filt.kind.includes('budgets'))) return '';
666
+ if (PF || D.saved || D.id.startsWith('p:') || (!M.initiativesRead && !(M.budgets || []).length) || (filt.kind.length && !filt.kind.includes('budgets'))) return '';
714
667
  const B = (M.budgets || []).filter((b) => hit(b.title, ...b.moves.map((m) => m.title)) && ownerHit(b.moves.map((m) => m.owner).filter(Boolean)) && (!filt.status.length || filt.status.includes(budgetStatus(b))));
715
- return '<div class="ins-grp" role="row"><span role="cell">Health budgets</span> <span class="q">always on, judged every week</span></div>'
716
- + (B.length ? B.map(budgetRow).join('') : '<div class="ins-empty ins-sm2">No health budget is declared and no initiative anchors to one.</div>');
668
+ if (!B.length) return ''; // zero is silence
669
+ return `<div class="okr-sec"><h2 class="okr-h">Health budgets</h2></div><div class="okr-card">${B.map(budgetOkr).join('')}</div>`;
717
670
  }
718
671
  $('#goalTbl').addEventListener('click', (e) => {
719
672
  if (e.target.closest('#goalsAll')) { find = ''; $('#findIn').value = ''; clearFilter(); per = periods()[3]; redraw(); return; }
720
673
  if (e.target.closest('a')) return;
721
674
  const tile = e.target.closest('[data-tile]'); if (tile) { if (tgOpen === tile.dataset.tile) closeTarget(true); else openTarget(tile.dataset.tile); return; }
675
+ if (e.target.closest('.okr-dr')) return; // a draft under a row has its own presses
722
676
  const bu = e.target.closest('[data-budget]'); if (bu) { openBudget(bu.dataset.budget); return; }
723
677
  const r = e.target.closest('[data-goal]'); if (r) pressGoal(r.dataset.goal);
724
678
  });
725
- $('#goalTbl').addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; const r = e.target.closest && e.target.closest('.ins-row, [data-tile]'); if (!r || e.target !== r) return; e.preventDefault(); r.click(); });
679
+ $('#goalTbl').addEventListener('keydown', (e) => { if (e.key !== 'Enter' && e.key !== ' ') return; const r = e.target.closest && e.target.closest('.okr-main, .ins-row, [data-tile]'); if (!r || e.target !== r) return; e.preventDefault(); r.click(); });
726
680
  /** A goal press: picks it while New dashboard is open; opens Edit chart on a saved dashboard (AgInsChart); otherwise the goal's detail (IsGoal). */
727
681
  function pressGoal(id) {
728
682
  if (selecting) { picked = picked.includes(id) ? picked.filter((x) => x !== id) : picked.concat(id); drawGoals(); drawDashSide(); return; }
@@ -733,7 +687,7 @@ function pressGoal(id) {
733
687
  const nextMonday = () => { const t = today(), d = new Date(t).getUTCDay(); return t + ((8 - d) % 7 || 7) * DAY; };
734
688
  /** Where the next reading comes from: a read source is read every Monday (New goal says so); a typed one waits for you. */
735
689
  const nextReading = (g) => (!g.source || g.source === 'typed' ? 'You type its readings in.' : 'The next reading comes from ' + (SRC_NAME[g.source] || g.source) + ' on ' + md(nextMonday()) + '.');
736
- const srcOf = (g) => (g.source ? SRC_NAME[g.source] || g.source : 'Recorded');
690
+ const srcOf = (g) => (g.recipe && g.recipe.connector ? g.recipe.connector : g.source ? SRC_NAME[g.source] || g.source : 'Recorded');
737
691
  const unitV = (g, v) => { const u = String(g.unit || '').trim(); return String(v) + (u ? (/^[A-Za-z]/.test(u) ? ' ' + u : u) : ''); };
738
692
  /** The ship dates of the work that moves a goal: a mark with the initiative's name where it falls inside the readings. */
739
693
  const shipsOf = (g) => (g.moves || []).filter((r) => r.endAt && (r.idx >= 5 || r.status === 'done')).map((r) => ({ t: day(r.endAt), label: r.title + ' shipped' })).filter((x) => x.t !== null);
@@ -804,20 +758,46 @@ const CHEV = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke
804
758
  const moveRow = (r) => { const sub = r.milestone ? '<i class="ins-dia" aria-hidden="true"></i>' + esc(r.milestone.name + (r.end ? ', plan ' + md(day(r.endAt)) : '')) : esc([r.stageLabel, r.end ? 'plan ' + md(day(r.endAt)) : ''].filter(Boolean).join(', '));
805
759
  return `<a class="ovw ins-mvr" href="${iniHref(r.id)}"><span class="go"><span class="tl" aria-hidden="true">${FLAG}</span><span class="tx"><b>${esc(r.title)}</b>${sub ? `<small>${sub}</small>` : ''}</span><span class="cv">${CHEV}</span></span></a>`; };
806
760
  const movedHtml = (g) => (g.moves.length ? `<div class="ins-mvl">${g.moves.map(moveRow).join('')}</div>` : `<p class="note">${M.initiativesRead ? 'No initiative anchors to it yet. An initiative moves it once its anchor names it.' : 'The initiatives are not read yet.'}</p>`);
761
+ /** Why the goal moved, in Claude's words (GsViewer's ✦ card): lib/goal-status.js's reading.why, else the finding on this goal's chart, else its
762
+ * pace said plainly. '' when there is nothing to say. */
763
+ function whyOf(g) {
764
+ if (g.reading && g.reading.why) return g.reading.why;
765
+ const f = (M.findings || []).find((x) => x.chart && x.chart === g.key && x.kind !== 'calm');
766
+ if (f) return f.text + (f.why ? ' ' + f.why : '');
767
+ const P = g.pace || {};
768
+ return P.head && P.head !== '—' ? P.head + (P.sub ? ', ' + P.sub : '') + '.' : '';
769
+ }
770
+ /** How the goal is read (fold 1): the recipe (source, query, cadence) and its last read, honest when it could not read; a typed goal says so. */
771
+ function readHtml(g, o) {
772
+ const R = g.recipe, L = R && R.last;
773
+ const rows = R ? [['Source', R.connector || '—'], R.query ? ['What I read', R.query] : null, ['How often', R.cadence ? R.cadence[0].toUpperCase() + R.cadence.slice(1) : '—'],
774
+ ['Last read', L ? md(day(L.at)) + (L.ok ? '' : ' · could not read' + (L.error ? ': ' + L.error : '')) : 'Not read yet']].filter(Boolean)
775
+ : [['Source', srcOf(g) === 'Recorded' ? 'Typed in' : srcOf(g)], ['Next reading', nextReading(g)]];
776
+ return rows.map(([k, v]) => `<div class="ins-trow"><span>${esc(k)}</span><span class="note">${esc(v)}</span></div>`).join('') + readingsHtml(g, o);
777
+ }
778
+ /** History (fold 3): what Claude changed and what the PM kept (lib/goal-status.js history), newest first. */
779
+ const historyHtml = (g) => ((g.history || []).length ? (g.history || []).slice().reverse().map((h) => `<div class="ins-trow"><span>${esc(md(day(h.at)))}</span><span class="note">${esc(h.text)}</span></div>`).join('') : '<p class="note">Nothing changed yet.</p>');
780
+ /** The goal Viewer (GsViewer): its reading against its line with the owner, the chart, why it moved (with the work that moves it), then three
781
+ * folds: How I read it, What it counts and History. On dashboards folds under them when the PM keeps a saved dashboard. */
807
782
  function goalBodyHtml(g, o) {
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;
783
+ const c = g.key ? byKey(g.key) : null, phone = isPhone(), steps = g.type === 'Done or not' && g.steps && g.steps.length;
809
784
  const chart = steps ? stepsHtml(g) : c ? detailSvg(g, c, phone ? 330 : 470, phone ? 140 : 160) : emptyTrend(g, o.own);
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>`;
785
+ const d = OK.dotOf(g), R = g.reading || {}, prog = R.txt || OK.progressOf(g);
786
+ const line = R.line || (d === 'behind' && g.pace && g.pace.sub ? g.pace.sub : '');
787
+ const head = `<div class="okr-vh">${OK.dotHtml(d)}<b>${esc(prog || OK.DOT_SAY[d])}</b>${line ? `<span class="note">${esc(line)}</span>` : ''}${PF && g.prod ? `<span class="note">${esc(g.prod)}</span>` : ''}<span class="okr-sp"></span>${OK.avHtml(OK.whoOf(g))}</div>`;
812
788
  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>` : '';
789
+ const why = whyOf(g), moves = g.moves || [];
790
+ const whyCard = why || moves.length ? `<div class="okr-why"><span class="sp" aria-hidden="true">${SV(I.spark)}</span><div>${why ? `<p>${esc(why)}</p>` : ''}${moves.length ? `<div class="ins-mvl">${moves.map(moveRow).join('')}</div>` : ''}</div></div>` : '';
813
791
  const onDash = savedDash().filter((D) => D.charts.includes(g.id)).length;
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>`;
792
+ const R0 = g.recipe;
815
793
  const rows = [
816
- { id: 'read', title: 'Readings', count: g.series.length, open: o.open === 'read', render: () => readingsHtml(g, o) },
794
+ { id: 'read', title: 'How I read it', count: R0 && R0.connector ? R0.connector : srcOf(g) === 'Recorded' ? 'typed in' : srcOf(g), open: o.open === 'read', render: () => readHtml(g, o) },
795
+ { id: 'counts', title: 'What it counts', count: g.defn ? '' : 'not written yet', render: () => `<p class="note">${esc(g.defn || 'No definition is written for it yet. I write one with how I read it, and you keep it with ✓.')}</p>` },
796
+ { id: 'hist', title: 'History', count: (g.history || []).length || '', render: () => historyHtml(g) },
817
797
  o.own && savedDash().length ? { id: 'dash', title: 'On dashboards', count: onDash, render: () => dashSwitches(g) } : null,
818
798
  ];
819
799
  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;
800
+ return head + form + `<div class="ins-gbig">${chart}</div>` + whyCard + window.czViewer.czSections(rows, { key: 'goal' }) + '<p class="note ins-gmsg" data-gmsg role="status"></p>' + ask;
821
801
  }
822
802
  /** The goal as plain text, for Copy as text. */
823
803
  function goalText(g) {
@@ -826,6 +806,16 @@ function goalText(g) {
826
806
  }
827
807
  const goalLink = (g) => new URL(setQ({ goal: g.id, tab: null }), location.href).href;
828
808
  function copyText(text, said) { try { navigator.clipboard.writeText(text).then(() => toast(said), () => toast('This browser did not allow the copy.')); } catch { toast('This browser did not allow the copy.'); } }
809
+ /** The notify choice of one goal (GsNotify): POST /api/goals/notify { ws, id, notify }. Said back in a toast with Undo. */
810
+ async function setNotify(g, k) {
811
+ const was = g.notify || 'intel'; if (was === k) return;
812
+ const r = await pmPost('/api/goals/notify', { ws: goalWs(g), id: goalRid(g), notify: k });
813
+ if (!r || r.ok !== true) { toast((r && r.error) || 'It could not be saved. Nothing changed.'); return; }
814
+ g.notify = k;
815
+ const say = { push: 'I will notify you when it falls behind.', intel: 'It shows only in Intelligence.', quiet: 'Quiet. I still read it.' }[k];
816
+ toast(say, { label: 'Undo', fn: async () => { await pmPost('/api/goals/notify', { ws: goalWs(g), id: goalRid(g), notify: was }); await load(); } });
817
+ await load();
818
+ }
829
819
  let ovCss = false;
830
820
  function openGoalDetail(id, open0) {
831
821
  let g = goalById(id); if (!g) return;
@@ -833,12 +823,22 @@ function openGoalDetail(id, open0) {
833
823
  const own = goalWs(g) === M.board.ws, st = { open: open0 || '', more: false, adding: false, own };
834
824
  const kr = krId(g);
835
825
  const more = [], stepsGoal = g.type === 'Done or not' && g.steps && g.steps.length;
826
+ if (own && g.recipe) more.push({ label: 'Read it now', note: g.recipe.connector || '', on: async () => {
827
+ const r = await pmPost('/api/goal-status/read', { ws: goalWs(g), id: goalRid(g) });
828
+ toast(r && r.ok === true ? 'Read. The goal shows the new reading.' : (r && r.error) || 'It could not be read. Nothing changed.'); if (r && r.ok === true) await load();
829
+ } });
836
830
  if (own && !stepsGoal) more.push({ label: 'Add a reading', on: () => { const el = window.czViewer && window.czViewer.body(); st.adding = true; if (el) { el.innerHTML = goalBodyHtml(g, st); const f = el.querySelector('[data-rdf] [name="v"]'); if (f) f.focus(); } } });
837
831
  if (own && M.goals.some((x) => x.id === g.id)) more.push({ label: 'Edit chart', on: () => openChartEdit(g.id) });
838
832
  if (more.length) more.push({ sep: true });
839
833
  more.push({ label: 'Copy link', on: () => copyText(goalLink(g), 'Link copied.') }, { label: 'Copy as text', on: () => copyText(goalText(g), 'Copied as text.') });
834
+ // GsNotify: how Claude tells the PM about this goal. Only in Intelligence is the default and Claude's pick; a broken limit pushes once either way
835
+ // unless the goal is Quiet. The choice is stored on the goal (POST /api/goals/notify).
836
+ const NOTIFY = [['push', 'Notify me', 'when it falls behind', 'bell'], ['intel', 'Only in Intelligence', '✦ my pick', 'spark'], ['quiet', 'Quiet', '', 'quiet']];
837
+ const notifyItems = () => (own && !PF ? NOTIFY.map(([k, label, note]) => ({ label, note: [note, (g.notify || 'intel') === k ? 'on' : ''].filter(Boolean).join(' · '), on: () => setNotify(g, k) })).concat({ sep: true }) : []);
838
+ const moreOf = () => notifyItems().concat(more);
840
839
  const rp = own && !PF ? RI.viewerPress('goal:' + id) : null; // RfA1: a key result's panel makes a report too
841
- const body = vwOpen({ kind: 'Goal', title: (kr ? kr + ' · ' : '') + g.title, icon: 'goal', id: 'goal:' + id, more,
840
+ const subOf = () => [kr, g.targetTxt ? g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : ''].filter(Boolean).join(' · ');
841
+ const body = vwOpen({ kind: 'Goal', title: g.title, sub: subOf(), icon: 'goal', id: 'goal:' + id, more: moreOf,
842
842
  discuss: true, presses: rp ? [rp] : null, onPress: (act) => { if (rp && act === rp.act) rp.run(); },
843
843
  render: (el) => {
844
844
  el.classList.add('ins-vbody', 'ins-xv');
@@ -909,22 +909,6 @@ function openBudget(id) {
909
909
  el.innerHTML = V.czSummary(sum) + meter + V.czSections(rows, { key: 'budget' });
910
910
  } });
911
911
  }
912
- /* the phone (AgInsPhone): one card per goal, its status at the top right, its value, its so-far, its bar and the first initiative that moves it */
913
- function cardPill(g) {
914
- const t = g.pace && g.pace.tone !== 'q' ? g.pace.tone : g.tone;
915
- if (t === 'late' || t === 'red') return ['late', 'Behind'];
916
- if (t === 'ok') return g.done !== null && g.timeGone != null && g.done > g.timeGone ? ['ok', 'Ahead'] : ['ok', 'On track'];
917
- return null;
918
- }
919
- function drawCards(G) {
920
- $('#goalCards').innerHTML = G.map((g) => {
921
- const p = cardPill(g), tg = g.targetTxt ? (g.type === 'Count' ? 'of ' : 'target ') + g.targetTxt + (g.byAt ? ' by ' + md(day(g.byAt)) : '') : 'no target';
922
- return `<div class="ins-card" role="listitem" data-goal="${esc(g.id)}" tabindex="0" aria-label="${esc(g.title)}"><div class="ins-ch"><b>${esc(g.title)}</b>${p ? `<span class="cz-pill ${p[0]}">${p[1]}</span>` : ''}</div>`
923
- + `<div class="ins-cs"><span class="cz-pill q ins-type">${esc(g.type)}</span><span class="note">${esc(tg)}</span></div>`
924
- + `<div class="ins-cv"><b>${esc(g.nowTxt || '—')}</b><span class="ins-cg">${isBlocks(g) ? blocksHtml(g, 190, false) : g.type === 'Stay within' && g.series.length && g.target !== null ? bandSvg(g.series, g.target, g.limit !== 'floor', g.tone, g.title, 190, 30) : g.key ? sparkHtml(g, 190, 30) : ''}</span></div>${barHtml(g, ' ins-wide')}`
925
- + (g.moves[0] ? `<div class="ins-c1">${initRow(g.moves[0], false)}</div>` : '') + '</div>';
926
- }).join('') || (M.goals.length ? '<p class="note">No goal in this period.</p>' : '<p class="note">No goal is recorded for this workspace.</p>');
927
- }
928
912
  $('#goalCards').addEventListener('click', (e) => { if (e.target.closest('a')) return; const c = e.target.closest('[data-goal]'); if (c) pressGoal(c.dataset.goal); });
929
913
 
930
914
  /* ── Delivery trends: six tiles from the Board's measures (AgInsGoals, IsTarget): a label, the value, a small line with its end dot and the
@@ -1636,7 +1620,7 @@ async function load() {
1636
1620
  // an old tab link (Insights had Goals, Outcomes and Library): it lands on the section or the panel, once
1637
1621
  if (first) { const t = new URLSearchParams(location.search).get('tab'); if (t === 'outcomes' || t === 'library') setTab(t); }
1638
1622
  if (first) draftsLoad();
1639
- if (!PF) { await noteOpen(); RI.loadProposals(M.board.ws, M.board.id).then(() => { if (M) drawStrip(); }); }
1623
+ if (!PF) { await noteOpen(); RI.loadProposals(M.board.ws, M.board.id).then(() => { if (M) drawStrip(); }); IM.readWeek().then(() => { if (M && IM.intelItem()) drawStrip(); }).catch(() => {}); }
1640
1624
  }
1641
1625
  /* a report from Intelligence (batch 15 item 4): the view on screen is its first scope; a saved dashboard is its own */
1642
1626
  RI.mount({ model: () => (PF ? null : M), scope: () => { const D = curDash(); return D && D.saved ? 'dashboard:' + D.id : 'view'; }, viewer, close: () => closeMenus(), reload: () => load(),