create-pmos 0.397.0 → 0.399.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 (195) 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-adddoc-test.js +105 -52
  8. package/workspace/briefing-premium-board-test.js +284 -128
  9. package/workspace/briefing-premium-calendar-2-test.js +135 -198
  10. package/workspace/briefing-premium-calendar-3-test.js +143 -418
  11. package/workspace/briefing-premium-calendar-test.js +85 -196
  12. package/workspace/briefing-premium-doc-edit-test.js +99 -83
  13. package/workspace/briefing-premium-initiative-test.js +175 -290
  14. package/workspace/briefing-premium-insights-test.js +414 -219
  15. package/workspace/briefing-premium-metrics-test.js +55 -97
  16. package/workspace/briefing-premium-products-test.js +44 -28
  17. package/workspace/briefing-premium-sources-test.js +70 -49
  18. package/workspace/briefing-premium-test.js +155 -648
  19. package/workspace/briefing-premium-work-test.js +88 -283
  20. package/workspace/changelog.json +24 -0
  21. package/workspace/ev-everywhere-test.js +210 -0
  22. package/workspace/fixtures/board-premium-trail.js +32 -0
  23. package/workspace/fixtures/premium-viewer-fixtures.js +187 -0
  24. package/workspace/guide/briefing-premium.md +3 -1
  25. package/workspace/guide/home.md +68 -0
  26. package/workspace/guide/index.md +1 -0
  27. package/workspace/lib/agent-roles.js +71 -0
  28. package/workspace/lib/board-grill.js +63 -0
  29. package/workspace/lib/board-premium.js +121 -24
  30. package/workspace/lib/board-trail.js +223 -0
  31. package/workspace/lib/home-work-item.js +58 -0
  32. package/workspace/lib/initiative-layout.js +77 -0
  33. package/workspace/lib/insights-goals.js +196 -0
  34. package/workspace/lib/insights-premium.js +64 -15
  35. package/workspace/lib/insights-records.js +115 -0
  36. package/workspace/lib/jira-tickets.js +1 -1
  37. package/workspace/lib/meeting-points.js +52 -0
  38. package/workspace/lib/news-for-you.js +88 -0
  39. package/workspace/lib/notes-series.js +29 -6
  40. package/workspace/lib/report-confirm.js +48 -0
  41. package/workspace/lib/route-modules.js +12 -0
  42. package/workspace/lib/routes-board-docs.js +46 -0
  43. package/workspace/lib/routes-board-grill.js +90 -0
  44. package/workspace/lib/routes-board-trail.js +33 -0
  45. package/workspace/lib/routes-home-desk.js +176 -0
  46. package/workspace/lib/routes-home-review.js +108 -0
  47. package/workspace/lib/routes-initiative-layout.js +57 -0
  48. package/workspace/lib/routes-insights-premium.js +16 -4
  49. package/workspace/lib/routes-insights-records.js +133 -0
  50. package/workspace/lib/routes-meeting-points.js +37 -0
  51. package/workspace/lib/routes-news.js +57 -0
  52. package/workspace/lib/routes-notes.js +3 -1
  53. package/workspace/lib/routes-report-confirm.js +31 -0
  54. package/workspace/lib/routes-search.js +38 -0
  55. package/workspace/lib/routes-viewer.js +108 -0
  56. package/workspace/lib/search-index.js +176 -0
  57. package/workspace/lib/transcript-steps.js +123 -0
  58. package/workspace/lib/viewer-meeting.js +205 -0
  59. package/workspace/lib/viewer-report.js +89 -0
  60. package/workspace/package-lock.json +2 -2
  61. package/workspace/package.json +1 -1
  62. package/workspace/premium-board-actions-test.js +128 -82
  63. package/workspace/premium-briefing-depth-test.js +104 -90
  64. package/workspace/premium-chat-attach-test.js +54 -63
  65. package/workspace/premium-chat-chart-tab-test.js +37 -37
  66. package/workspace/premium-chat-context-test.js +19 -18
  67. package/workspace/premium-chat-goal-view-test.js +23 -23
  68. package/workspace/premium-chat-notes-test.js +26 -31
  69. package/workspace/premium-chat-report-tab-test.js +46 -28
  70. package/workspace/premium-chat-term-test.js +16 -16
  71. package/workspace/premium-chat-viewer-test.js +60 -59
  72. package/workspace/premium-core-doc-issue-test.js +52 -43
  73. package/workspace/premium-html-viewer-test.js +14 -17
  74. package/workspace/premium-phone-card-test.js +10 -3
  75. package/workspace/premium-phone-room-test.js +41 -35
  76. package/workspace/premium-report-read-test.js +152 -197
  77. package/workspace/premium-viewer-download-test.js +19 -22
  78. package/workspace/premium-viewer-flicker-test.js +11 -16
  79. package/workspace/premium-viewer-share-test.js +6 -9
  80. package/workspace/premium-viewer-test.js +41 -60
  81. package/workspace/premium-vw-backlog-test.js +53 -33
  82. package/workspace/premium-vw-cal-test.js +97 -128
  83. package/workspace/premium-vw-copy-test.js +17 -33
  84. package/workspace/premium-vw-doc-test.js +17 -10
  85. package/workspace/premium-vw-item-test.js +50 -49
  86. package/workspace/premium-vw-jira-test.js +53 -27
  87. package/workspace/premium-vw-meet-test.js +115 -187
  88. package/workspace/premium-vw-notes-test.js +88 -109
  89. package/workspace/premium-vw-rec-test.js +71 -194
  90. package/workspace/premium-vw-slides-test.js +46 -50
  91. package/workspace/premium-welcome-test.js +3 -2
  92. package/workspace/premium-work-depth-test.js +61 -53
  93. package/workspace/public/pm/bd-acts.js +383 -0
  94. package/workspace/public/pm/bd-asks.js +261 -0
  95. package/workspace/public/pm/bd-pop.js +59 -0
  96. package/workspace/public/pm/bd-span.js +222 -82
  97. package/workspace/public/pm/bd-stages.js +25 -11
  98. package/workspace/public/pm/bd-views.js +169 -0
  99. package/workspace/public/pm/c3-doc-sheet.js +1 -1
  100. package/workspace/public/pm/c3-md.js +3 -395
  101. package/workspace/public/pm/c3-phone-detail.js +1 -1
  102. package/workspace/public/pm/c3-phone-model.js +3 -68
  103. package/workspace/public/pm/chat-term.js +3 -3
  104. package/workspace/public/pm/cozy-board.css +798 -230
  105. package/workspace/public/pm/cozy-ev.css +228 -0
  106. package/workspace/public/pm/cozy-evmodel.js +106 -0
  107. package/workspace/public/pm/cozy-evui.js +47 -0
  108. package/workspace/public/pm/cozy-home.css +570 -142
  109. package/workspace/public/pm/cozy-home.js +5 -3
  110. package/workspace/public/pm/cozy-insights.css +437 -170
  111. package/workspace/public/pm/cozy-md.js +396 -0
  112. package/workspace/public/pm/cozy-nav.js +104 -29
  113. package/workspace/public/pm/cozy-news.js +140 -0
  114. package/workspace/public/pm/cozy-placeholder.js +26 -0
  115. package/workspace/public/pm/cozy-search.js +203 -0
  116. package/workspace/public/pm/cozy-settings.js +198 -0
  117. package/workspace/public/pm/cozy-sources.js +89 -0
  118. package/workspace/public/pm/cozy-today.css +217 -0
  119. package/workspace/public/pm/cozy-viewer.css +3 -3
  120. package/workspace/public/pm/cozy-viewer.js +145 -0
  121. package/workspace/public/pm/cozy-vw-mtg.css +350 -0
  122. package/workspace/public/pm/cozy-vw-rp.css +152 -0
  123. package/workspace/public/pm/cozy-vw.css +485 -0
  124. package/workspace/public/pm/cozy.css +83 -1
  125. package/workspace/public/pm/home-adddoc.js +48 -0
  126. package/workspace/public/pm/home-app.js +1179 -0
  127. package/workspace/public/pm/home-around.js +413 -0
  128. package/workspace/public/pm/home-chat.js +512 -0
  129. package/workspace/public/pm/home-data.js +312 -0
  130. package/workspace/public/pm/home-dictate.js +54 -0
  131. package/workspace/public/pm/home-draft.js +68 -0
  132. package/workspace/public/pm/home-ini-model.js +190 -0
  133. package/workspace/public/pm/home-ini.css +171 -0
  134. package/workspace/public/pm/home-ini.js +456 -0
  135. package/workspace/public/pm/home-list.js +276 -0
  136. package/workspace/public/pm/home-more.js +132 -0
  137. package/workspace/public/pm/home-phone-card.js +109 -0
  138. package/workspace/public/pm/home-review.js +104 -0
  139. package/workspace/public/pm/home-task.js +67 -0
  140. package/workspace/public/pm/home-today.js +144 -0
  141. package/workspace/public/pm/home-work.js +547 -0
  142. package/workspace/public/pm/phone-moment.js +69 -0
  143. package/workspace/public/pm/pm-work-view.js +1 -1
  144. package/workspace/public/pm/premium-attach.js +4 -0
  145. package/workspace/public/pm/premium-board.js +548 -395
  146. package/workspace/public/pm/premium-chart-tab.js +109 -62
  147. package/workspace/public/pm/premium-deck.js +3 -3
  148. package/workspace/public/pm/premium-first.js +23 -21
  149. package/workspace/public/pm/premium-insights.js +1102 -581
  150. package/workspace/public/pm/premium-meeting.js +61 -549
  151. package/workspace/public/pm/premium-mtg-present.js +138 -0
  152. package/workspace/public/pm/premium-mtg-replay.js +142 -0
  153. package/workspace/public/pm/premium-notes.js +1 -1
  154. package/workspace/public/pm/premium-report-frame.css +20 -0
  155. package/workspace/public/pm/premium-report-read.js +669 -476
  156. package/workspace/public/pm/premium-report-tab.js +116 -67
  157. package/workspace/public/pm/premium-shell.js +76 -123
  158. package/workspace/public/pm/premium-viewer.js +22 -1
  159. package/workspace/public/pm/premium-vw-cal.js +277 -48
  160. package/workspace/public/pm/premium-vw-doc.css +6 -0
  161. package/workspace/public/pm/premium-vw-doc.js +40 -2
  162. package/workspace/public/pm/premium-vw-file.js +2 -2
  163. package/workspace/public/pm/premium-vw-meet.js +6 -83
  164. package/workspace/public/pm/premium-vw-mtg.js +958 -0
  165. package/workspace/public/pm/premium-vw-notes.js +116 -68
  166. package/workspace/public/pm/premium-vw-open.js +35 -0
  167. package/workspace/public/pm/premium-vw-page.js +16 -0
  168. package/workspace/public/pm/premium-vw-rec.js +11 -218
  169. package/workspace/public/pm/premium-vw-slides.css +5 -0
  170. package/workspace/public/pm/premium-vw-slides.js +44 -8
  171. package/workspace/public/pm/rp-parts.js +269 -0
  172. package/workspace/public/pm/term-view.js +22 -0
  173. package/workspace/public/premium-board.html +29 -70
  174. package/workspace/public/premium-initiative.html +8 -48
  175. package/workspace/public/premium-insights.html +26 -64
  176. package/workspace/public/premium-viewer.html +20 -0
  177. package/workspace/public/premium.html +18 -107
  178. package/workspace/r/m1.png +0 -0
  179. package/workspace/r/m2.png +0 -0
  180. package/workspace/r/m3.png +0 -0
  181. package/workspace/r/nl.png +0 -0
  182. package/workspace/server.js +18 -3
  183. package/workspace/test-files.json +1 -0
  184. package/workspace/test-lists/home-libs.json +9 -0
  185. package/workspace/test-lists/initiative-layout.json +9 -0
  186. package/workspace/test-lists/premium-report-read.json +1 -1
  187. package/workspace/test-lists/premium-uncovered-meetings.json +9 -0
  188. package/workspace/test-lists/premium-uncovered-reports.json +9 -0
  189. package/workspace/test-lists/premium-vw-agreed.json +9 -0
  190. package/workspace/test-lists/premium-vw-notes.json +1 -1
  191. package/workspace/test-lists/uf-everywhere.json +15 -0
  192. package/workspace/test-lists/uf-home.json +9 -0
  193. package/workspace/test-lists/uncovered-board.json +9 -0
  194. package/workspace/public/pm/premium-work.js +0 -729
  195. package/workspace/public/pm/premium.js +0 -1146
@@ -1,1146 +0,0 @@
1
- /* pm/premium.js — the premium Briefing page (initiative briefing-premium, slice 1). Reads GET /api/briefing-premium and draws the model
2
- * lib/briefing-premium.js builds: the hero, "What you need to do", Today, the dock and the standard dialog. The read is one GET; the only writes are the PM's own presses (slice 2, below). A row clears when the repository's record changes, so there is nothing to press to clear it.
3
- * Slice 2 (initiative briefing-premium-writes): the buttons that record the PM's own calls post to /api/briefing-premium/{decide,put-off,return}.
4
- * Slice 3: the reply box asks a read-only agent. A control with nothing honest to write stays disabled and says why. */
5
- import { pmPost, pmGet } from './http.js';
6
- import { startAgent } from './page-agent.js';
7
- import { mountMeeting } from './premium-meeting.js';
8
- import { mountCalEntry } from './premium-vw-cal.js';
9
- import { mountNotes } from './premium-vw-notes.js';
10
- import { mountFirst } from './premium-first.js';
11
- import { lineItems, behindOf, refreshTargets, whenRead } from './freshness-words.js';
12
- import { consoleReads, briefOf, needsListOf } from './premium-brief.js';
13
- import { mountDocSheet } from './premium-doc-sheet.js';
14
- import { momentOf, inText } from './c3-phone-model.js';
15
- import { drawSummary, drawMeetLine } from './cozy-home.js';
16
- import { $, $$, esc, store, THEME_KEY, RM, AI, S, theme, toast, kv, H, openDlg, popKey, closeDlg, setTab, setMode, setFull, CHECK, CHEV, ptx, turnA, turnU, H1, H2, P1, UL, logHtml, loadThread, onScroll, wireRail, pvFeed, setPageGaps, sourcesHook, allText, sourcesNow, readLine, chatAbout, pvOpenBell, ibState } from './premium-shell.js';
17
- const ICON = {
18
- meeting: '<rect x="4" y="5" width="16" height="15" rx="3"/><path d="M4 10h16M9 3v4M15 3v4"/>',
19
- merge: '<circle cx="6" cy="6" r="2"/><circle cx="6" cy="18" r="2"/><circle cx="18" cy="9" r="2"/><path d="M6 8v8M18 11c0 4-6 3-12 5"/>',
20
- run: '<path d="M13 3 5 14h6l-1 7 8-11h-6z"/>',
21
- digest: '<path d="M5 7h14M5 12h14M5 17h9"/>',
22
- };
23
- const SRC = { meeting: 'Calendar', merge: 'Merges', run: 'Agent runs', digest: 'Digests' };
24
- let M = null; // the model
25
- const on = new Set(Object.keys(SRC));
26
- const pinned = new Set();
27
-
28
- wireRail('brief');
29
- const week = mountMeeting({ $, $$, esc, openDlg, toast, pmGet, pmPost, turnA, ptx, kv, H, setMode, setFull, ws: () => new URLSearchParams(location.search).get('ws'), redraw: () => { if (M) drawTl(); } });
30
- mountCalEntry($('#todayCard'), { $, esc, openDlg, setMode, turnA, ptx, pmGet, ws: () => new URLSearchParams(location.search).get('ws'), openRow: week.openRow }); // the full calendar: Day, Week and Month in the viewer
31
- mountNotes({ $, esc, openDlg, toast, pmGet, pmPost, task: week.task });
32
-
33
- /* ── a day's baseline, kept on this device, so "N of M done" counts rows that cleared since the page first read today ────── */
34
- const dayKey = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0'); };
35
- function baseline(keys) {
36
- const k = 'pmos.premium.base.' + dayKey();
37
- let seen = [];
38
- try { seen = JSON.parse(store.get(k) || '[]'); } catch { seen = []; }
39
- const all = [...new Set([...seen, ...keys])];
40
- store.set(k, JSON.stringify(all));
41
- return all;
42
- }
43
-
44
- /* ── hero ───────────────────────────────────────────────────────────────────────────────────────────────── */
45
- /* The headline is the console's "The brief", from the same reads and the same composer (premium-brief.js). Until it comes back, or when its reads fail, the
46
- * records-only sentences above stay. Each draw asks again; a late answer to an older ask is dropped. */
47
- let briefAsk = 0, shownBrief = null; // once the console brief is shown, a re-read keeps it on screen until the next answer: the hero does not flip back
48
- /* "What you need to do" is the console's Needs you, from the same reads (premium-brief.js needsListOf). null until they come back, and while the
49
- * needs reads fail: the records-only rows of the model stay. */
50
- let CL = null;
51
- function drawConsoleBrief() {
52
- const ask = ++briefAsk;
53
- consoleReads().then((reads) => {
54
- if (ask !== briefAsk) return;
55
- const list = needsListOf(reads, new URLSearchParams(location.search).get('ws'));
56
- if (list) { CL = list; drawRows(); drawDock(); pvFeed({ ok: true, model: { list: LIST() } }); }
57
- const r = briefOf(reads);
58
- if (!r) return;
59
- shownBrief = r.parts.map((p) => (p.go ? `<span class="k">${esc(p.t)}</span>` : esc(p.t))).join('');
60
- if ($('#brief').innerHTML !== shownBrief) { $('#brief').innerHTML = shownBrief; onScroll(); }
61
- $('#brief').title = 'The same paragraph as The brief on the console Briefing. Read from: ' + r.sources.join(', ') + '.';
62
- }, () => {});
63
- }
64
- function drawHero() {
65
- $('#date').textContent = M.date;
66
- if (shownBrief == null) $('#brief').innerHTML = M.hero.map((s) => s.parts.map((p) => (p.s ? `<span class="k">${esc(p.t)}</span>` : esc(p.t))).join('')).join(' ');
67
- drawConsoleBrief();
68
- $('#snap').textContent = M.header.text;
69
- setPageGaps(M.header.sources ? M.header.sources.filter((x) => x.state === 'not-read').length : (M.header.missing || []).length);
70
- $('#snap').title = M.header.missing.length ? 'A source that cannot be read adds nothing. It is named here, and the page does not guess.' : 'Every figure on this page comes from a record in the repository.';
71
- }
72
-
73
- /* ── rows ───────────────────────────────────────────────────────────────────────────────────────────────── */
74
- const STAMP = (n) => String(n).padStart(2, '0');
75
- /* premium-simple-ui #5: a row is two lines, the title and then "subject · next step". A "nothing on record" sentence is left off the row; the
76
- * "If you skip" line and the whole next step stay in the row's dialog (skipFact). */
77
- const NEXT_OF = (r) => { const t = String(r.prepared || '').replace(/^Next step: /, ''); return /^No .* is on record\.$/.test(t) ? '' : t; };
78
- const line2 = (r) => [r.subject, NEXT_OF(r)].filter(Boolean).join(' · ');
79
- /** The row's own "If you skip" (or "Why now", …) line, as a dialog fact, when the dialog does not already hold it. */
80
- function skipFact(r) {
81
- const d = r.dialog;
82
- if (!r.skip || !d || !Array.isArray(d.facts) || d.items) return r;
83
- const m = /^([A-Z][a-z]+(?: [a-z]+){0,3}): (.+)$/.exec(r.skip), label = m ? m[1] : 'Note', text = m ? m[2] : r.skip;
84
- if (d.facts.some(([a, b]) => a === label || b === text)) return r;
85
- return { ...r, dialog: { ...d, facts: d.facts.concat([[label, text]]) } };
86
- }
87
- const CL_ORDER = 'In the order of Needs you on the console: what cannot wait first, then by impact, urgency and effort.';
88
- /** The list the page draws: the console's Needs you once it is read, else the model's records-only rows. */
89
- function LIST() {
90
- if (!CL) return M.list;
91
- const own = CL.filter((r) => !r.prop); // premium-agent-inbox: the Driver's drafts rows are in the bell; the count line below the rows names them
92
- return { rows: own.map((r, i) => ({ ...r, n: i + 1 })), count: own.length, more: 0, putOff: [], order: CL_ORDER, pendingNote: '' };
93
- }
94
- /** The count line of the agent's results under the rows (premium-agent-inbox): the total, the new ones and the oldest, and a press opens the bell. */
95
- function inboxLine() {
96
- const j = ibState(); if (!j || !j.count) return '';
97
- const d = j.oldest == null ? null : Math.floor((Date.now() - j.oldest) / 86400000);
98
- const sub = [j.newCount ? j.newCount + ' new since you last looked' : 'none new since you last looked', d == null ? '' : d < 1 ? 'the oldest is from today' : 'the oldest is ' + d + (d === 1 ? ' day old' : ' days old')].filter(Boolean).join(' · ');
99
- return `<div class="ib-sum"><span class="ib-n">${j.count}</span><span class="ib-b"><b>${j.count === 1 ? 'agent result waits' : 'agent results wait'} on you.</b><small>${esc(sub)}</small></span><button type="button" class="cta" id="ibOpen" aria-haspopup="dialog">Open Needs you</button></div>`;
100
- }
101
- document.addEventListener('pmos:inbox', () => { if (M) drawRows(); });
102
- document.addEventListener('click', (e) => { if (e.target.closest('#ibOpen')) pvOpenBell(); });
103
- function drawRows() {
104
- const LS = LIST(), pend = M.pending && !CL;
105
- const rows = LS.rows, L = $('#rank');
106
- const keys = rows.map((r) => r.key), off = (LS.putOff || []).map((x) => x.key); // a row put off is not done: it leaves both counts and is named below the list
107
- const base = (pend ? keys : baseline(keys)).filter((k) => !off.includes(k)), done = base.filter((k) => !keys.includes(k)).length, total = base.length;
108
- const order = rows.slice().sort((a, b) => (pinned.has(b.key) - pinned.has(a.key)) || (a.n - b.n));
109
- L.innerHTML = order.map((r, i) => `<div class="rr${i < 3 ? ' lead' : ''}${i === 0 ? ' first' : ''}" data-key="${esc(r.key)}"${linkOf(r) ? ` data-link="${esc(linkOf(r))}"` : ''}><button class="rhd" aria-haspopup="dialog"><span class="rn">${STAMP(i + 1)}</span><span><span class="rt">${esc(r.title)}${i === 0 ? '<em class="tgf">Do this first</em>' : ''}</span><span class="rs" title="${esc(line2(r))}">${r.product ? `<b class="pn">${esc(r.product)}</b>` : ''}${esc(line2(r))}</span></span><svg class="rchev" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 6 6 6-6 6"/></svg></button><button class="rpin" data-pin="${esc(r.key)}" aria-pressed="${pinned.has(r.key)}" aria-label="Pin ${esc(r.title)} to the top" title="Pin to the top"><svg class="i" viewBox="0 0 24 24"><path d="M9 4h6l-1 6 3 3H7l3-3zM12 13v7"/></svg></button></div>`).join('')
110
- + (LS.more ? `<p class="note">${LS.more} more ${LS.more === 1 ? 'row is' : 'rows are'} not shown here.</p>` : '');
111
- if (!$('#ibLine')) $('#calm').insertAdjacentHTML('afterend', '<div id="ibLine"></div>'); // premium-agent-inbox: the agent's results, one count line under the PM's own rows
112
- $('#ibLine').innerHTML = inboxLine();
113
- $('#calm b').textContent = ibState() && ibState().count ? 'Nothing of your own waits right now.' : 'Nothing needs you right now.';
114
- const n = LS.count;
115
- $('#movesCap').innerHTML = pend ? `${n} ${n === 1 ? 'row' : 'rows'} so far · still reading` : n ? `<b>${done} of ${total}</b> done · ${n} ${n === 1 ? 'row' : 'rows'} left` : 'All clear';
116
- $('#movesCap').title = 'Counts rows that cleared since this page first read today. A row clears when its record changes.';
117
- const p = $('#mprog'); p.hidden = !total || pend; p.setAttribute('aria-valuemax', total); p.setAttribute('aria-valuenow', done); $('b', p).style.width = (total ? done / total * 100 : 0) + '%';
118
- $('#calm').hidden = n > 0 || pend; $('#calmNext').textContent = '';
119
- $('#order').textContent = pend ? LS.pendingNote : n ? LS.order : '';
120
- $('#order').hidden = !n && !pend;
121
- const po = LS.putOff || [];
122
- $('#putoff').textContent = po.length ? 'Put off by you: ' + po.map((x) => x.text).join('; ') + '. Not counted as done.' : '';
123
- $('#putoff').hidden = !po.length;
124
- }
125
- $('#rank').addEventListener('click', (e) => {
126
- const pin = e.target.closest('.rpin');
127
- if (pin) { const k = pin.dataset.pin; pinned.has(k) ? pinned.delete(k) : pinned.add(k); drawRows(); toast(pinned.has(k) ? 'Pinned to the top for this session.' : 'Unpinned.'); return; }
128
- const h = e.target.closest('.rhd');
129
- if (!h) return;
130
- const r = LIST().rows.find((x) => x.key === h.closest('.rr').dataset.key);
131
- if (r && r.prop) { openPropsDlg(r.prop); return; }
132
- if (r && r.docs) { openCoreDraft(r.docs); return; } // portfolio documents: the document sheet, with Read and Issue it // the agent's drafts: the Agent proposals dialog, that target's proposals only
133
- if (r && r.go && homeItem(r.go)) return; // Home holds My work: an item of your list opens its own dialog here
134
- if (r && r.go) { location.assign(r.go); return; } // a console row opens its item on its own page: My work, the initiative or the board
135
- openRow(r);
136
- });
137
-
138
- /** A row whose page is Home itself with ?item=<id> opens that item on this page (premium-work.js listens). */
139
- function homeItem(go) {
140
- const m = /^\/premium\.html\?(.*)$/.exec(go || ''), id = m && new URLSearchParams(m[1]).get('item');
141
- if (!id || !document.getElementById('queue')) return false;
142
- document.dispatchEvent(new CustomEvent('pmos:item', { detail: { id } }));
143
- return true;
144
- }
145
- /* ── today ──────────────────────────────────────────────────────────────────────────────────────────────── */
146
- const linkOf = (r) => ((r.from || []).find((x) => /^meeting:/.test(x)) || '').replace(/^meeting:/, '');
147
- function evHtml(e, i) {
148
- const lnk = e.kind === 'meeting' && (LIST().rows || []).some((r) => linkOf(r) === e.title) ? e.title : '';
149
- return `<button class="ev src-${e.kind}"${lnk ? ` data-link="${esc(lnk)}"` : ''} data-i="${i}" style="animation:rise .6s var(--ease) both"><time>${esc(e.t)}</time><span class="gl-t"><svg class="i" viewBox="0 0 24 24">${ICON[e.kind]}</svg></span><span><b>${esc(e.title)}</b><span class="d">${esc(e.sub)}${e.product ? ' · ' + esc(e.product) : ''}</span></span></button>`;
150
- }
151
- const ALL = () => M.today.ahead.concat(M.today.earlier);
152
- function drawChips() {
153
- $('#srcChips').innerHTML = Object.entries(SRC).filter(([k]) => k !== 'digest' || M.today.counts.digest).map(([k, n]) => `<button class="fchip" data-k="${k}" aria-pressed="${on.has(k)}">${n}<em>${M.today.counts[k] || 0}</em></button>`).join('');
154
- }
155
- /** The prep ring: of the meetings still ahead today, how many have nothing left to do before them. Counts from /api/brief-page rows (`before` is the open items linked to a meeting). */
156
- let PREP = null;
157
- function drawPrep() {
158
- const c = $('#prep'); if (!c) return;
159
- const p = PREP, t = p && p.ok ? p.today || [] : [], left = t.filter((m) => m.state !== 'past'), ok = left.filter((m) => !(m.before || []).length).length;
160
- if (!left.length || document.querySelector('#todayCard.wkm')) { c.hidden = true; return; }
161
- const cur = t.find((m) => m.state === 'now'), nxt = cur || t.find((m) => m.state === 'next'), R = 17, C = 2 * Math.PI * R;
162
- c.innerHTML = `<svg width="44" height="44" viewBox="0 0 44 44" role="img" aria-label="${ok} of ${left.length} prepped"><circle class="rb" cx="22" cy="22" r="${R}" fill="none" stroke-width="6"/><circle class="rg" cx="22" cy="22" r="${R}" fill="none" stroke-width="6" stroke-linecap="round" stroke-dasharray="${(C * ok / left.length).toFixed(2)} ${C.toFixed(2)}" transform="rotate(-90 22 22)"/><text class="rt" x="22" y="26">${ok}/${left.length}</text></svg><div>${nxt ? `<b>${esc(nxt.title)}${cur ? ' is on now' : ' at ' + pHm(nxt.start) + ' is next'}</b>` : ''}<span>${pl(left.length, 'meeting', 'meetings')} left today. ${ok} of ${left.length} prepped.</span></div>`;
163
- c.hidden = false;
164
- }
165
- async function readPrep() { PREP = await briefPage(); drawPrep(); drawMeetLine(PREP, { open: (m) => week.openToday({ at: Date.parse(m.start), title: m.title }) }); }
166
- function drawTl() {
167
- if (week.draw()) { drawPrep(); return; }
168
- drawPrep();
169
- const T = M.today, all = ALL(), ahead = T.ahead.filter((e) => on.has(e.kind)), early = T.earlier.filter((e) => on.has(e.kind));
170
- $('#todayCap').textContent = `${early.length} earlier · ${ahead.length} ahead`;
171
- $('#tl').innerHTML = `<div class="grp">Ahead</div>${ahead.length ? ahead.map((e) => evHtml(e, all.indexOf(e))).join('') : '<div class="empty">Nothing ahead in these sources.</div>'}<div class="nowl">${esc(T.now.t)} · ${esc(T.now.label)}</div><div class="grp" style="padding-top:6px">Earlier today</div><div class="early">${early.length ? early.map((e) => evHtml(e, all.indexOf(e))).join('') : `<div class="empty">${esc(T.note || 'Nothing yet in these sources.')}</div>`}</div>`;
172
- $$('#tl .ev').forEach((x, i) => { x.tabIndex = i ? -1 : 0; });
173
- week.mark((i) => ALL()[i]);
174
- const next = ahead[0];
175
- $('#dNext').innerHTML = next ? `<i></i>Next <b>${esc(next.t)}</b> ${esc(next.title)}` : (M.header.missing.includes('calendar') ? 'Calendar not read' : 'Nothing more today');
176
- }
177
- $('#srcChips').addEventListener('click', (e) => { const b = e.target.closest('button'); if (!b) return; const k = b.dataset.k; on.has(k) ? on.delete(k) : on.add(k); b.setAttribute('aria-pressed', on.has(k)); drawTl(); });
178
- $('#tl').addEventListener('keydown', (e) => {
179
- if (!/^(ArrowUp|ArrowDown|Home|End)$/.test(e.key)) return;
180
- const L = $$('#tl .ev'), i = L.indexOf(document.activeElement); if (i < 0) return;
181
- e.preventDefault();
182
- const j = e.key === 'ArrowDown' ? Math.min(L.length - 1, i + 1) : e.key === 'ArrowUp' ? Math.max(0, i - 1) : e.key === 'Home' ? 0 : L.length - 1;
183
- L.forEach((x) => { x.tabIndex = -1; }); L[j].tabIndex = 0; L[j].focus();
184
- });
185
- $('#tl').addEventListener('click', async (e) => {
186
- const b = e.target.closest('.ev'); if (!b || b.dataset.w) return;
187
- const ev = ALL()[+b.dataset.i];
188
- if (ev && ev.kind === 'meeting' && await week.openToday(ev)) return; // the calendar answer knows this meeting: the full meeting dialog
189
- openEvent(ev);
190
- });
191
- document.addEventListener('click', (e) => {
192
- const fb = e.target.closest('.fbtn');
193
- if (fb) { const o = $('#' + fb.dataset.opts), v = !o.classList.contains('on'); o.classList.toggle('on', v); o.inert = !v; fb.setAttribute('aria-expanded', v); }
194
- /* the Calendar card's ⋯ holds Notes, the source filter and the full calendar; a press inside runs and shuts it (premium-calmer-first-screen) */
195
- const cm = $('#calMenu'), more = e.target.closest('#calMore');
196
- if (cm) calMenu(more ? cm.hidden : false);
197
- });
198
- function calMenu(open) { const cm = $('#calMenu'), b = $('#calMore'); if (!cm || cm.hidden === !open) return; cm.hidden = !open; b.setAttribute('aria-expanded', String(open)); if (open) { const f = cm.querySelector('button'); if (f) f.focus(); } }
199
- document.addEventListener('keydown', (e) => { const cm = $('#calMenu'); if (e.key === 'Escape' && cm && !cm.hidden) { calMenu(false); $('#calMore').focus(); } });
200
-
201
- /* ── dock ───────────────────────────────────────────────────────────────────────────────────────────────── */
202
- function drawDock() {
203
- const n = CL ? LIST().count : M.dock.needs;
204
- drawSummary(n); // Home's summary line: Good afternoon. N things need you.
205
- $('#dN').textContent = n == null ? '·' : n; $('#dLab').textContent = n == null ? 'still reading' : n === 0 ? 'need you' : CL ? (n === 1 ? 'needs you' : 'need you') : M.dock.label;
206
- }
207
-
208
- const SEL = {}; // the option chosen on each row, for this session
209
- const START = {}; // 'ask' while the PM is confirming a start, by row key
210
- const RET = {}; // the reason chosen for returning a run, by row key
211
- const WHY = {}; // what the PM typed in the reason box, by row key (kept across a redraw and across a refused press)
212
- const RET_REASONS = ['wrong facts', 'wrong scope', 'not now', 'too long'];
213
- const holdNote = (t) => `<p class="nodef" id="holdWhy">${esc(t)}</p>`;
214
- const whyBox = (r, label) => `<label class="whyl" for="why">${esc(label)}</label><textarea id="why" class="why" rows="3" maxlength="1200" aria-describedby="cardErr">${esc(WHY[r.key] || '')}</textarea>`;
215
- function ctaState(r) {
216
- const d = r.dialog, w = d.write, b = $('#recBtn');
217
- if (!b || !w) return;
218
- const why = ($('#why') || {}).value || '';
219
- if (w.kind === 'decision') b.disabled = !(SEL[r.key] || d.sel) || why.trim().length < 3;
220
- else if (w.kind === 'return') b.disabled = !RET[r.key];
221
- }
222
- function cardHtml(r) {
223
- const d = r.dialog, sel = SEL[r.key] || d.sel, w = d.write;
224
- if (d.items) return `<div class="acard" id="card"><p class="ct">${esc(d.head)}</p>${d.items.map((x) => `<div class="tri"><span><b>${esc(x.t)}</b><small>${esc(x.m)}</small><em>${esc(x.s)}${x.lead ? ' · ' + esc(x.lead) : ''}</em></span></div>`).join('')}</div>`;
225
- const o = d.opts.find((x) => x.k === sel);
226
- const err = '<p class="nodef err" id="cardErr" role="alert" hidden></p>';
227
- const facts = d.facts.length ? `<div class="kv">${d.facts.map(([a, b]) => `<span>${esc(a)}</span><span>${esc(b)}</span>`).join('')}</div>` : '';
228
- const opts = d.opts.length ? `<div class="opts2">${d.opts.map((x) => `<button class="op" data-op="${esc(x.k)}" aria-pressed="${x.k === sel}"><i></i><span><b>${esc(x.t)}</b><small>${esc(x.d)}</small></span></button>`).join('')}</div>` : '';
229
- const head = `<div class="acard" id="card"><p class="ct">${esc(d.head)}</p>${facts}`;
230
- if (w && w.kind === 'decision') {
231
- // the simple decision card: the evidence as label-value rows, the option cards, the reason as one labelled field, and one bottom bar
232
- // with a quiet "Later" and the only primary, named after the chosen option
233
- const label = o ? 'Record: ' + o.t : 'Your call: choose one';
234
- const ev = d.facts.length ? `<p class="ct">${esc(d.head)}</p><dl class="dkv">${d.facts.map(([a, b]) => `<div><dt>${esc(a)}</dt><dd>${esc(b)}</dd></div>`).join('')}</dl>` : '';
235
- const later = [['later', 'Later today'], ['tomorrow', 'Tomorrow'], ['nextweek', 'Next week']].map(([k, t]) => `<button type="button" role="menuitem" data-until="${k}">${t}</button>`).join('');
236
- return `<div class="acard dsim" id="card">${ev}${d.opts.length ? '<p class="ct">Your call</p>' : ''}${opts}<div class="dwhy">${whyBox(r, 'Why · kept in the journal')}</div>${d.nodef ? `<p class="dinfo"><i aria-hidden="true">i</i><span>${esc(d.nodef)}</span></p>` : ''}${err}<div class="dbar" id="cardAct"><div class="dlater"><button type="button" class="dlb" id="laterBtn" aria-haspopup="menu" aria-expanded="false" aria-controls="laterMenu">Later <svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 9l6 6 6-6"/></svg></button><div class="seg2 dlm" id="laterMenu" role="menu" aria-label="Put it off until" hidden>${later}</div></div><button class="cta" id="recBtn" data-rec="decision" disabled>${CHECK}<span>${esc(label)}</span></button></div></div>`;
237
- }
238
- if (w && w.kind === 'return') {
239
- return `${head}<p class="ct">Return this run: why</p><div class="seg2" id="retWhy">${RET_REASONS.map((x) => `<button data-ret="${esc(x)}" aria-pressed="${RET[r.key] === x}">${esc(x)}</button>`).join('')}</div>${err}<div class="cact"><button class="cta" id="recBtn" data-rec="return" disabled>${CHECK}<span>${esc(d.action)}</span></button></div></div>`;
240
- }
241
- if (w && w.kind === 'start') {
242
- const ask = START[r.key] === 'ask';
243
- return `${head}${opts}${err}${ask ? `<p class="nodef">Start this agent session? It drafts “${esc(w.what)}” for you to read and sends nothing outside PMOS.</p><div class="cact" id="cardAct"><button class="cta" id="startGo" data-start="go">${CHECK}<span>Start the session</span></button><button class="cta alt" data-start="no">Not now</button></div>` : `<div class="cact" id="cardAct"><button class="cta" id="startBtn" data-start="ask">${CHECK}<span>${esc(d.prim[d.sel])}</span></button></div>${d.hold ? holdNote(d.hold) : ''}`}</div>`;
244
- }
245
- if (d.opts.length) return `${head}${opts}${d.nodef ? `<p class="nodef">${esc(d.nodef)}</p>` : ''}<div class="cact" id="cardAct"><button class="cta" disabled title="${esc(d.hold || 'Nothing here can be recorded yet.')}">${o ? esc(d.prim[o.k]) : 'Your call: choose one'}</button></div>${d.hold ? holdNote(d.hold) : ''}</div>`;
246
- if (d.proposals) return `${head}<div class="cact"><button class="cta" id="openProps" type="button">Review the drafts</button></div><p class="nodef">Keep, send back and Drop are under Around you, Agent proposals. Nothing here changes a record.</p></div>`;
247
- if (d.link) return `${head}<div class="cact"><a class="cta" id="srcLink" href="${esc(d.link)}" target="_blank" rel="noopener noreferrer">${esc(d.linkLabel || 'Open the source')}</a></div></div>`;
248
- return `${head}${d.nodef ? `<p class="nodef">${esc(d.nodef)}</p>` : ''}${d.action ? `<div class="cact"><button class="cta" disabled title="${esc(d.hold || 'Nothing here can be recorded.')}">${CHECK}${esc(d.action)}</button></div>${d.hold ? holdNote(d.hold) : ''}` : ''}</div>`;
249
- }
250
- function paneHtml(r) {
251
- // as the mockup draws it: the record's path, its heading and one lead line, then its grid or sections
252
- const p = r.dialog.pane, sel = SEL[r.key] || r.dialog.sel, o = (r.dialog.opts || []).find((x) => x.k === sel);
253
- // the dialog head already shows the title and its line: the pane does not draw them a second time
254
- const same = (a, b) => String(a || '').trim() === String(b || '').trim();
255
- let h = `<p class="dpath">${esc(p.file || '')}</p>${p.h && !same(p.h, r.dialog.title || r.title) ? H1(p.h) : ''}${p.intro && !same(p.intro, r.dialog.sub || r.subject) ? P1(p.intro) : ''}`;
256
- if (p.list) h = `<p class="dpath">planning/runs/evals.jsonl</p><ol class="stp">${r.dialog.items.map((x, k) => `<li><i>${k + 1}</i><span><b>${esc(x.t)}</b><small>${esc(x.m + ' · ' + x.s)}${x.lead ? '. ' + esc(x.lead) : ''}</small></span></li>`).join('')}</ol>`;
257
- else if (p.optsDraft) h += H2('Evidence') + UL(p.evidence.filter((x) => x && x[1]).map(([k, v]) => k + ': ' + v)) + H2('Decision') + P1(o ? o.t + '. ' + o.draft : 'Choose an option to draft the entry.') + `<p class="xn">A draft. Nothing is written to the journal until you press Record.</p>`;
258
- else h += (p.rows && p.rows.length ? kv(p.rows) : '') + (p.paras && p.paras.length ? (p.parasTitle ? H2(p.parasTitle) : '') + p.paras.map(P1).join('') : '') + `<p class="xn">The record as it stands. Nothing is drafted here.</p>`;
259
- return `<article class="paper doc">${h}</article>`;
260
- }
261
- let openR = null;
262
- /* A record whose dialog could not be built still opens something true: what the row itself says. */
263
- function plainDialog(r) {
264
- return { eye: 'Detail', logTitle: 'Read from the repository', log: ['Read the record'], say: [r.prepared, r.skip].filter(Boolean).join(' '), head: 'What is known', facts: [['Subject', r.subject], ['Next', r.prepared], ['If you skip', r.skip && r.skip.replace(/^If you skip: /, '')]].filter((x) => x[1]), opts: [], sel: null, nodef: '', pane: { label: 'Detail', file: '', h: r.title, intro: r.subject || '', rows: [], paras: [] } };
265
- }
266
- /* A decision from the console's Needs you: what its record says, and its source. Choosing an option on an engine card is not recorded from here. */
267
- function consoleDialog(r) {
268
- const facts = [['Kind', r.subject]].concat((r.facts || []).map((f) => ['Fact', f]), r.options && r.options.length ? [['Options', r.options.join(' · ')]] : []);
269
- return { eye: 'Needs you', logTitle: 'Read from the console Briefing', log: ['Read GET /api/briefing', 'Kept the row Needs you shows'], say: r.prepared || 'This is on the console\'s Needs you.', head: 'What is known', facts, opts: [], sel: null,
270
- nodef: r.options && r.options.length ? 'Choosing an option is recorded on the console Briefing, not here.' : '', link: r.url || null, linkLabel: r.urlLabel || null, popAsk: true,
271
- pane: { label: 'Detail', file: 'Needs you', h: r.title, intro: r.subject || '', rows: [], paras: (r.facts || []).slice(0, 6) } };
272
- }
273
- function openRow(r) {
274
- if (!r) return;
275
- if (!r.dialog) r = { ...r, dialog: r.src ? consoleDialog(r) : plainDialog(r) };
276
- r = skipFact(r);
277
- openR = r; const d = r.dialog;
278
- openDlg({ eye: d.eye + ' · real data', title: d.title || r.title, sub: d.sub || r.subject, say: d.say, stream: turnA(logHtml(d)) + turnA(ptx(d.say)) + cardHtml(r), noteKey: d.popAsk ? popKey('need', r.key) : r.chatKey || r.key, facts: d.facts, pane: paneHtml(r), label: d.pane.label }); // a goal row (premium-chat-session U7) opens its own conversation
279
- ctaState(r);
280
- pinBtn(r.key);
281
- if (!r.dialog.popAsk) loadThread(r.chatKey || r.key); // a console row's popup key loads its own thread (premium-shell openDlg)
282
- setTimeout(() => { const b = $('#dBody'); b.scrollTop = b.scrollHeight; }, 120);
283
- }
284
- /* A list row's pin also sits in its dialog: a phone has no hover, so the row shows the pin only once pinned (premium-calmer-first-screen) */
285
- function pinBtn(k) {
286
- const ct = $('#card .ct'); if (!ct || ![...$$('#rank .rpin')].some((b) => b.dataset.pin === k)) return;
287
- const on = pinned.has(k), b = document.createElement('button');
288
- b.type = 'button'; b.className = 'dpin'; b.dataset.dpin = k; b.setAttribute('aria-pressed', String(on));
289
- b.innerHTML = `<svg class="i" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4h6l-1 6 3 3H7l3-3zM12 13v7"/></svg>${on ? 'Unpin' : 'Pin to the top'}`;
290
- b.onclick = () => { pinned.has(k) ? pinned.delete(k) : pinned.add(k); drawRows(); toast(pinned.has(k) ? 'Pinned to the top for this session.' : 'Unpinned.'); b.remove(); pinBtn(k); };
291
- ct.append(b);
292
- }
293
- function showErr(msg) { const e = $('#cardErr'); if (!e) { toast(msg); return; } e.textContent = msg; e.hidden = false; }
294
- /* A press that records. The page waits for the server's answer: a refusal shows its reason and keeps what the PM typed. */
295
- async function write(path, body, done) {
296
- const ws = new URLSearchParams(location.search).get('ws');
297
- const btns = $$('#card button, #askF button'); btns.forEach((b) => { b.disabled = true; });
298
- const res = await pmPost('/api/briefing-premium/' + path + (ws ? '?ws=' + encodeURIComponent(ws) : ''), body);
299
- if (!res || res.ok !== true) {
300
- btns.forEach((b) => { b.disabled = false; }); if (openR) ctaState(openR);
301
- const m = (res && res.error) || 'The record was not written.';
302
- showErr(m); return false;
303
- }
304
- $$('#askF button').forEach((b) => { b.disabled = false; });
305
- done(res); return true;
306
- }
307
- $('#dBody').addEventListener('click', (e) => {
308
- const lt = e.target.closest('#logT');
309
- if (lt && e.pmLog) return; // Home also loads premium-work.js, which takes the same press: the log toggles once per press
310
- if (lt) { e.pmLog = true; const c = $('#alog').classList.toggle('col'); lt.setAttribute('aria-expanded', !c); return; }
311
- if (!openR) return;
312
- if (e.target.closest('#openProps')) { const r = openR; closeDlg(); openPropsDlg(rowTarget(r)); return; } // a drafts row: that target's proposals only
313
- const op = e.target.closest('[data-op]');
314
- if (op) { WHY[openR.key] = ($('#why') || {}).value || ''; SEL[openR.key] = op.dataset.op; $('#card').outerHTML = cardHtml(openR); $('#oMain').innerHTML = paneHtml(openR); ctaState(openR); return; }
315
- const st = e.target.closest('[data-start]');
316
- if (st) {
317
- const key = openR.key, w = openR.dialog.write;
318
- if (st.dataset.start === 'ask') { START[key] = 'ask'; $('#card').outerHTML = cardHtml(openR); return; }
319
- if (st.dataset.start === 'no') { delete START[key]; $('#card').outerHTML = cardHtml(openR); return; }
320
- $$('#card button').forEach((b) => { b.disabled = true; });
321
- startAgent({ ws: w.ws || new URLSearchParams(location.search).get('ws') || undefined, task: 'draft', initiative: w.initiative, what: w.what }).then((res) => {
322
- if (!res.ok) { $$('#card button').forEach((b) => { b.disabled = false; }); showErr('Not started: ' + res.error); return; }
323
- delete START[key]; toast('The agent started. It is listed in Sessions, and its draft waits for you to read.'); closeDlg();
324
- });
325
- return;
326
- }
327
- const rt = e.target.closest('[data-ret]');
328
- if (rt) { WHY[openR.key] = ($('#why') || {}).value || ''; RET[openR.key] = rt.dataset.ret; $('#card').outerHTML = cardHtml(openR); ctaState(openR); return; }
329
- const lb = e.target.closest('#laterBtn'), lm = $('#laterMenu');
330
- if (lb) { const v = lm.hidden; lm.hidden = !v; lb.setAttribute('aria-expanded', v); return; }
331
- if (lm && !lm.hidden && !e.target.closest('#laterMenu')) { lm.hidden = true; $('#laterBtn').setAttribute('aria-expanded', 'false'); }
332
- const un = e.target.closest('[data-until]');
333
- if (un) { write('put-off', { key: openR.key, until: un.dataset.until }, async () => { toast('Put off. It comes back by itself, and it is not counted as done.'); closeDlg(); await load(); }); return; }
334
- const rec = e.target.closest('#recBtn');
335
- if (rec && !rec.disabled) {
336
- const w = openR.dialog.write, why = ($('#why') || {}).value || '', key = openR.key;
337
- WHY[key] = why;
338
- if (w.kind === 'decision') write('decide', { key, choice: SEL[key] || openR.dialog.sel, why }, async (res) => { delete WHY[key]; toast('Recorded in pm-decisions.md.'); closeDlg(); await load(); });
339
- else write('return', { run: w.run, reason: RET[key], ...(w.ws ? { ws: w.ws } : {}) }, async () => { toast('Returned to the agent. It counts as a correction.'); closeDlg(); await load(); });
340
- }
341
- });
342
- $('#dBody').addEventListener('input', (e) => { if (e.target.id === 'why' && openR) { WHY[openR.key] = e.target.value; ctaState(openR); } });
343
- function openEvent(e) {
344
- if (!e) return;
345
- openRow({ key: 'ev:' + e.kind + ':' + e.at, title: e.title, subject: e.sub, prepared: e.sub, dialog: e.dialog });
346
- }
347
-
348
-
349
- /* ── a decision and the meeting that needs it are one thing, shown twice ─────────────────────────────────── */
350
- {
351
- const lk = (el, v) => { const id = el.dataset.link; if (!id) return; $$(`[data-link="${CSS.escape(id)}"]`).forEach((x) => x.classList.toggle('hl-k', v)); };
352
- ['pointerenter', 'focusin'].forEach((ev) => document.addEventListener(ev, (e) => { const t = e.target.closest && e.target.closest('[data-link]'); if (t) lk(t, true); }, true));
353
- ['pointerleave', 'focusout'].forEach((ev) => document.addEventListener(ev, (e) => { const t = e.target.closest && e.target.closest('[data-link]'); if (t) lk(t, false); }, true));
354
- }
355
-
356
-
357
- /* ── the products the Briefing reads (initiative briefing-premium-products) ──────────────────────────────────────────────────────────── */
358
- const wsParam = () => new URLSearchParams(location.search).get('ws');
359
- function drawPick() {
360
- const w = $('#pkw'), P = M.products, one = wsParam();
361
- if (!w) return;
362
- if (one) { w.hidden = false; $('#pick').hidden = true; $('#pickMenu').hidden = true; let a = $('#pickAll'); if (!a) { a = document.createElement('a'); a.id = 'pickAll'; a.className = 'fchip'; a.href = '/premium.html'; a.textContent = 'All picked products'; w.appendChild(a); } return; }
363
- if ($('#pickAll')) $('#pickAll').remove();
364
- $('#pick').hidden = false;
365
- if (!P) { w.hidden = true; return; }
366
- w.hidden = false;
367
- const n = P.available.filter((x) => x.on).length;
368
- $('#pickN').textContent = n + ' of ' + P.available.length;
369
- $('#pickMenu').innerHTML = P.available.length
370
- ? P.available.map((x) => `<button role="menuitemcheckbox" aria-checked="${x.on}" data-ws="${esc(x.ws)}"><i class="bx"></i><span>${esc(x.name)}</span>${x.home ? '<em>home</em>' : ''}</button>`).join('') + '<button role="menuitem" data-reset="1" class="pkreset"><span>Back to the default</span><em>all but home</em></button>'
371
- : '<p class="note pkempty">No product workspace is registered.</p>';
372
- }
373
- function closePick() { $('#pickMenu').hidden = true; $('#pick').setAttribute('aria-expanded', 'false'); }
374
- $('#pick').addEventListener('click', (e) => {
375
- e.stopPropagation();
376
- const m = $('#pickMenu'), open = m.hidden;
377
- m.hidden = !open; $('#pick').setAttribute('aria-expanded', open);
378
- if (open) { const f = $('button', m); if (f) f.focus(); }
379
- });
380
- document.addEventListener('click', (e) => { if (!e.target.closest('#pkw')) closePick(); });
381
- $('#pkw').addEventListener('keydown', (e) => {
382
- if (e.key === 'Escape') { closePick(); $('#pick').focus(); return; }
383
- if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
384
- const L = $$('#pickMenu button'), i = L.indexOf(document.activeElement); if (i < 0) return;
385
- e.preventDefault(); L[(i + (e.key === 'ArrowDown' ? 1 : L.length - 1)) % L.length].focus();
386
- });
387
- $('#pickMenu').addEventListener('click', async (e) => {
388
- const b = e.target.closest('button'); if (!b || !M || !M.products) return;
389
- const on = M.products.available.filter((x) => x.on).map((x) => x.ws);
390
- let body;
391
- if (b.dataset.reset) body = { key: 'ws.briefing.include', reset: true };
392
- else { const ws = b.dataset.ws, next = on.includes(ws) ? on.filter((x) => x !== ws) : on.concat(ws); body = { key: 'ws.briefing.include', value: next }; }
393
- const res = await pmPost('/api/settings', body);
394
- if (!res || res.ok !== true) { toast((res && res.error) || 'The choice was not saved.'); return; }
395
- toast(b.dataset.reset ? 'Back to the default: every product except the home one.' : 'Saved. The Briefing now reads the products you ticked.');
396
- await load();
397
- const again = b.dataset.ws ? $(`#pickMenu [data-ws="${CSS.escape(b.dataset.ws)}"]`) : null; if (again) again.focus();
398
- });
399
-
400
- /* ── Around you: what the agents and the outside world left for you (initiative premium-briefing-depth) ─────────────────────────────
401
- * One card under Today with six rows; each row opens the standard dialog. Every read is a route the console already uses and every
402
- * write is a press that says what it does first, through the launch nonce (pmPost). A source that cannot be read is named in its row,
403
- * never shown as empty. Which products: ?ws=<id> that one, otherwise every product the Briefing reads. */
404
- const SRCN = { slack: 'Slack', jira: 'Jira', confluence: 'Confluence', mail: 'Mail' };
405
- const srcName = (s) => SRCN[s] || String(s || 'a source');
406
- const first = (s) => String(s || '').trim().split(/\s+/)[0];
407
- const pl = (n, one, many) => n + ' ' + (n === 1 ? one : many);
408
- const BDI = {
409
- at: '<circle cx="12" cy="12" r="4"/><path d="M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1"/>',
410
- prop: '<path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/>',
411
- pulse: '<path d="M3 12h4l3-7 4 14 3-7h4"/>',
412
- scan: '<circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/>',
413
- rep: '<path d="M7 3h8l4 4v14H7z"/><path d="M14 3v5h5M10 13h6M10 17h6"/>',
414
- src: '<path d="M20 11a8 8 0 0 0-14.6-4.5M4 13a8 8 0 0 0 14.6 4.5"/><path d="M5 3v4h4M19 21v-4h-4"/>',
415
- ret: '<path d="M9 14 4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12h-3"/>',
416
- x: '<path d="M6 6l12 12M18 6 6 18"/>',
417
- };
418
- const bdIco = (d) => `<svg class="i" viewBox="0 0 24 24">${d}</svg>`;
419
- const A = { prop: null, men: null, pulse: null, scan: null, rep: null, src: null }; // the last answer of each source: { ok, … } or { ok: false, error }
420
- const DEC = new Map(); // proposals decided on this visit: id → { item, st: 'kept' | 'back' | 'dropped', note, wrote, warnings }
421
- const PNOTE = {}, PERR = {}, PBACK = new Set(); // the send-back note typed, the refusal shown, the proposals whose note box is open
422
- const MREAD = new Map(), MADD = new Set(); // mentions marked read or unread on this visit; mentions made a task
423
- const SDEC = new Map(); // scan proposals decided on this visit: id → { st: 'ok' | 'no', result }
424
- const SERR = {}, SWHY = {}, SOPEN = new Set(); // a scan proposal's dismissal reason, and the proposals whose reason box is open
425
- let MTAB = 'all', BUSY = '';
426
- const getj = async (p) => { const r = await pmGet(p); return r && r.ok !== false ? r : { ok: false, error: (r && r.error) || 'the server did not answer' }; };
427
- const wq = (ws) => (ws ? 'ws=' + encodeURIComponent(ws) : '');
428
- const prods = () => {
429
- const one = wsParam(); if (one) return [{ ws: one, name: one }];
430
- const P = M && M.products;
431
- return P ? P.available.filter((x) => x.on).map((x) => ({ ws: x.ws, name: x.name })) : [{ ws: '', name: '' }];
432
- };
433
- const said = (r) => 'could not be read: ' + (r && r.error ? r.error : 'the server did not answer');
434
-
435
- /* reads */
436
- async function readProps(P) {
437
- const items = [], errs = [];
438
- await Promise.all(P.flatMap((p) => ['initiative', 'work'].map(async (kind) => {
439
- const r = await getj('/api/driver/open?target_kind=' + kind + (p.ws ? '&' + wq(p.ws) : ''));
440
- if (!r.ok) { errs.push(r.error); return; }
441
- if (r.mode !== 'approve') return; // Off and Shadow raise nothing on the Briefing (the console draws the same)
442
- for (const [tid, list] of Object.entries(r.targets || {})) for (const pr of list) items.push({ id: pr.id, ws: r.ws, pname: P.length > 1 ? p.name : '', kind, tid, p: pr, title: '' });
443
- })));
444
- items.sort((a, b) => String(a.p.at).localeCompare(String(b.p.at)) || a.id.localeCompare(b.id));
445
- if (items.some((x) => x.kind === 'work')) {
446
- const w = await getj('/api/pm-items'), by = new Map(((w.ok && w.items) || []).map((i) => [i.id, i.title]));
447
- items.forEach((x) => { if (x.kind === 'work') x.title = by.get(x.tid) || ''; });
448
- }
449
- if (!items.length && errs.length) return { ok: false, error: errs[0] };
450
- return { ok: true, items, errs };
451
- }
452
- const briefPage = (force) => (BP && !force && Date.now() - BP.at < 30000 ? BP.p : (BP = { at: Date.now(), p: getj('/api/brief-page') }).p); // one read of the day for the Around you card and the phone card
453
- let BP = null;
454
- async function readMen() {
455
- const r = await briefPage();
456
- return r.ok ? { ok: true, list: Array.isArray(r.mentions) ? r.mentions : null } : r;
457
- }
458
- const PST = { 'on time': ['ok', 'On time'], 'at risk': ['warn', 'At risk'], delayed: ['bad', 'Delayed'], overdue: ['bad', 'Overdue'], 'no plan': ['', 'No plan'] };
459
- /** One Calendar row as the pulse draws it. cls: bad (late) · warn (at risk) · ok (on plan) · '' (no plan date). The Calendar's own status, no forecast of ours. */
460
- function pulseRow(g) {
461
- const j = g.jira && Number.isInteger(g.jira.total) && g.jira.total > 0 && Number.isInteger(g.jira.done) ? g.jira : null;
462
- const f = (g.forecast && (g.forecast.end || g.forecast.start)) || null;
463
- if (j && (!PST[g.status] || g.status === 'no plan')) {
464
- const all = j.done >= j.total;
465
- return { id: g.id, title: g.title || g.id, cls: j.blocked > 0 ? 'warn' : all ? 'ok' : '', word: j.blocked > 0 ? 'Blocked' : all ? 'Done in Jira' : 'In progress',
466
- why: j.done + ' of ' + j.total + ' done in Jira' + (j.blocked > 0 ? ', ' + j.blocked + ' blocked' : '') + '; no promised date' };
467
- }
468
- const k = PST[g.status] ? g.status : 'no plan', p = g.promised || null;
469
- return { id: g.id, title: g.title || g.id, cls: PST[k][0], word: PST[k][1] + (g.slip_days > 0 ? ' +' + g.slip_days + ' d' : ''),
470
- why: (p ? 'Forecast ' + (f || 'not set') + ' vs promised ' + p : 'No promised date' + (f ? '; forecast ' + f : '')) + (j ? '. ' + j.done + ' of ' + j.total + ' done in Jira' : '') };
471
- }
472
- async function readPulse(P) {
473
- const d = new Date(), day = d.getFullYear() + '-' + STAMP(d.getMonth() + 1) + '-' + STAMP(d.getDate()), rows = [], errs = [];
474
- let none = 0;
475
- await Promise.all(P.map(async (p, i) => {
476
- const r = await getj('/api/calendar-views?view=quarter&only=gantt&date=' + day + (p.ws ? '&' + wq(p.ws) : ''));
477
- if (!r.ok) { errs.push(r.error); return; }
478
- none += Number(r.no_plan) || 0;
479
- for (const g of r.gantt || []) rows.push({ ...pulseRow(g), ws: p.ws, pname: P.length > 1 ? p.name : '', at: i });
480
- }));
481
- rows.sort((a, b) => a.at - b.at);
482
- if (!rows.length && !none && errs.length) return { ok: false, error: errs[0] };
483
- return { ok: true, rows, none, errs };
484
- }
485
- async function readScan(P) {
486
- const got = [], errs = [];
487
- await Promise.all(P.map(async (p, i) => {
488
- const r = await getj('/api/scan/portfolio' + (p.ws ? '?' + wq(p.ws) : ''));
489
- if (!r.ok) errs.push(r.error); else got.push({ ...r, pname: P.length > 1 ? p.name : '', at: i });
490
- }));
491
- got.sort((a, b) => a.at - b.at);
492
- if (!got.length && errs.length) return { ok: false, error: errs[0] };
493
- return { ok: true, scans: got, errs };
494
- }
495
- /** The report finder's findings, one read per product. A product that cannot be read is named, never shown as empty. */
496
- async function readReps(P) {
497
- const got = [], errs = [];
498
- await Promise.all(P.map(async (p, i) => {
499
- const r = await getj('/api/report-setups' + (p.ws ? '?' + wq(p.ws) : ''));
500
- if (!r.ok) errs.push((P.length > 1 && p.name ? p.name + ': ' : '') + r.error);
501
- else got.push({ ws: r.ws || p.ws, pname: P.length > 1 ? p.name : '', at: i, finder: r.finder || null, findings: Array.isArray(r.findings) ? r.findings : [] });
502
- }));
503
- got.sort((a, b) => a.at - b.at);
504
- if (!got.length && errs.length) return { ok: false, error: errs[0] };
505
- return { ok: true, prods: got, errs };
506
- }
507
- const readSrc = () => getj('/api/sources' + (wsParam() ? '?' + wq(wsParam()) : ''));
508
- const readAll = async (which) => {
509
- const P = prods(), all = !which, job = {
510
- prop: () => readProps(P), men: () => readMen(), pulse: () => readPulse(P), scan: () => readScan(P), rep: () => readReps(P), src: () => readSrc(),
511
- };
512
- await Promise.all(Object.keys(job).filter((k) => all || which.includes(k)).map(async (k) => { try { A[k] = await job[k](); } catch (e) { A[k] = { ok: false, error: String((e && e.message) || e) }; } }));
513
- drawAround();
514
- };
515
-
516
- /* words */
517
- const PWHAT = { problem: 'Problem statement', evidence: 'Evidence', sizing: 'Opportunity sizing', assumption: 'Riskiest assumption and spike brief', stakeholders: 'Stakeholders', move: 'Move', note: 'Note', 'next-step': 'Next step', 'follow-up': 'Follow-up' };
518
- const pWhat = (p) => (p.what === 'move' && p.data && p.data.to ? 'Move to ' + p.data.to : PWHAT[p.what] || p.what);
519
- const pKeep = (p) => ({ problem: 'Keep writes the problem statement into the stage record.', move: 'Keep moves the initiative on its board.', 'next-step': 'Keep adds the next step to your Work item.', 'follow-up': 'Keep copies the follow-up text. Nothing is sent to anyone.', doc: 'Keep issues the draft document.' }[p.what] || 'Keep records that you accept it. Nothing else changes.');
520
- const pWrote = (w) => ({ problem: 'The problem statement is in the stage record.', move: 'The initiative moved.', doc: 'The document was issued.', 'next-step': 'The next step is in your Work item.' }[w] || 'It is recorded. Nothing else changed.');
521
- const pText = (p) => {
522
- const t = p.data && typeof p.data.text === 'string' ? p.data.text : '';
523
- if (p.what === 'move') return 'Move this initiative to ' + ((p.data && p.data.to) || 'the next stage') + '.';
524
- if (t) return t;
525
- if (p.data && Array.isArray(p.data.items)) return pl(p.data.items.length, 'item', 'items') + ' with a pointer each.';
526
- return '';
527
- };
528
- const iniTitle = (x) => { const r = A.pulse && A.pulse.ok && A.pulse.rows.find((y) => y.id === x.tid && y.ws === x.ws); return r ? r.title : ''; };
529
- const targetOf = (x) => (x.kind === 'work' ? 'Work · ' : 'Initiative · ') + (x.title || (x.kind === 'initiative' ? iniTitle(x) : '') || x.tid);
530
- const openProps = () => (A.prop && A.prop.ok ? A.prop.items : []);
531
- const shownMen = () => {
532
- const l = A.men && A.men.ok && A.men.list ? A.men.list : [];
533
- return l.filter((m) => !m.in_needs && (MREAD.has(m.id) || !m.read)).map((m) => (MREAD.has(m.id) ? { ...m, read: MREAD.get(m.id) } : m));
534
- };
535
- const waitM = (l) => l.filter((m) => m.reply && !m.read);
536
- function menLine(l) {
537
- const w = waitM(l), rest = l.filter((m) => !m.read).length - w.length;
538
- if (!w.length) return rest ? 'No one is waiting on a reply. ' + pl(rest, 'mention is', 'mentions are') + ' for your information.' : 'No mentions are left unread.';
539
- const names = w.map((m) => (m.who ? first(m.who) : 'Someone') + ' in ' + srcName(m.source)), s = names.length < 2 ? names[0] : names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1];
540
- return s + (w.length === 1 ? ' is' : ' are') + ' waiting on your reply.' + (rest ? ' ' + rest + (rest === 1 ? ' more is' : ' more are') + ' for your information.' : '');
541
- }
542
- const mWhen = (iso) => {
543
- if (!iso) return '';
544
- const d = new Date(iso), n = new Date(), hm = STAMP(d.getHours()) + ':' + STAMP(d.getMinutes()), k = (x) => x.getFullYear() * 400 + x.getMonth() * 32 + x.getDate(), y = new Date(n); y.setDate(y.getDate() - 1);
545
- return k(d) === k(n) ? hm : k(d) === k(y) ? 'yesterday ' + hm : d.getDate() + '/' + (d.getMonth() + 1) + ' ' + hm;
546
- };
547
- const groups = (rows) => ({ bad: rows.filter((r) => r.cls === 'bad'), warn: rows.filter((r) => r.cls === 'warn'), ok: rows.filter((r) => r.cls === 'ok'), none: rows.filter((r) => !r.cls) });
548
- const PGW = { bad: 'Late', warn: 'At risk', ok: 'On plan', none: 'No plan date' };
549
- const bar = (g, n, extra) => `<span class="bd-bar" aria-hidden="true">${['bad', 'warn', 'ok', 'none'].map((k) => { const c = k === 'none' ? g.none.length + extra : g[k].length; return c ? `<i class="${k}" style="width:${c / n * 100}%"></i>` : ''; }).join('')}</span>`;
550
- const dayWord = (iso) => {
551
- const d = new Date(iso); if (!Number.isFinite(d.getTime())) return '';
552
- const n = new Date(), y = new Date(n), hm = STAMP(d.getHours()) + ':' + STAMP(d.getMinutes()); y.setDate(y.getDate() - 1);
553
- return d.toDateString() === n.toDateString() ? 'today, ' + hm : d.toDateString() === y.toDateString() ? 'yesterday, ' + hm : d.getDate() + ' ' + ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()] + ', ' + hm;
554
- };
555
- const scanOpen = () => (A.scan && A.scan.ok ? A.scan.scans.reduce((n, s) => n + (s.proposals_waiting || 0), 0) : 0);
556
- const REC = new Map(); // findings decided on this visit: id → { st: 'set' | 'no', f, setup }
557
- const RERR = {};
558
- const repFound = () => (A.rep && A.rep.ok ? A.rep.prods.flatMap((q) => q.findings.map((f) => ({ ...f, ws: q.ws, pname: q.pname }))) : []);
559
- const behindSrc = () => {
560
- if (!A.src || !A.src.ok) return [];
561
- const ids = behindOf(lineItems(A.src.sources)).map((i) => i.id);
562
- return A.src.sources.filter((s) => ids.includes(s.id));
563
- };
564
- const joinN = (a) => (a.length < 2 ? a.join('') : a.slice(0, -1).join(', ') + ' and ' + a[a.length - 1]);
565
-
566
- /** What Scan now may do right now, in the server's own words: the manual scans left today, or why it cannot start. Empty when the server says neither. */
567
- function scanNowLine(S) {
568
- if (S.length && S.every((x) => x.switched_off)) return ' · Scan now is off here';
569
- const M = S.map((x) => x.manual).filter((m) => m && m.limit);
570
- if (!M.length) { const no = S.map((x) => x.manual).find((m) => m && m.ok === false && m.error); return no ? ' · ' + no.error : ''; }
571
- const left = M.reduce((n, m) => n + (m.left || 0), 0), lim = M.reduce((n, m) => n + m.limit, 0);
572
- return M.every((m) => m.ok === false) ? ' · Scan now: ' + (M[0].error || 'not now') : ' · Scan now: ' + left + ' of ' + lim + ' left today';
573
- }
574
-
575
- /** The six rows of the card: { k, ic, t, s, m (count html), bar, wait }. Pure of the DOM; every word comes from A. */
576
- function aroundRows() {
577
- const R = [], rd = 'Reading…';
578
- { // agent proposals
579
- const a = A.prop, n = a && a.ok ? a.items.length : 0;
580
- R.push({ k: 'prop', ic: BDI.prop, wait: n > 0,
581
- t: !a ? rd : !a.ok ? 'Agent proposals ' + said(a) : n ? pl(n, 'agent proposal waits', 'agent proposals wait') + ' on you' : 'No agent proposals wait',
582
- s: !a ? '' : !a.ok ? '' : n ? 'Keep, send back or drop each one' : 'The agent files a draft here when it has one', m: n ? `<span class="due">${n}</span>` : '' });
583
- }
584
- { // mentions
585
- const a = A.men, l = shownMen(), w = waitM(l);
586
- R.push({ k: 'men', ic: BDI.at, wait: w.length > 0,
587
- t: !a ? rd : !a.ok ? 'Mentions ' + said(a) : a.list === null ? 'No brief for today, so no mentions were read' : l.filter((m) => !m.read).length ? menLine(l) : 'No one has mentioned you today',
588
- s: !a || !a.ok || !l.filter((m) => !m.read).length ? '' : [...new Set(l.filter((m) => !m.read).map((m) => srcName(m.source)))].join(', '),
589
- m: w.length ? '<span class="due od">Reply</span>' : '' });
590
- }
591
- { // portfolio pulse
592
- const a = A.pulse, g = a && a.ok ? groups(a.rows) : null, n = a && a.ok ? a.rows.length + a.none : 0;
593
- R.push({ k: 'pulse', ic: BDI.pulse, wait: !!(g && g.bad.length),
594
- t: !a ? rd : !a.ok ? 'Portfolio pulse ' + said(a) : n ? `Portfolio pulse: ${g.bad.length} late, ${g.warn.length} at risk` : 'Portfolio pulse: nothing to compare yet',
595
- s: !a || !a.ok ? '' : n ? `${g.ok.length} on plan · ${g.none.length + a.none} with no plan date` : 'No initiative has a promised date or a Jira read.',
596
- bar: n ? bar(g, n, a.none) : '', m: '' });
597
- }
598
- { // horizon scan
599
- const a = A.scan, S = a && a.ok ? a.scans : [], w = scanOpen(), run = S.some((x) => x.open), last = S.map((x) => x.last && x.last.at).filter(Boolean).sort().pop(), nrep = S.reduce((n, x) => n + x.reports.filter((r) => r.written && !r.parent).length, 0);
600
- R.push({ k: 'scan', ic: BDI.scan, wait: w > 0,
601
- t: !a ? rd : !a.ok ? 'Horizon scan ' + said(a) : run ? 'Horizon scan: scanning now' : w ? 'Horizon scan: ' + pl(w, 'proposal waits', 'proposals wait') + ' for you' : S.every((x) => x.switched_off) ? 'Horizon scan: switched off' : last ? 'Horizon scan: nothing waits' : 'Horizon scan: no scan has run yet',
602
- s: !a || !a.ok ? '' : run ? 'Reading the web and the repository' : (last ? 'Ran ' + dayWord(last).toLowerCase() + (nrep ? ' · ' + pl(nrep, 'report', 'reports') : '') : 'Start one from here') + scanNowLine(S), m: w ? `<span class="due">${w}</span>` : '' });
603
- }
604
- { // report found
605
- const a = A.rep, L = repFound(), n = L.length, fd = a && a.ok ? a.prods.map((q) => q.finder).filter(Boolean) : [], off = fd.length > 0 && fd.every((x) => x.cadence === 'off'), nx = fd.map((x) => x.next_run).filter(Boolean).sort()[0];
606
- R.push({ k: 'rep', ic: BDI.rep, wait: n > 0,
607
- t: !a ? rd : !a.ok ? 'Report finder ' + said(a) : n === 1 ? 'Report found: ' + L[0].name : n ? pl(n, 'report', 'reports') + ' found in your work' : off ? 'The report finder is off' : 'No report found',
608
- s: !a || !a.ok ? '' : n ? 'Set it up, or say it is not a report' : nx ? 'The finder looks next ' + dayWord(nx) : off ? 'Switch it on in the console' : 'It reads your calendar, Slack and the subjects of mail you sent', m: n ? `<span class="due">${n}</span>` : '' });
609
- }
610
- { // data freshness
611
- const a = A.src, b = behindSrc();
612
- R.push({ k: 'src', ic: BDI.src, wait: b.length > 0,
613
- t: !a ? rd : !a.ok ? 'Data freshness ' + said(a) : b.length > 2 ? b.length + ' sources need a new read' : b.length ? joinN(b.map((s) => s.label)) + (b.length === 1 ? ' needs' : ' need') + ' a new read' : 'Every source was read recently',
614
- s: !a || !a.ok ? '' : b.length > 2 ? joinN(b.map((s) => s.label)) + '. Read on a schedule, not live' : 'Sources are read on a schedule, not live', m: b.length ? `<span class="due">${b.length}</span>` : '' });
615
- }
616
- return R;
617
- }
618
- function drawAround() {
619
- const B = $('#aroundBody'); if (!B) return;
620
- const R = aroundRows(), n = R.filter((r) => r.wait).length;
621
- B.innerHTML = R.map((r) => `<div class="wrw"><div class="wrow sm" data-bdrow="${r.k}"><span class="wgl" aria-hidden="true">${bdIco(r.ic)}</span><button type="button" class="wrh" data-bd="${r.k}" aria-haspopup="dialog"><span class="wtx"><span class="wtit">${esc(r.t)}</span>${r.s ? `<span class="ws">${esc(r.s)}</span>` : ''}${r.bar || ''}</span>${r.m ? `<span class="wm">${r.m}</span>` : ''}</button></div></div>`).join('');
622
- $('#aroundCap').textContent = Object.values(A).some((x) => x === null) ? 'Reading' : n ? n + ' to look at' : 'quiet';
623
- }
624
-
625
- /* the dialogs: each draws into the dialog's Detail pane and redraws after a press, with its own conversation beside it (premium-popup-context P1) */
626
- function bdDlg(key, eye, title, sub, say, draw, onPress, onInput) {
627
- openDlg({ eye, title, sub, say, stream: turnA(ptx(say)), noteKey: popKey('around', key), pane: '<article class="paper doc"><div class="bd-a"></div></article>', label: title });
628
- setMode('detail');
629
- const o = $('#oMain'); o.dataset.bd = key;
630
- const redraw = (focus) => {
631
- const a = $('.bd-a', o); if (!a) return; // the dialog has moved on (on Home the dock goes back to your own chat): nothing of this row is left to redraw
632
- a.innerHTML = draw();
633
- if (focus) { const f = $(focus, o) || $('.bd-a button:not([disabled]), .bd-a a', o); if (f) f.focus(); }
634
- };
635
- o.onclick = (e) => { if (o.dataset.bd === key) onPress(e, redraw); };
636
- o.oninput = (e) => { if (o.dataset.bd === key && onInput) onInput(e); };
637
- redraw();
638
- return redraw;
639
- }
640
- const bdActs = (...b) => `<div class="bd-acts">${b.join('')}</div>`;
641
- const bdBtn = (label, act, id, alt, attrs) => `<button type="button" class="cta${alt ? ' alt' : ''}" data-bda="${act}"${id != null ? ` data-id="${esc(id)}"` : ''}${attrs || ''}>${esc(label)}</button>`;
642
- const bdDone = (ok, text) => `<p class="bd-done" role="status">${ok ? CHECK : bdIco(BDI.x)}<span>${esc(text)}</span></p>`;
643
- const bdChip = (t, c) => `<span class="bd-chip${c ? ' ' + c : ''}">${esc(t)}</span>`;
644
- const bdLink = (href) => (/^https:\/\/\S+$/i.test(String(href || '')) ? href : '');
645
- const bdFail = (id, e) => (e[id] ? `<p class="nodef err" role="alert">${esc(e[id])}</p>` : '');
646
-
647
- /* ── agent proposals: one card per proposal, one bottom bar for the chosen card (Keep is the only primary), the notes behind one ⓘ ── */
648
- const PMORE = new Set(); // the cards whose Read more is open
649
- let PSEL = '', PINFO = false; // the card the bottom bar acts on; the ⓘ notes open
650
- function propItem(it, sel) {
651
- const p = it.p, d = DEC.get(it.id), id = it.id, text = pText(p), more = PMORE.has(id), on = !d && id === sel;
652
- const src = (p.sources || []).filter((s) => s && s.ref).map((s) => (bdLink(s.ref) ? `<a href="${esc(bdLink(s.ref))}" target="_blank" rel="noopener noreferrer">${esc(s.label || s.ref)}</a>` : esc((s.label ? s.label + ': ' : '') + s.ref))).join(' · ');
653
- const line = text || (p.why ? 'Why: ' + p.why : ''), extra = (text && p.why) || src;
654
- let act = '';
655
- if (d) act = d.st === 'kept' ? bdDone(true, 'Kept. ' + pWrote(d.wrote) + (d.warnings.length ? ' ' + d.warnings.join(' ') : '')) : d.st === 'back' ? bdDone(true, 'Sent back with your note: “' + d.note + '”. The note starts a new run.') : bdDone(false, 'Dropped. It counts as a correction.');
656
- else if (on && !PBACK.has(id)) act = bdFail(id, PERR);
657
- const pick = d ? `<span class="bd-t">${esc(targetOf(it))}</span>` : `<button type="button" class="bd-t pc-pick" data-bda="psel" data-id="${esc(id)}" aria-pressed="${on}">${esc(targetOf(it))}</button>`;
658
- return `<div class="bd-it pcard${d ? ' decided' : ''}${on ? ' on' : ''}" data-id="${esc(id)}"${d ? '' : ` data-bda="psel"`}><small class="pc-k">${esc(pWhat(p))}${it.pname ? ' · ' + esc(it.pname) : ''}</small>${pick}`
659
- + (line ? `<p class="pc-line${more ? ' open' : ''}"><span>${esc(line)}</span>${extra ? `<button type="button" class="pc-more" data-bda="pmore" data-id="${esc(id)}" aria-expanded="${more}">${more ? 'Less' : 'Read more'}</button>` : ''}</p>` : '')
660
- + (extra ? `<div class="pc-x"${more ? '' : ' hidden'}>${text && p.why ? `<p class="bd-why">Why: ${esc(p.why)}</p>` : ''}${src ? `<p class="bd-why">Sources: ${src}</p>` : ''}</div>` : '') + act + '</div>';
661
- }
662
- /* ── portfolio documents: the shared document sheet (premium-doc-sheet.js) over GET /api/core-docs?level=portfolio, on the Briefing ── */
663
- const CDS = { missing: 'Not started', draft: 'Draft', ok: 'Up to date', stale: 'Stale', due: 'Due' };
664
- const PD = { ws: null, scope: 'portfolio', rows: [] };
665
- async function readPortfolioDocs() {
666
- const r = await getj('/api/core-docs?level=portfolio' + (PD.ws ? '&' + wq(PD.ws) : ''));
667
- if (!r.ok) return r;
668
- PD.scope = r.scope || 'portfolio';
669
- PD.rows = (r.docs || []).map((d) => ({ key: d.key, title: d.title, what: d.for || '', state: d.kind === 'live' ? 'Live' : CDS[d.st] || d.st || '', st: d.st, path: d.open && d.open.path ? d.open.path : null, slot: d.st === 'draft' && d.draft && d.draft.slot ? d.draft.slot : '' }));
670
- return r;
671
- }
672
- const pdSheet = mountDocSheet({ ws: () => PD.ws, scope: () => PD.scope, rows: () => PD.rows, reload: async () => { await readPortfolioDocs(); drawConsoleBrief(); }, noteKey: (d) => 'doc:portfolio:' + d.key, sub: () => 'Portfolio documents', again: true });
673
- async function openCoreDraft(t) {
674
- PD.ws = t.ws || wsParam() || null;
675
- const r = await readPortfolioDocs();
676
- if (!r.ok) { toast('The portfolio documents ' + said(r) + '.'); return; }
677
- const d = PD.rows.find((x) => t.path && x.path === t.path) || PD.rows.find((x) => x.st === 'draft' && x.path);
678
- if (!d) { toast('No portfolio draft waits now. It may have been issued since the list was read.'); drawConsoleBrief(); return; }
679
- pdSheet.open(d);
680
- }
681
-
682
- /* PFOCUS: the one target a "What you need to do" row opened the dialog on ({ kind, ws, id }), the one proposal the bell opened it on ({ proposal, ws }),
683
- * or null for every proposal. Show all clears it. A focus from the bell (premium-agent-inbox) also carries `bell` and the target's drafts row key `session`. */
684
- let PFOCUS = null;
685
- const inFocus = (it) => !PFOCUS || (PFOCUS.proposal ? it.id === PFOCUS.proposal && (!PFOCUS.ws || it.ws === PFOCUS.ws) : it.kind === PFOCUS.kind && it.tid === PFOCUS.id && (!PFOCUS.ws || it.ws === PFOCUS.ws));
686
- /** The Driver target of an agent drafts row (its run id driver-needs:<drafts|blocked>:<kind>:<ws>:<id>), or null: Review the drafts opens that target's proposals. */
687
- function rowTarget(r) {
688
- const m = /driver-needs:(?:drafts|blocked):(initiative|work):([^:]+):(.+)$/.exec(String((r && r.from && r.from[0]) || ''));
689
- return m ? { kind: m[1], ws: m[2], id: m[3] } : null;
690
- }
691
- /** The agent's drafts rows and goal rows (in model.agent since premium-agent-inbox) and the list's rows: a deep link opens one by its key. */
692
- const anyRow = (key) => [].concat(M && M.agent ? M.agent.rows || [] : [], M && M.agent ? M.agent.goals || [] : [], M ? M.list.rows : [], CL || []).find((r) => r.key === key) || null;
693
- const propSel = (L) => { const w = L.filter((it) => !DEC.has(it.id)); return (w.find((it) => it.id === PSEL) || w[0] || {}).id || ''; };
694
- function propsHtml() {
695
- const a = A.prop; if (!a.ok) return `<p class="nodef err" role="alert">Agent proposals ${esc(said(a))}</p>`;
696
- const all = a.items.concat([...DEC.values()].map((d) => d.item).filter((it) => !a.items.some((o) => o.id === it.id)));
697
- const L = all.filter(inFocus), rest = PFOCUS ? a.items.length - a.items.filter(inFocus).length : 0, sel = propSel(L), it = L.find((x) => x.id === sel);
698
- const extra = PFOCUS ? [PFOCUS.session && anyRow(PFOCUS.session) ? bdBtn('Talk to the agent', 'psess', null, true) : '', PFOCUS.bell ? bdBtn('Back to Needs you', 'pbell', null, true) : ''].filter(Boolean) : [];
699
- const more = PFOCUS ? `<button type="button" class="pc-all" data-bda="pall"><b>${rest ? pl(rest, 'more', 'more') + ' on other work' : 'Show all proposals'}</b>${CHEV}</button>` + (extra.length ? bdActs(...extra) : '') : '';
700
- const notes = [it ? pKeep(it.p) + ' Drop counts as a correction. Send back starts a new run with your note. None of the three can be undone.' : '', 'The agent mode (Off, Shadow, Approve) stays in the console. This list shows a kind only when its mode is Approve.', a.errs.length ? 'Not read: ' + a.errs[0] : ''].filter(Boolean);
701
- const info = `<div class="pc-info"><button type="button" data-bda="pinfo" aria-expanded="${PINFO}" aria-controls="pcNotes"><i class="pc-i" aria-hidden="true">i</i>Nothing changes a record until you keep it</button><div id="pcNotes"${PINFO ? '' : ' hidden'}>${notes.map((t) => `<p class="bd-why">${esc(t)}</p>`).join('')}</div></div>`;
702
- const back = it && PBACK.has(it.id), id = it ? esc(it.id) : '';
703
- const note = back ? `<label class="bd-l" for="bdn-${id}">What should the agent change?</label><textarea id="bdn-${id}" data-bdn="${id}" maxlength="500" rows="2">${esc(PNOTE[it.id] || '')}</textarea>${bdFail(it.id, PERR)}` : '';
704
- const bar = !it ? '' : `<div class="pc-bar">${note}<div class="pc-row">${back
705
- ? `<button type="button" class="pc-q" data-bda="pcancel" data-id="${id}">Cancel</button><button type="button" class="pc-p" data-bda="pback" data-id="${id}"${(PNOTE[it.id] || '').trim() ? '' : ' disabled'}>Send back</button>`
706
- : `<button type="button" class="pc-q" data-bda="pnote" data-id="${id}">Send back</button><button type="button" class="pc-q" data-bda="pdrop" data-id="${id}">Drop</button><button type="button" class="pc-p" data-bda="pkeep" data-id="${id}">Keep</button>`}</div><p class="pc-fine">${L.filter((x) => !DEC.has(x.id)).length > 1 ? 'For the chosen card · ' : ''}Can’t be undone</p></div>`;
707
- return (L.length ? `<div class="bd-list pc-list">${L.map((x) => propItem(x, sel)).join('')}</div>` : `<p class="empty3">${CHECK}${PFOCUS ? 'No proposal waits on this one. It may have been decided since the list was read.' : 'No agent proposals wait.'}</p>`) + more + info + bar;
708
- }
709
- const propTitle = () => { const a = A.prop; if (!a || !a.ok) return 'Agent proposals'; const n = a.items.filter(inFocus).length; return n ? n + (n === 1 ? ' waits' : ' wait') + ' for you' : 'All decided'; };
710
- async function propPress(e, redraw) {
711
- const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
712
- if (b.dataset.bda === 'pall') { PFOCUS = null; redraw(); return; }
713
- if (b.dataset.bda === 'psess') { const r = anyRow(PFOCUS && PFOCUS.session); closeDlg(); if (r) openRow(r); return; } // the target's drafts row: its conversation is the agent's session
714
- if (b.dataset.bda === 'pbell') { closeDlg(); pvOpenBell(); return; }
715
- if (b.dataset.bda === 'pinfo') { PINFO = !PINFO; redraw('[data-bda="pinfo"]'); return; }
716
- const act = b.dataset.bda, id = b.dataset.id;
717
- if (act === 'pmore') { if (PMORE.has(id)) PMORE.delete(id); else PMORE.add(id); redraw(`[data-bda="pmore"][data-id="${CSS.escape(id)}"]`); return; }
718
- const it = openProps().find((x) => x.id === id);
719
- if (!it) return;
720
- if (act === 'psel') { const was = b.closest('.pcard.on'); PSEL = id; if (!was) { redraw(`[data-bda="psel"][data-id="${CSS.escape(id)}"]`); } return; }
721
- if (act === 'pnote') { PBACK.add(id); redraw(`[data-bdn="${CSS.escape(id)}"]`); return; }
722
- if (act === 'pcancel') { PBACK.delete(id); delete PERR[id]; redraw(`[data-bda="pnote"][data-id="${CSS.escape(id)}"]`); return; }
723
- const note = (PNOTE[id] || '').trim();
724
- if (act === 'pback' && !note) { PERR[id] = 'Write one line for the agent. A note starts its next run.'; redraw(`[data-bdn="${CSS.escape(id)}"]`); return; }
725
- BUSY = id; b.disabled = true;
726
- const r = await pmPost('/api/driver/' + (act === 'pkeep' ? 'keep' : act === 'pback' ? 'return' : 'drop'), { ws: it.ws, proposal: id, ...(act === 'pback' ? { note } : {}) });
727
- BUSY = '';
728
- if (!r || r.ok !== true) { PERR[id] = (r && r.error) || 'It was not recorded.'; redraw(); return; }
729
- delete PERR[id]; PBACK.delete(id);
730
- DEC.set(id, { item: it, st: act === 'pkeep' ? 'kept' : act === 'pback' ? 'back' : 'dropped', note, wrote: r.wrote, warnings: r.warnings || [] });
731
- toast(act === 'pkeep' ? 'Kept.' : act === 'pback' ? 'Sent back with your note.' : 'Dropped. It counts as a correction.');
732
- await readAll(['prop']); redraw('.pc-bar .pc-p:not([disabled])');
733
- }
734
- /** ?open= (premium-agent-inbox): the bell's deep link. prop:<id> opens the Agent proposals dialog on that one proposal, target:<kind>:<id> on that target's,
735
- * row:<key> a drafts or goal row's dialog, whose conversation is the session. pws names the product. On this page the bell opens it in place ('pmos:open'). */
736
- function openParam(open, pws) {
737
- const v = String(open || ''), ws = pws || null;
738
- let m;
739
- if ((m = /^prop:(.+)$/.exec(v))) {
740
- const it = openProps().find((x) => x.id === m[1] && (!ws || x.ws === ws));
741
- openPropsDlg({ proposal: m[1], ws, bell: true, session: it ? rowKeyOf(it) : null });
742
- } else if ((m = /^target:(initiative|work):(.+)$/.exec(v))) openPropsDlg({ kind: m[1], id: m[2], ws, bell: true, session: ws ? rowKeyOf({ kind: m[1], ws, tid: m[2] }) : null });
743
- else if ((m = /^row:(.+)$/.exec(v))) { const r = anyRow(m[1]); if (r) openRow(r); else toast('That item no longer waits on you. It may have been decided since.'); }
744
- }
745
- /** The key of a target's drafts row (lib/agent-inbox.js draftsRowKey): the row's conversation is that target's agent session. */
746
- function rowKeyOf(it) {
747
- const k = (M && M.agent && M.agent.rows || []).find((r) => { const t = rowTarget(r); return t && t.kind === it.kind && t.ws === it.ws && t.id === it.tid; });
748
- return k ? k.key : null;
749
- }
750
- function openOpenParam() {
751
- const q = new URLSearchParams(location.search), v = q.get('open');
752
- if (!v || /^(report|chart|dashboard):/.test(v)) return; // Home's chat (premium-chat.js) owns ?open=report: | chart: | dashboard: and keeps it in the address
753
- try { const u = new URL(location.href); u.searchParams.delete('open'); u.searchParams.delete('pws'); history.replaceState(history.state, '', u); } catch { /* no history */ }
754
- openParam(v, q.get('pws'));
755
- }
756
- document.addEventListener('pmos:open', (e) => { if (!M) return; const d = e.detail || {}; (A.prop ? Promise.resolve() : readAll(['prop'])).then(() => openParam(d.open, d.pws)); });
757
- /** ?around=<prop|scan|rep|src|men|pulse> opens that Around you dialog once its read is in: another premium page links here (a board document's Run a scan). */
758
- function openAroundParam() {
759
- const k = new URLSearchParams(location.search).get('around'), fn = { prop: openPropsDlg, men: openMen, pulse: openPulse, scan: openScan, rep: openReport, src: openSrc }[k];
760
- if (!fn) return;
761
- try { const u = new URL(location.href); u.searchParams.delete('around'); history.replaceState(history.state, '', u); } catch { /* no history */ }
762
- fn();
763
- }
764
- const openPropsDlg = async (focus) => {
765
- PFOCUS = focus && ((focus.kind && focus.id) || focus.proposal) ? focus : null;
766
- if (PFOCUS && !A.prop) await readAll(['prop']); // pressed before Around you has read: read the proposals first
767
- const n = openProps().filter(inFocus).length; PSEL = ''; PINFO = false;
768
- bdDlg('prop', 'Agent proposals', propTitle(), '',
769
- A.prop && A.prop.ok ? (n ? pl(n, 'proposal waits', 'proposals wait') + ' for you. Keep one to record it, send it back with a note, or drop it.' : 'No proposal waits for you.') : 'The proposals could not be read.', () => { $('#dTitle').textContent = propTitle(); return propsHtml(); }, propPress,
770
- (e) => { const t = e.target.closest('[data-bdn]'); if (!t) return; PNOTE[t.dataset.bdn] = t.value; const k = $(`[data-bda="pback"][data-id="${CSS.escape(t.dataset.bdn)}"]`, $('#oMain')); if (k) k.disabled = !t.value.trim(); });
771
- $('#oLab').textContent = 'Agent proposals';
772
- };
773
-
774
- /* ── mentions ── */
775
- const taskLine = (m) => (m.reply ? 'Reply to ' + (m.who ? first(m.who) : 'the sender') + ' (' + srcName(m.source) + ') by today' : 'Read ' + (m.who ? first(m.who) : 'the sender') + '\'s note (' + srcName(m.source) + ')');
776
- function menHtml() {
777
- const a = A.men; if (!a.ok) return `<p class="nodef err" role="alert">Mentions ${esc(said(a))}</p>`;
778
- if (a.list === null) return '<p class="empty3">No brief for today, so no mentions were read.</p><p class="note">Mentions come from today\'s brief. Nothing here replies, reacts or posts in Slack, Jira, Confluence or mail.</p>';
779
- const l = shownMen(), ORD = ['slack', 'jira', 'confluence', 'mail'], srcs = ORD.filter((k) => l.some((m) => m.source === k)).concat([...new Set(l.map((m) => m.source))].filter((k) => !ORD.includes(k)));
780
- if (MTAB !== 'all' && !srcs.includes(MTAB)) MTAB = 'all';
781
- const rows = l.filter((m) => MTAB === 'all' || m.source === MTAB).sort((x, y) => (y.reply - x.reply) || ((y.at ? Date.parse(y.at) : 0) - (x.at ? Date.parse(x.at) : 0)));
782
- const tabs = `<div class="seg2" role="group" aria-label="Source">${['all', ...srcs].map((k) => `<button type="button" data-bda="mtab" data-k="${esc(k)}" aria-pressed="${MTAB === k}">${k === 'all' ? 'All ' + l.length : esc(srcName(k)) + ' ' + l.filter((m) => m.source === k).length}</button>`).join('')}</div>`;
783
- const item = (m) => {
784
- const link = bdLink(m.link), when = mWhen(m.at);
785
- const acts = m.read ? bdActs(bdBtn('Mark unread', 'munread', m.id, true))
786
- : bdActs(MADD.has(m.id) ? bdDone(true, 'In your Work list.') : bdBtn('Make it a task', 'madd', m.id), bdBtn('Mark read', 'mread', m.id, true), link ? `<a class="cta alt" href="${esc(link)}" target="_blank" rel="noopener noreferrer" data-bdlink="${esc(m.id)}">Open in ${esc(srcName(m.source))}</a>` : '')
787
- + (MADD.has(m.id) ? '' : `<p class="bd-why">Make it a task adds “${esc(taskLine(m))}” to your Work list. Mark read hides it from today's list.</p>`) + bdFail(m.id, SERR);
788
- return `<div class="bd-it${m.read ? ' decided' : ''}" data-id="${esc(m.id)}"><div class="bd-h">${bdChip(srcName(m.source) + (m.where ? ' · ' + m.where : ''))}${when ? bdChip(when, 'mono') : ''}${m.reply ? bdChip('Needs your reply', 'warn') : bdChip('For your information')}</div><span class="bd-t">${esc(m.who || srcName(m.source))}</span><p class="bd-q">${esc(m.text)}</p>${m.initiative ? `<p class="bd-why">${esc(m.initiative)}</p>` : ''}${acts}</div>`;
789
- };
790
- return (l.length ? `<div class="bd-top">${tabs}</div><div class="bd-list">${rows.map(item).join('')}</div>` : '<p class="empty3">' + CHECK + 'No one has mentioned you today.</p>')
791
- + '<p class="note">Mentions come from today\'s brief. A mention that is already a row under What you need to do is not listed here. Nothing here replies, reacts or posts in Slack, Jira, Confluence or mail.</p>';
792
- }
793
- async function menPress(e, redraw) {
794
- const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
795
- const act = b.dataset.bda, id = b.dataset.id;
796
- if (act === 'mtab') { MTAB = b.dataset.k; redraw(`[data-bda="mtab"][data-k="${CSS.escape(MTAB)}"]`); return; }
797
- const m = shownMen().find((x) => x.id === id); if (!m) return;
798
- BUSY = id; b.disabled = true; delete SERR[id];
799
- const r = act === 'madd' ? await pmPost('/api/pm-items/add', { line: taskLine(m) }) : await pmPost('/api/mentions/read', { id, read: act === 'mread' });
800
- BUSY = '';
801
- if (!r || r.ok === false) { SERR[id] = 'That did not go through' + (r && r.error ? ': ' + r.error : '.'); redraw(); return; }
802
- if (act === 'madd') { MADD.add(id); toast('Added to Work: ' + taskLine(m).replace(/ by today$/, '')); redraw(`.bd-it[data-id="${CSS.escape(id)}"] [data-bda="mread"]`); }
803
- else { MREAD.set(id, act === 'mread'); toast(act === 'mread' ? 'Marked read.' : 'Marked unread.'); redraw(`.bd-it[data-id="${CSS.escape(id)}"] button`); }
804
- drawAround();
805
- }
806
- const openMen = () => {
807
- const l = shownMen();
808
- bdDlg('men', 'Mentions · real data', 'Mentions', 'Slack, Jira, Confluence and mail · today\'s brief', A.men && A.men.ok && A.men.list ? menLine(l) + ' Make one a task, mark it read, or open it where it was said.' : 'Mentions could not be read from today\'s brief.', menHtml, menPress);
809
- };
810
-
811
- /* ── portfolio pulse ── */
812
- function pulseHtml() {
813
- const a = A.pulse; if (!a.ok) return `<p class="nodef err" role="alert">Portfolio pulse ${esc(said(a))}</p>`;
814
- const g = groups(a.rows), n = a.rows.length + a.none, item = (r) => `<div class="bd-it"><div class="bd-h">${bdChip(r.word, r.cls === 'bad' ? 'hot' : r.cls === 'warn' ? 'warn' : '')}${r.pname ? bdChip(r.pname, 'mono') : ''}</div><span class="bd-t">${esc(r.title)}</span><p class="bd-why">${esc(r.why)}</p>${bdActs(`<a class="cta alt" href="/premium-initiative.html?id=${encodeURIComponent(r.id)}${r.ws ? '&ws=' + encodeURIComponent(r.ws) : ''}">Open the initiative</a>`)}</div>`;
815
- const hot = g.bad.concat(g.warn);
816
- return `<div class="bd-leg">${['bad', 'warn', 'ok', 'none'].map((k) => `<span><i class="${k}"></i>${PGW[k]} ${k === 'none' ? g.none.length + a.none : g[k].length}</span>`).join('')}</div>${n ? bar(g, n, a.none) : ''}`
817
- + H2('Needs a look') + (hot.length ? `<div class="bd-list">${hot.map(item).join('')}</div>` : '<p class="note">Nothing is late or at risk.</p>')
818
- + `<details class="bd-more"><summary>${g.ok.length} on plan</summary><div class="bd-list">${g.ok.map(item).join('')}</div></details>`
819
- + `<details class="bd-more"><summary>${g.none.length + a.none} with no plan date</summary><div class="bd-list">${g.none.map(item).join('')}</div>${a.none ? `<p class="note">${pl(a.none, 'more initiative has', 'more initiatives have')} no promised date and no Jira read, so they are not listed.</p>` : ''}</details>`
820
- + (a.errs.length ? `<p class="note">Not read: ${esc(a.errs[0])}</p>` : '') + '<p class="note">The status is the Calendar\'s: the promised date against the forecast, or the Jira read. It is not a forecast of its own, and nothing here changes a record.</p>';
821
- }
822
- const openPulse = () => {
823
- const a = A.pulse, g = a && a.ok ? groups(a.rows) : null;
824
- bdDlg('pulse', 'Portfolio pulse · real data', 'Portfolio pulse', 'The initiatives, by the Calendar\'s own status', g ? `${g.bad.length} late and ${g.warn.length} at risk, of ${a.rows.length + a.none}. The late and at-risk ones are listed first. Opening one takes you to its page.` : 'The initiatives could not be read.', pulseHtml, () => {});
825
- };
826
-
827
- /* ── horizon scan ── */
828
- const SKIND = { create: ['New initiative', 'Approve', 'The initiative was created in the first stage of the board.'], research: ['Research', 'Start the research', 'A research scan was started.'], attach: ['Evidence', 'Approve', 'An evidence line was written.'] };
829
- const sDoes = (p) => {
830
- const f = p.fields || {};
831
- return p.kind === 'create' ? 'Approve creates the initiative in the first stage of the ' + (f.board || 'board') + ' workflow.' : p.kind === 'research' ? 'Start the research starts a research scan' + (f.question ? ' for “' + f.question + '”' : '') + '.' : 'Approve writes an evidence line on ' + (f.initiative || 'the initiative') + '.';
832
- };
833
- function scanProp(p, ws) {
834
- const d = SDEC.get(p.id), k = SKIND[p.kind] || [p.kind, 'Approve', 'It is recorded.'], f = p.fields || {};
835
- const act = d ? bdDone(d.st === 'ok', d.st === 'ok' ? 'Approved. ' + k[2] : 'Dismissed. It counts as a correction.') + (d.st === 'no' ? bdActs(bdBtn('Undo', 'sundo', p.id, true, ` data-ws="${esc(ws)}"`)) : '')
836
- : SOPEN.has(p.id) ? `<label class="bd-l" for="bds-${esc(p.id)}">Why dismiss it? A reason is required.</label><input type="text" id="bds-${esc(p.id)}" data-bds="${esc(p.id)}" maxlength="500" value="${esc(SWHY[p.id] || '')}" placeholder="For example: we already decided this">${bdFail(p.id, SERR)}`
837
- + bdActs(bdBtn('Dismiss', 'sdis', p.id, false, ` data-ws="${esc(ws)}"${(SWHY[p.id] || '').trim() ? '' : ' disabled'}`), bdBtn('Cancel', 'sdiscancel', p.id, true)) + '<p class="bd-why">A dismissal counts as a correction. The scan will not raise the same thing again.</p>'
838
- : bdActs(bdBtn(k[1], 'sapp', p.id, false, ` data-ws="${esc(ws)}"`), bdBtn('Dismiss', 'sdisopen', p.id, true)) + `<p class="bd-why">${esc(sDoes(p))} Dismiss asks for a reason and counts as a correction.</p>` + bdFail(p.id, SERR);
839
- return `<div class="bd-it${d ? ' decided' : ''}" data-id="${esc(p.id)}"><div class="bd-h">${bdChip(k[0])}${f.board ? bdChip(f.board) : ''}</div><span class="bd-t">${esc(p.title)}</span>${p.why ? `<p class="bd-why">${esc(p.why)}</p>` : ''}${p.finding ? `<p class="bd-q">${esc(p.finding)}</p>` : ''}${act}</div>`;
840
- }
841
- function scanPart(s) {
842
- const lastWord = s.last ? dayWord(s.last.at) + (s.last.ok === false ? ' (did not finish' + (s.last.reason ? ': ' + s.last.reason : '') + ')' : '') : 'No scan has run yet';
843
- const nextWord = s.switched_off ? 'Scans are switched off on this machine' : s.next ? dayWord(s.next) + (s.schedule ? ' · ' + s.schedule : '') : (s.schedule || 'Not scheduled');
844
- let ctl;
845
- if (s.open) ctl = `<div class="bd-it"><span class="bd-t">Scanning now</span><div class="bd-steps">${(s.open.steps || []).map((x) => `<div class="${esc(x.state)}"><i></i>${esc(x.label || x.id)}${x.state === 'work' ? ' …' : ''}</div>`).join('')}</div>${bdActs(bdBtn(s.open.stopping ? 'Stopping…' : 'Stop', 'sstop', s.ws, true, s.open.stopping ? ' disabled' : ''))}<p class="bd-why">Stop ends the scan. Nothing it has not filed is written.</p></div>`;
846
- else {
847
- const m = s.manual || {}, no = s.switched_off ? 'Scans are switched off on this machine.' : m.ok === false ? (m.error || 'A manual scan cannot start now.') : '';
848
- ctl = bdActs(bdBtn('Scan now', 'snow', s.ws, false, no ? ' disabled' : '')) + `<p class="bd-why">${no ? esc(no) + ' ' : ''}Scan now starts an agent that reads the public web for your watch list and this repository, then writes reports with proposals. Nothing acts until you approve it.${m.limit ? ' ' + m.left + ' of ' + m.limit + ' manual scans left today.' : ''}</p>`;
849
- }
850
- const top = s.reports.filter((r) => !r.parent && r.written), scan = s.last && s.last.scan, show = top.filter((r) => r.scan === scan || (r.proposals && r.proposals.open > 0) || [...SDEC.values()].some((d) => d.p.report === r.id));
851
- const reps = show.map((r) => {
852
- const ps = s.proposals.filter((p) => p.report === r.id), dec = [...SDEC.entries()].filter(([, d]) => d.p.report === r.id && !ps.some((p) => p.id === d.p.id)).map(([, d]) => d.p), all = ps.concat(dec);
853
- return H2(r.label || r.type + ' report') + `<p class="bd-q">${esc(r.title)}</p><p class="bd-why">From: ${esc(r.origin || 'the repository')} · ${ps.length} of ${(r.proposals && r.proposals.total) || all.length} proposals wait</p><div class="bd-list">${all.map((p) => scanProp(p, s.ws)).join('')}</div>`;
854
- }).join('');
855
- return (s.pname ? H2(s.pname) : '') + kv([['Last scan', lastWord], ['Next', nextWord]]) + ctl + (reps || (s.last ? '<p class="note">The last scan wrote no report.</p>' : ''));
856
- }
857
- function scanHtml() {
858
- const a = A.scan; if (!a.ok) return `<p class="nodef err" role="alert">Horizon scan ${esc(said(a))}</p>`;
859
- return a.scans.map(scanPart).join('') + (a.errs.length ? `<p class="note">Not read: ${esc(a.errs[0])}</p>` : '') + '<p class="note">One scan covers the whole product. The watch list, the scan setting, the report documents and Change on a proposal stay in the console.</p>';
860
- }
861
- let SPOLL = null;
862
- function scanPoll(redraw) {
863
- clearTimeout(SPOLL);
864
- if (!A.scan || !A.scan.ok || !A.scan.scans.some((s) => s.open)) return;
865
- SPOLL = setTimeout(async () => {
866
- if ($('#oMain').dataset.bd !== 'scan' || !$('#dlg').classList.contains('on')) return;
867
- const before = JSON.stringify(A.scan); await readAll(['scan']);
868
- if (JSON.stringify(A.scan) !== before) redraw();
869
- scanPoll(redraw);
870
- }, 4000);
871
- }
872
- async function scanPress(e, redraw) {
873
- const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
874
- const act = b.dataset.bda, id = b.dataset.id, ws = b.dataset.ws || '';
875
- if (act === 'sdisopen') { SOPEN.add(id); redraw(`[data-bds="${CSS.escape(id)}"]`); return; }
876
- if (act === 'sdiscancel') { SOPEN.delete(id); delete SERR[id]; redraw(`[data-bda="sdisopen"][data-id="${CSS.escape(id)}"]`); return; }
877
- const why = (SWHY[id] || '').trim();
878
- if (act === 'sdis' && !why) return;
879
- BUSY = id; b.disabled = true;
880
- let r;
881
- if (act === 'snow') r = await pmPost('/api/scan/now', { ws: id });
882
- else if (act === 'sstop') r = await pmPost('/api/scan/stop', { ws: id });
883
- else r = await pmPost('/api/scan/proposal', { ws, id, action: act === 'sapp' ? 'approve' : act === 'sdis' ? 'dismiss' : 'undo', ...(act === 'sdis' ? { why } : {}) });
884
- BUSY = '';
885
- if (!r || r.ok !== true) { SERR[id] = (r && r.error) || 'It did not go through.'; redraw(); toast(SERR[id]); return; }
886
- delete SERR[id];
887
- if (act === 'sapp' || act === 'sdis') { const p = A.scan.scans.flatMap((s) => s.proposals).find((x) => x.id === id); if (p) SDEC.set(id, { st: act === 'sapp' ? 'ok' : 'no', p }); SOPEN.delete(id); toast(act === 'sapp' ? 'Approved.' : 'Dismissed. It counts as a correction.'); }
888
- else if (act === 'sundo') { SDEC.delete(id); toast('The dismissal was taken back.'); }
889
- else toast(act === 'snow' ? 'Scan started. It runs in the background.' : 'Stopping the scan.');
890
- await readAll(['scan']); redraw(act === 'snow' ? '[data-bda="sstop"]' : act === 'sstop' ? '[data-bda="snow"]' : `.bd-it[data-id="${CSS.escape(id)}"] .bd-done`); scanPoll(redraw);
891
- }
892
- const openScan = () => {
893
- const w = scanOpen();
894
- const redraw = bdDlg('scan', 'Horizon scan · real data', 'Horizon scan', 'One scan for the whole product', A.scan && A.scan.ok ? (w ? pl(w, 'proposal waits', 'proposals wait') + ' for you. Nothing acts until you approve it.' : 'No proposal waits for you. Nothing acts until you approve it.') : 'The scan could not be read.', scanHtml, scanPress,
895
- (e) => { const t = e.target.closest('[data-bds]'); if (!t) return; SWHY[t.dataset.bds] = t.value; const k = $(`[data-bda="sdis"][data-id="${CSS.escape(t.dataset.bds)}"]`, $('#oMain')); if (k) k.disabled = !t.value.trim(); });
896
- scanPoll(redraw);
897
- };
898
-
899
- /* ── report found ── */
900
- const EVK = { mail: 'Mail', calendar: 'Calendar', slack: 'Slack', drive: 'Drive', confluence: 'Confluence' };
901
- const CONF = { likely: 'Likely', 'not-sure': 'Not sure' };
902
- function repItem(f) {
903
- const d = REC.get(f.id), id = f.id;
904
- const ev = (f.evidence || []).filter((e) => e && e.text).map((e) => bdChip((EVK[e.kind] || String(e.kind || 'Source')) + ': ' + e.text, 'mono')).join('');
905
- const act = d ? (d.st === 'set' ? bdDone(true, 'Set up' + (d.setup ? ' as ' + d.setup : '') + '. Its first cycle is drafted on this machine. Nothing was sent.') : bdDone(true, 'Marked not a report. The finder will not raise it again.'))
906
- : bdActs(bdBtn('Set up', 'rset', id, false, ` data-ws="${esc(f.ws)}"`), bdBtn('Not a report', 'rno', id, true, ` data-ws="${esc(f.ws)}"`)) + '<p class="bd-why">Set up creates the recurring report and drafts its first cycle on this machine. PMOS drafts only. Nothing is sent. Not a report: the finder will not raise it again.</p>' + bdFail(id, RERR);
907
- return `<div class="bd-it${d ? ' decided' : ''}" data-id="${esc(id)}"><div class="bd-h">${f.confidence && CONF[f.confidence] ? bdChip(CONF[f.confidence]) : ''}${f.pname ? bdChip(f.pname, 'mono') : ''}</div><span class="bd-t">${esc(f.name)}</span>${f.why ? `<p class="bd-q">${esc(f.why)}</p>` : ''}${ev ? `<p class="bd-h">${ev}</p>` : ''}${act}</div>`;
908
- }
909
- function repHtml() {
910
- const a = A.rep; if (!a.ok) return `<p class="nodef err" role="alert">Report finder ${esc(said(a))}</p>`;
911
- const L = repFound().concat([...REC.values()].map((d) => d.f).filter((f) => !repFound().some((o) => o.id === f.id && o.ws === f.ws)));
912
- return (L.length ? `<p class="bd-top">${repFound().length ? pl(repFound().length, 'report was', 'reports were') + ' found in your work.' : 'All decided.'} PMOS drafts only. Nothing is sent.</p><div class="bd-list">${L.map(repItem).join('')}</div>` : `<p class="empty3">${CHECK}No report found.</p>`)
913
- + (a.errs.length ? `<p class="note">Not read: ${esc(a.errs[0])}</p>` : '') + '<p class="note">The finder reads your calendar, Slack and the subjects of mail you sent, never message bodies. Change first, the report finder settings and every other report press stay in Insights and the console.</p>';
914
- }
915
- async function repPress(e, redraw) {
916
- const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
917
- const act = b.dataset.bda, id = b.dataset.id, ws = b.dataset.ws || '', f = repFound().find((x) => x.id === id && x.ws === ws);
918
- if (!f) return;
919
- BUSY = id; b.disabled = true;
920
- const r = act === 'rset' ? await pmPost('/api/report-setups/setup', { ws, finding: id }) : await pmPost('/api/report-setups/dismiss', { ws, finding: id, name: f.name });
921
- BUSY = '';
922
- if (!r || r.ok !== true) { RERR[id] = (r && r.error) || 'It did not go through.'; redraw(); toast(RERR[id]); return; }
923
- delete RERR[id];
924
- REC.set(id, { st: act === 'rset' ? 'set' : 'no', f, setup: act === 'rset' && r.setup ? r.setup.name || '' : '' });
925
- toast(act === 'rset' ? 'Set up. Nothing is sent.' : 'Marked not a report.');
926
- await readAll(['rep']); redraw(`.bd-it[data-id="${CSS.escape(id)}"] .bd-done`);
927
- }
928
- const openReport = () => {
929
- const n = repFound().length;
930
- bdDlg('rep', 'Report finder · real data', 'Report found', 'From your calendar, Slack and the subjects of mail you sent', A.rep && A.rep.ok ? (n ? pl(n, 'report was', 'reports were') + ' found in your work. Set it up, or say it is not a report. PMOS drafts only.' : 'No report waits for you.') : 'The findings could not be read.', repHtml, repPress);
931
- };
932
-
933
- /* ── data freshness ── */
934
- const SSTATE = { fresh: 'Recent', stale: 'Old', never: 'Never read', building: 'Reading now…', failed: 'Failed', off: 'Off' };
935
- const SNOTE = {};
936
- const limitWord = (ms) => (ms >= 48 * 3600000 ? Math.round(ms / 86400000) + ' days' : Math.round(ms / 3600000) + ' hours');
937
- function srcHtml() {
938
- const a = A.src; if (!a.ok) return `<p class="nodef err" role="alert">Data freshness ${esc(said(a))}</p>`;
939
- const b = behindSrc(), many = refreshTargets(a.sources);
940
- const row = (s) => {
941
- const when = s.id === 'repository' && s.state === 'fresh' ? 'watching' : s.as_of ? whenRead(s.as_of) : 'never';
942
- const sch = s.schedule ? [s.schedule.cadence, s.schedule.day, s.schedule.time].filter(Boolean).join(' ') : s.skill ? 'no schedule' : 'on every change';
943
- return `<div class="bd-src"><span><b>${esc(s.label)}</b><small><span class="bd-st ${esc(s.state)}">${esc(SSTATE[s.state] || s.state)}</span> · ${esc(when)} · ${esc(sch)}${s.stale_after_ms ? ' · old after ' + esc(limitWord(s.stale_after_ms)) : ''}</small><small>${s.skill ? 'Refresh starts the ' + esc(s.skill) + ' skill in an agent session, with your own connection.' : 'Refresh rebuilds the facts on this machine.'}</small>${SNOTE[s.id] ? `<small role="status">${esc(SNOTE[s.id])}</small>` : ''}</span>${bdBtn('Refresh', 'sfone', s.id, true, (s.state === 'off' || s.state === 'building' ? ' disabled' : '') + ` aria-label="Refresh ${esc(s.label)}"`)}</div>`;
944
- };
945
- return `<div class="bd-top"><p>Sources are read on a schedule, not live. ${b.length ? pl(b.length, 'source needs', 'sources need') + ' a new read.' : 'None is old.'}</p>${bdBtn('Refresh all', 'sfall', '', false, many.length ? '' : ' disabled')}</div>${a.sources.map(row).join('')}<p class="note">Refresh all reads every source, then writes the Briefing from those reads. The server calls nothing outside this machine: an outside source is read by a skill, with your own connection.</p>`;
946
- }
947
- let FPOLL = null;
948
- function srcPoll(redraw, n) {
949
- clearTimeout(FPOLL);
950
- if (!n || !A.src || !A.src.ok || !A.src.sources.some((s) => s.state === 'building')) return;
951
- FPOLL = setTimeout(async () => { if ($('#oMain').dataset.bd !== 'src' || !$('#dlg').classList.contains('on')) return; await readAll(['src']); redraw(); srcPoll(redraw, n - 1); }, 3000);
952
- }
953
- async function srcPress(e, redraw) {
954
- const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
955
- const act = b.dataset.bda, ids = act === 'sfall' ? refreshTargets(A.src.sources) : [b.dataset.id];
956
- BUSY = 'src'; b.disabled = true;
957
- if (act === 'sfall') {
958
- // briefing-source-flow slice 3: the same ordered run as the Sources popup: every source, then the Briefing from those reads
959
- const r = await pmPost('/api/sources/refresh-all', { ws: A.src.ws || wsParam() || '' });
960
- BUSY = '';
961
- toast(!r || !r.ok ? 'Refresh all did not start: ' + ((r && r.error) || 'the server did not answer') + '.' : r.joined ? 'Refresh all is already running. ' + allText(r.all) : allText(r.all));
962
- await readAll(['src']); redraw('[data-bda="sfall"]'); srcPoll(redraw, 8);
963
- return;
964
- }
965
- const got = await Promise.all(ids.map(async (id) => [id, await pmPost('/api/sources/refresh', { ws: A.src.ws || wsParam() || '', source: id })]));
966
- BUSY = '';
967
- let bad = 0;
968
- for (const [id, r] of got) { if (r && r.ok) SNOTE[id] = r.started === 'session' ? 'An agent session started to read it.' : 'Rebuilding the facts on this machine.'; else { bad++; SNOTE[id] = 'It did not start: ' + ((r && r.error) || 'the server did not answer') + '.'; } }
969
- toast(bad ? bad + ' of ' + ids.length + ' did not start.' : act === 'sfall' ? 'Reading every source again.' : 'Reading again.');
970
- await readAll(['src']); redraw(act === 'sfall' ? '[data-bda="sfall"]' : `[data-bda="sfone"][data-id="${CSS.escape(ids[0])}"]`); srcPoll(redraw, 8);
971
- }
972
- const openSrc = () => {
973
- const b = behindSrc();
974
- const redraw = bdDlg('src', 'Sources · real data', 'Data freshness', 'When each source was last read', A.src && A.src.ok ? (b.length ? joinN(b.map((s) => s.label)) + (b.length === 1 ? ' needs' : ' need') + ' a new read. Refresh one, or all.' : 'Every source was read recently.') : 'The sources could not be read.', srcHtml, srcPress);
975
- srcPoll(redraw, 8);
976
- };
977
-
978
- function mountAround() {
979
- const t = $('#todayCard'); if (!t) return;
980
- const s = document.createElement('section');
981
- s.className = 'card rise'; s.id = 'aroundCard'; s.style.setProperty('--d', '8'); s.setAttribute('aria-labelledby', 'hAround');
982
- s.innerHTML = `<div class="ch"><span class="ic">${bdIco(BDI.at)}</span><h2 id="hAround">Around you</h2><small id="aroundCap">Reading</small></div><div id="aroundBody" class="bd-rows"></div><p class="note bd-note">Nothing here posts to Slack, Jira, Confluence or mail. A button that records something says what, before you press it.</p>`;
983
- const slot = $('#prodSlot'); // Home: the product-wide signals are the list's Product group
984
- if (slot) { slot.appendChild(s); $('#hAround', s).textContent = 'Product'; } else t.insertAdjacentElement('afterend', s);
985
- s.addEventListener('click', (e) => {
986
- const b = e.target.closest('[data-bd]'); if (!b) return;
987
- ({ prop: openPropsDlg, men: openMen, pulse: openPulse, scan: openScan, rep: openReport, src: openSrc })[b.dataset.bd]();
988
- });
989
- drawAround();
990
- }
991
- mountAround();
992
-
993
- /* ── the phone moment card: what the day is doing now, above What you need to do, at 640 px and narrower ───────────────────────────────
994
- * The moment is chosen by momentOf (c3-phone-model.js) from the brief-page day and a clock. Every line below comes from /api/brief-page or /api/phone-day. */
995
- const PH = { page: null, day: null, dayAt: 0, dec: new Map(), err: {} };
996
- const phoneOn = () => matchMedia('(max-width:640px)').matches;
997
- const pHm = (iso) => { const d = new Date(iso); return STAMP(d.getHours()) + ':' + STAMP(d.getMinutes()); };
998
- const pWho = (m) => (m.people && m.people.length ? m.people.map(first).join(', ') : '');
999
- const pOwn = () => ((PH.page && PH.page.ok && PH.page.needs) || []).filter((n) => n && n.id && (n.kind === 'overdue' || n.kind === 'due-today'))
1000
- .map((n) => ({ id: n.id, headline: n.headline, label: n.kind === 'overdue' ? (n.days_late === 1 ? '1 day late' : n.days_late + ' days late') : 'Due today', kind: n.kind, looks: !!(n.evidence && n.evidence.text) }));
1001
- const pBtn = (label, act, id, alt) => `<button type="button" class="cta${alt ? ' alt' : ''}" data-pha="${act}"${id != null ? ` data-id="${esc(id)}"` : ''}>${esc(label)}</button>`;
1002
- const pItem = (n) => {
1003
- const d = PH.dec.has(n.id);
1004
- const act = d ? `<p class="bd-done" role="status">${CHECK}<span>Done.</span></p><div class="phacts">${pBtn('Undo', 'phundo', n.id, true)}</div>` : `<div class="phacts">${pBtn(n.looks ? 'Confirm done' : 'Done', 'phdone', n.id)}</div>`;
1005
- return `<div class="phfit" data-id="${esc(n.id)}"><span class="label">${esc(n.label)}</span><b class="phtt">${esc(n.headline)}</b>${act}${PH.err[n.id] ? `<p class="nodef err" role="alert">${esc(PH.err[n.id])}</p>` : ''}</div>`;
1006
- };
1007
- const pItems = (list) => list.concat([...PH.dec.values()].filter((x) => !list.some((y) => y.id === x.id))).map(pItem).join('');
1008
- const pOpen = (m) => pBtn('Open the meeting', 'phopen', m.id, true);
1009
- const pBig = (t) => `<b class="phbig">${esc(t)}</b>`;
1010
- const pL = (t) => `<p class="phl">${esc(t)}</p>`, pS = (t) => `<p class="phs">${esc(t)}</p>`;
1011
- const pDayErr = () => (PH.day && PH.day.ok === false ? pS('Today could not be read: ' + PH.day.error + '.') : !PH.day ? pS('Reading your day.') : '');
1012
- const pNum = (n, one, many) => (n === 1 ? '1 ' + one : (n || 0) + ' ' + many);
1013
- function phMoment(mo) {
1014
- const m = mo.meeting, own = pOwn(), day = PH.day && PH.day.ok !== false ? PH.day : null, fin = day ? day.finished || [] : [];
1015
- const wait = own.length ? pNum(own.length, 'item of yours waits', 'items of yours wait') + '.' : 'Nothing of yours is due.';
1016
- const finRows = (n) => fin.slice(0, n).map((t) => `<div class="phfit"><span class="label">${t.status === 'review' ? 'Waits for you' : t.status === 'sent' ? 'Sent' : 'Finished'}</span><b class="phtt">${esc(t.title)}</b><p class="phs">${esc(t.summary)}</p></div>`).join('');
1017
- if (mo.kind === 'meeting') return `<span class="label">Under way · ends ${esc(inText(mo.minutes))}</span>${pBig(m.title)}${pWho(m) ? pL(pWho(m)) : ''}<div class="phacts">${pOpen(m)}</div>`;
1018
- if (mo.kind === 'before') {
1019
- const prep = (m.prepared || []).slice(0, 3).map((x) => `<p class="phs">${esc(x.text)}</p>`).join('') || pS('Nothing is prepared for it.');
1020
- const bf = (m.before || []).filter((x) => x && x.id && !x.done).map((x) => ({ id: x.id, headline: x.title, label: 'Before you go', kind: 'before' }));
1021
- return `<span class="label">Starts ${esc(inText(mo.minutes))} · ${pHm(m.start)}</span>${pBig(m.title)}${[pWho(m), m.initiative].filter(Boolean).length ? pL([pWho(m), m.initiative].filter(Boolean).join(' · ')) : ''}${prep}${pItems(bf)}<div class="phacts">${pOpen(m)}</div>`;
1022
- }
1023
- if (mo.kind === 'after') return `<span class="label">Just ended · ${pHm(m.end || m.start)}</span>${pBig(m.title)}${pS('The notes of this meeting, if there are any, are in the meeting.')}<div class="phacts">${pOpen(m)}</div>`;
1024
- if (mo.kind === 'gap') return `<span class="label">Until ${esc(mo.next.title)} at ${pHm(mo.next.start)}</span>${pBig(mo.minutes + ' free minutes')}${mo.fits.length ? pItems(mo.fits.map((n) => own.find((o) => o.id === n.id)).filter(Boolean)) : pL('Nothing of yours is due. A good moment to prepare the next meeting.')}`;
1025
- if (mo.kind === 'morning') {
1026
- const top = own.slice(0, 3);
1027
- return `<span class="label">Your morning</span>${pBig(top.length ? ['', 'One thing', 'Two things', 'Three things'][top.length] + ' this morning' : 'Nothing pressing this morning')}${pItems(top)}${pS(wait)}${mo.next ? `<div class="phfit"><b class="phtt">First up: ${esc(mo.next.title)} at ${pHm(mo.next.start)}</b><p class="phs">${esc(inText((Date.parse(mo.next.start) - Date.now()) / 60000).replace(/^in/, 'In'))}${pWho(mo.next) ? ' · ' + esc(pWho(mo.next)) : ''}</p><div class="phacts">${pOpen(mo.next)}</div></div>` : pS('No meetings today.')}`;
1028
- }
1029
- if (mo.kind === 'work') return `<span class="label">${mo.next ? 'Next: ' + esc(mo.next.title) + ' at ' + pHm(mo.next.start) : 'No more meetings today'}</span>${pBig(fin.length ? 'Finished for you' : 'Nothing new from the agent')}${fin.length ? finRows(2) + pS('Approving a draft waits for your computer.') : pDayErr() || pS('When the agent finishes a draft today, it shows here.')}${mo.fits.length ? pItems(mo.fits.map((n) => own.find((o) => o.id === n.id)).filter(Boolean)) : ''}${mo.next ? `<div class="phacts">${pOpen(mo.next)}</div>` : ''}`;
1030
- if (mo.kind === 'recap') {
1031
- const r = day && day.recap, one = own[0];
1032
- return `<span class="label">Evening recap</span>${pBig('How today went')}${r ? `<div class="phstats"><div><b>${r.meetings || 0}</b><span>meetings</span></div><div><b>${r.decided || 0}</b><span>decided in meetings</span></div><div><b>${r.done || 0}</b><span>done by you</span></div></div>${(r.moved || []).length ? `<div class="phfit"><b class="phtt">What moved</b>${r.moved.map((x) => `<p class="phs">${esc(x.text)}${x.sub ? ' · ' + esc(x.sub) : ''}</p>`).join('')}</div>` : ''}` : pDayErr()}<div class="phfit"><b class="phtt">Still open · ${own.length}</b>${own.slice(0, 3).map((x) => pS(x.headline)).join('')}${pS(own.length ? "They come first on tomorrow's Briefing." : 'Nothing of yours is still open.')}</div>${one ? `<div class="phfit"><span class="label">One thing tonight, if you have a minute</span>${pItems([one])}</div>` : ''}`;
1033
- }
1034
- const r = day && day.recap, tm = day && day.tomorrow;
1035
- return `<span class="label">End of day</span>${pBig(tm ? 'Tomorrow, ' + tm.label : 'Tomorrow, at a glance')}${r ? pL('Today: ' + [pNum(r.meetings, 'meeting', 'meetings'), pNum(r.decided, 'decision', 'decisions'), pNum(r.done, 'item done', 'items done')].join(', ') + '.') : ''}${tm ? `<div class="phfit"><b class="phtt">${tm.meetings.length ? pNum(tm.meetings.length, 'meeting', 'meetings') : 'No meetings'}</b>${tm.meetings.slice(0, 5).map((x) => `<p class="phs">${pHm(x.start)} · ${esc(x.title)}${pWho(x) ? ' · ' + esc(pWho(x)) : ''}</p>`).join('')}</div>` : pDayErr()}${pS(own.length ? pNum(own.length, 'item carries', 'items carry') + " over. They open first on tomorrow's Briefing." : 'Nothing carries over.')}`;
1036
- }
1037
- function drawPhone(focus) {
1038
- const c = $('#phoneCard'); if (!c) return;
1039
- c.hidden = !phoneOn(); if (c.hidden) return;
1040
- if (!PH.page) c.innerHTML = '<span class="label">Now</span><p class="phl">Reading your day.</p>';
1041
- else if (!PH.page.ok) c.innerHTML = `<span class="label">Now</span><p class="nodef err" role="alert">Your day ${esc(said(PH.page))}</p>`;
1042
- else { const mo = momentOf({ today: PH.page.today || [], needs: pOwn(), now: new Date() }); c.dataset.moment = mo.kind; c.innerHTML = phMoment(mo); }
1043
- if (focus) { const f = $(focus, c); if (f) f.focus(); }
1044
- }
1045
- async function readPhone(force) {
1046
- if (!phoneOn()) { drawPhone(); return; }
1047
- PH.page = await briefPage(force);
1048
- const mo = PH.page.ok ? momentOf({ today: PH.page.today || [], needs: pOwn(), now: new Date() }) : null;
1049
- if (mo && ['work', 'recap', 'night'].includes(mo.kind) && (force || !PH.day || Date.now() - PH.dayAt > 300000)) { PH.day = await getj('/api/phone-day'); PH.dayAt = Date.now(); }
1050
- drawPhone();
1051
- }
1052
- async function phonePress(e) {
1053
- const b = e.target.closest('[data-pha]'); if (!b || BUSY) return;
1054
- const act = b.dataset.pha, id = b.dataset.id;
1055
- if (act === 'phopen') {
1056
- const m = ((PH.page && PH.page.today) || []).find((x) => x.id === id); if (!m) return;
1057
- if (!(await week.openToday({ at: Date.parse(m.start), title: m.title }))) toast('The calendar PMOS holds does not list that meeting, so it could not be opened.');
1058
- return;
1059
- }
1060
- const n = pOwn().find((x) => x.id === id) || (PH.dec.get(id)) || (((PH.page && PH.page.today) || []).flatMap((x) => x.before || []).map((x) => ({ id: x.id, headline: x.title, label: 'Before you go', kind: 'before' })).find((x) => x.id === id));
1061
- if (!n) return;
1062
- BUSY = id; b.disabled = true; delete PH.err[id];
1063
- const r = await pmPost(act === 'phdone' ? '/api/pm-items/done' : '/api/pm-items/reopen', { id });
1064
- BUSY = '';
1065
- if (!r || r.ok === false) { PH.err[id] = 'That did not go through' + (r && r.error ? ': ' + r.error : '.'); drawPhone(`.phfit[data-id="${CSS.escape(id)}"] button`); return; }
1066
- if (act === 'phdone') { PH.dec.set(id, n); toast('Done: ' + n.headline); } else { PH.dec.delete(id); toast('Reopened: ' + n.headline); }
1067
- drawPhone(`.phfit[data-id="${CSS.escape(id)}"] button`);
1068
- await readPhone(true); drawPhone(`.phfit[data-id="${CSS.escape(id)}"] button`);
1069
- }
1070
- function mountPhone() {
1071
- const anchor = $('#hMoves') && $('#hMoves').closest('.cols2'); if (!anchor) return;
1072
- const s = document.createElement('section');
1073
- s.className = 'card rise phm'; s.id = 'phoneCard'; s.hidden = true; s.setAttribute('aria-label', 'Now'); s.style.setProperty('--d', '5');
1074
- anchor.insertAdjacentElement('beforebegin', s);
1075
- s.addEventListener('click', phonePress);
1076
- const mq = matchMedia('(max-width:640px)'), again = () => { if (!document.hidden) readPhone(); };
1077
- (mq.addEventListener ? mq.addEventListener('change', again) : mq.addListener(again));
1078
- document.addEventListener('visibilitychange', again);
1079
- setInterval(() => { if (!document.hidden && phoneOn()) { PH.page && PH.page.ok ? drawPhone() : null; readPhone(true); } }, 60000);
1080
- readPhone();
1081
- }
1082
- mountPhone();
1083
-
1084
- /* ── load ───────────────────────────────────────────────────────────────────────────────────────────────── */
1085
- let readTimer = null, AROUND = false;
1086
- const ago = (ms) => { const m = Math.round(ms / 60000); return m < 1 ? 'just now' : m < 90 ? m + ' min ago' : Math.round(m / 60) + ' h ago'; };
1087
- async function load() {
1088
- let r = null, status = 0;
1089
- const ws = new URLSearchParams(location.search).get('ws');
1090
- try { const res = await fetch('/api/briefing-premium' + (ws ? '?ws=' + encodeURIComponent(ws) : ''), { credentials: 'same-origin' }); status = res.status; r = await res.json(); } catch { r = null; }
1091
- clearInterval(readTimer);
1092
- pvFeed(CL && r && r.ok ? { ok: true, model: { list: LIST() } } : r); // the bell counts what the list shows: the console's Needs you once it is read
1093
- if (r && r.state === 'reading') {
1094
- // the first read has no end I can promise: say how long it has run, and ask again
1095
- const t0 = Date.now() - (r.elapsed_ms || 0), tick = () => { $('#brief').textContent = 'Reading the products for the first time. ' + Math.round((Date.now() - t0) / 1000) + ' s so far. This page shows nothing until it has read, rather than guess.'; };
1096
- tick(); readTimer = setInterval(tick, 1000); setTimeout(load, 3000);
1097
- return;
1098
- }
1099
- if (!r || !r.ok) {
1100
- $('#snap').textContent = 'The repository could not be read';
1101
- $('#brief').textContent = 'The Briefing could not read the repository, so it shows nothing rather than guess.' + (r && r.error ? ' The reason: ' + r.error : status ? ' (the server answered ' + status + ')' : ' The server did not answer.');
1102
- return;
1103
- }
1104
- M = r.model; drawHero(); drawRows(); drawChips(); drawTl(); readPrep(); drawDock(); drawPick(); onScroll();
1105
- if (!AROUND) { AROUND = true; readAll().then(() => { openAroundParam(); openOpenParam(); }); setInterval(() => { if (!document.hidden && (!$('#dlg').classList.contains('on') || document.body.classList.contains('cz-dock'))) readAll(); }, 300000); }
1106
- const age = Date.now() - r.as_of;
1107
- if (age > 5 * 60000) $('#snap').textContent += ' · read ' + ago(age) + (r.refreshing ? ', refreshing' : '');
1108
- if (r.error) $('#snap').textContent += ' · the latest read failed: ' + r.error.slice(0, 120);
1109
- if (r.error && !r.pending) setTimeout(load, 150000);
1110
- else if (r.pending) setTimeout(load, 3000);
1111
- else if (r.refreshing) setTimeout(load, 10000);
1112
- }
1113
- /* ── the Briefing's part of Sources (initiative premium-topbar): the products it reads, what it could not read and why, and Refresh all
1114
- * also reads the included repositories again. The product picker is the header's own control, lent to the dialog while it is open. ── */
1115
- const RDST = { read: ['ok', 'Read'], 'not-read': ['warn', 'Not read'], 'not-included': ['', 'Not included'], off: ['', 'Off'] };
1116
- function sourcesHtml() {
1117
- const L = (M && M.header && M.header.sources) || [];
1118
- const rows = !L.length ? '<p class="note">The Briefing has not read anything yet.</p>'
1119
- : L.map((x) => { const [c, w] = RDST[x.state] || ['', x.state]; return `<div class="sr"><span class="sn"><b><i class="sdot ${c}" aria-hidden="true"></i>${esc(x.name)}</b><em>${esc(w)}${x.reason ? ' · ' + esc(x.reason) : ''}</em></span></div>`; }).join('');
1120
- return `<div class="srgrp"><span class="label">This Briefing was built from</span>${rows}</div><div id="pkSlot"></div>`;
1121
- }
1122
- async function refreshRepos() {
1123
- const ws = new URLSearchParams(location.search).get('ws');
1124
- const r = await pmPost('/api/briefing-premium/refresh' + (ws ? '?ws=' + encodeURIComponent(ws) : ''), {});
1125
- if (!r || !r.ok) return 'The repositories were not read again: ' + ((r && r.error) || 'the server did not answer') + '.';
1126
- clearTimeout(RTIMER); RTIMER = setTimeout(load, 4000);
1127
- return r.started && r.started.length ? 'Reading again: ' + r.started.join(', ') + '.' : r.already && r.already.length ? 'Already reading ' + r.already.join(', ') + '.' : 'No repository is included.';
1128
- }
1129
- let RTIMER = null;
1130
- $('#pkw').dataset.park = 'pkPark';
1131
- sourcesHook({ html: sourcesHtml, mount: () => { const slot = $('#pkSlot'), w = $('#pkw'); if (slot && w) slot.appendChild(w); }, refresh: refreshRepos });
1132
- window.addEventListener('pm:refreshed', () => load()); // Refresh all ended: the Briefing it wrote is read again (briefing-source-flow, slice 3)
1133
- /* briefing-source-flow, slice 5: each card says which reads it shows and when they were read, and the hero says the step of a Refresh all
1134
- * that is going. Both come from the one Sources read (premium-shell.js), so a card and Sources cannot disagree. */
1135
- function drawReads() {
1136
- const put = (sel, ids) => { const c = $(sel); if (!c) return; let p = c.querySelector(':scope > .cread'); if (!p) { p = document.createElement('p'); p.className = 'cread'; c.appendChild(p); } p.innerHTML = readLine(ids); p.hidden = !p.innerHTML; };
1137
- put('#movesCard', ['initiatives', 'my-work', 'd:brief']);
1138
- put('#todayCard', ['calendar']);
1139
- const s = sourcesNow(), a = s && s.ok ? s.all : null, line = $('#rfLine');
1140
- if (line) { const on = !!(a && !a.done); line.hidden = !on; line.textContent = on ? allText(a) : ''; }
1141
- }
1142
- window.addEventListener('pm:sources', drawReads);
1143
- chatAbout('src:this-page', 'the Briefing');
1144
- $('#brief').textContent = 'Reading the repository.';
1145
- load();
1146
- mountFirst(); // the "Your first Briefing" card, only when the page was opened with first=<import id> (initiative premium-welcome)