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
@@ -0,0 +1,1179 @@
1
+ /* pm/home-app.js — Home in the Agreed design (initiative premium-agreed-design, Home; mockup Main.dc.html place="work": AgHome, AgHomePhone,
2
+ * AgInit*, AgProduct, AgChat*), with the one list of the Uncovered features canvas (initiative premium-uncovered-features, H1 and H2:
3
+ * HmMyWork, HmReview, HmProducts, HmMic, HmDay, HmDecide, HmPhone, HmPhone2).
4
+ *
5
+ * One desk. The list on the left is one list grouped by product (home-list.js builds it, home-today.js draws it): the Today card through
6
+ * the day, the filters (Today, Waiting, Kept, Done), each product's group with its initiatives (yours first, marked "your turn") and their
7
+ * tasks, next steps, sessions and meetings under them, then "Not in an initiative", the capture box and the untouched work. There is no
8
+ * Needs you group and no Your list. An initiative is a layout of this page (?ini=<id>): its card sits at the top of the list with its own
9
+ * groups and the Elsewhere card under it. The chat is in the middle (home-chat.js) and the Viewer on the right (cozy-viewer.js): a task opens
10
+ * there (home-task.js), and so does the weekly review (home-review.js). On a phone the list is the page; a row opens its conversation over
11
+ * it, with a back bar.
12
+ *
13
+ * The models are in home-data.js and home-list.js (pure). This file reads the routes, draws, and wires the presses. Every write is the PM's
14
+ * press (pmPost). Nothing here opens the old dialog or links to the console. */
15
+ import { mountNav } from './cozy-nav.js';
16
+ import * as VW from './cozy-viewer.js';
17
+ import { pmGet, pmPost, pmHeaders } from './http.js';
18
+ import * as H from './home-data.js';
19
+ import { mountChat, avHtml } from './home-chat.js';
20
+ import * as MORE from './home-more.js';
21
+ import { headModel, STEPS } from './premium-initiative-head.js';
22
+ import { startAgent } from './page-agent.js';
23
+ import { mdHtml } from './chat-md.js';
24
+ import { mountPhoneCard } from './home-phone-card.js';
25
+ import { mountFirst } from './premium-first.js';
26
+ import * as L from './home-list.js';
27
+ import * as TD from './home-today.js';
28
+ import { canDictate, dictate } from './home-dictate.js';
29
+ import { mountIni, iniList, iniOverview } from './home-ini.js'; // the initiative's stage move, Tasks and Core documents (premium-uncovered-features)
30
+
31
+ const $ = (s, r = document) => r.querySelector(s);
32
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
33
+ const P = new URLSearchParams(location.search);
34
+ const WS = P.get('ws') || '';
35
+ let PHC = null; // the phone moment card (home-phone-card.js): the top of the phone's sheet
36
+ const FST = mountFirst(); // the first-run card after an import (?first=<import id>, premium-first.js): the top of the list
37
+ const wsQ = (pre = '?') => (WS ? pre + 'ws=' + encodeURIComponent(WS) : '');
38
+ const BOARD = P.get('board') || ''; // the Board's expand link names its board: Home reads that board, not the default one
39
+ const boardQ = (pre = '?') => (BOARD ? pre + 'board=' + encodeURIComponent(BOARD) : '');
40
+ const PHONE = 760;
41
+ const isPhone = () => innerWidth <= PHONE;
42
+ const SVG = (d, w = 16, sw = 1.8) => `<svg aria-hidden="true" width="${w}" height="${w}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${sw}" stroke-linecap="round" stroke-linejoin="round"><path d="${d}"/></svg>`;
43
+ const I = {
44
+ plus: 'M12 5v14M5 12h14', fold: 'M4 5h16v14H4zM9 5v14', chev: 'M9 6l6 6-6 6', down: 'M6 9l6 6 6-6', x: 'M6 6l12 12M18 6L6 18',
45
+ clock: 'M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18M12 7v5l3 2', flag: 'M5 21V4M5 4h12l-2 4 2 4H5', check: 'M5 12l4.5 4.5L19 7',
46
+ chart: 'M4 20V10M10 20V4M16 20v-8M22 20H2', gate: 'M12 3l7 3v5c0 4.5-3 8.5-7 10-4-1.5-7-5.5-7-10V6zM9 12l2 2 4-4', warn: 'M12 3l9 16H3zM12 10v4M12 17h.01',
47
+ doc: 'M7 3h7l5 5v13H7zM14 3v5h5', chat: 'M4 5h16v11H9l-5 4z', person: 'M12 12a4 4 0 1 0 0-8a4 4 0 1 0 0 8M4 21a8 8 0 0 1 16 0',
48
+ routine: 'M4 12a8 8 0 0 1 14-5.3M20 4v4h-4M20 12a8 8 0 0 1-14 5.3M4 20v-4h4', home: 'M4 11l8-7 8 7v9h-5v-6h-6v6H4z', mail: 'M3 6h18v12H3zM3 7l9 6 9-6',
49
+ };
50
+ const ROW_ICON = { gate: I.gate, warn: I.warn, clock: I.clock, doc: I.doc, chat: I.chat, goal: I.flag, product: I.chart, routine: I.routine, person: I.person };
51
+ const COMMS = { key: 'comms', name: 'Communicator', initial: 'Co' };
52
+ const CLAUDE = { key: 'claude', name: 'Claude', initial: 'C' };
53
+ const RET_REASONS = ['wrong facts', 'wrong scope', 'not now', 'too long'];
54
+ const RET_LABEL = { 'wrong facts': 'Facts are wrong', 'wrong scope': 'Wrong scope', 'not now': 'Not needed now', 'too long': 'Too long' };
55
+ const store = {
56
+ get(k) { try { return localStorage.getItem(k); } catch { return null; } },
57
+ set(k, v) { try { if (v == null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* a private window */ } },
58
+ };
59
+
60
+ /* ── theme ── */
61
+ (function theme() {
62
+ const t = P.get('theme') || store.get('pmos.c3.theme');
63
+ const dark = t === 'dark' || (t !== 'light' && matchMedia && matchMedia('(prefers-color-scheme: dark)').matches);
64
+ document.documentElement.dataset.theme = dark ? 'dark' : 'light';
65
+ if (P.get('theme')) store.set('pmos.c3.theme', P.get('theme'));
66
+ }());
67
+
68
+ /* ── state ── */
69
+ const S = {
70
+ D: { now: Date.now(), sessions: [], err: [], files: [] }, ready: false,
71
+ ini: P.get('ini') || null, // the initiative layout ('product' for the product)
72
+ sel: null, // the selected row's id
73
+ allNeeds: false, kids: new Set(), shut: new Set(JSON.parse(store.get('pmos.home.shut') || '[]')), folded: store.get('pmos.home.fold') === '1',
74
+ IM: null, IMid: null, // the selected initiative's model (GET /api/initiative-premium)
75
+ doneOpen: false, sheet: false, rec: {}, pin: new Set(JSON.parse(store.get('pmos.home.pin') || '[]')),
76
+ cardFold: store.get('pmos.home.cardfold') === '1', // the card's checklist folded to one line (AgInitSpec), kept in this browser
77
+ // the one list (premium-uncovered-features): the filter, the picked product, which groups and initiatives are open, kept in this browser
78
+ filter: 'today', product: store.get('pmos.home.product') || null, kidsOff: new Set(), rest: new Set(),
79
+ pg: (() => { try { return JSON.parse(store.get('pmos.home.pg') || '{}') || {}; } catch { return {}; } })(),
80
+ eodHidden: store.get('pmos.home.eod') === L.dayOf(), phoneChat: false,
81
+ };
82
+ const toast = (t) => { const el = $('#toast'); el.textContent = t; el.classList.add('on'); clearTimeout(toast.t); toast.t = setTimeout(() => el.classList.remove('on'), 4200); };
83
+
84
+ /* ── reading ── */
85
+ async function getRetry(path, tries = 20) {
86
+ for (let i = 0; i < tries; i++) {
87
+ const r = await pmGet(path);
88
+ if (!(r && (r.state === 'reading' || r.status === 202 || r.pending && !r.model))) return r;
89
+ await new Promise((ok) => setTimeout(ok, 2500));
90
+ }
91
+ return { ok: false, error: 'still reading' };
92
+ }
93
+ async function load() {
94
+ const [brief, board, ses, desk, today, sch, work, day, rev] = await Promise.all([
95
+ getRetry('/api/briefing-premium' + wsQ()), getRetry('/api/board-premium' + wsQ() + boardQ(WS ? '&' : '?')), pmGet('/api/sessions'), pmGet('/api/home-desk' + wsQ()),
96
+ pmGet('/api/brief-page' + wsQ()), pmGet('/api/schedules' + wsQ()), pmGet('/api/my-work-premium' + wsQ()), pmGet('/api/phone-day'), pmGet('/api/home-review' + wsQ()),
97
+ ]);
98
+ const D = S.D;
99
+ D.brief = brief && brief.ok && brief.model ? brief.model : null;
100
+ D.board = board && board.ok && board.model ? board.model : null;
101
+ D.sessions = ses && Array.isArray(ses.sessions) ? ses.sessions : [];
102
+ D.desk = desk && desk.ok ? desk : null;
103
+ D.today = today && today.ok ? today : null;
104
+ D.schedules = sch && Array.isArray(sch.schedules) ? sch : null;
105
+ D.work = work && work.ok && work.model ? work.model : null; // the PM's own list (GET /api/my-work-premium): the filters and "Not in an initiative"
106
+ D.phoneDay = day && day.ok ? day : null; // what finished today, the recap and tomorrow (the end-of-day card, the Done filter)
107
+ D.review = rev && rev.ok ? rev : null; // this week's review (GET /api/home-review)
108
+ D.now = Date.now();
109
+ D.err = [brief, board].filter((x) => !x || !x.ok).map((x) => (x && x.error) || 'the server did not answer');
110
+ const rows = H.boardRows(D);
111
+ if (rows.length) {
112
+ const b = (D.board && D.board.board) || {};
113
+ const tr = await pmGet('/api/board-trail?ids=' + encodeURIComponent(rows.slice(0, 150).map((r) => r.id).join(',')) + (b.ws ? '&ws=' + encodeURIComponent(b.ws) : wsQ('&')) + (b.id ? '&board=' + encodeURIComponent(b.id) : boardQ('&')));
114
+ D.trail = tr && tr.ok ? tr : null;
115
+ }
116
+ // the PMOS tasks of the board, so each sits under its initiative
117
+ const b0 = (D.board && D.board.board) || {};
118
+ const items = b0.id ? await pmGet('/api/boards/items?ws=' + encodeURIComponent(b0.ws || WS || '') + '&board=' + encodeURIComponent(b0.id)) : null;
119
+ D.items = items && items.ok ? items : null;
120
+ D.others = D.others || [];
121
+ S.ready = true;
122
+ await loadIni();
123
+ draw();
124
+ // the boards of the other products Home reads, each its own closed group: read after the list is drawn, so a slow one never holds it up
125
+ const others = await Promise.all(otherProducts(D).map((a) => getRetry('/api/board-premium?ws=' + encodeURIComponent(a.ws), 4).then((r) => (r && r.ok && r.model ? { ws: a.ws, name: a.name, model: r.model } : null))));
126
+ const got = others.filter(Boolean);
127
+ if (got.length || D.others.length) { D.others = got; drawList(); }
128
+ }
129
+ /** The products Home reads (Products, on) other than the board's own: each is a group of the list, read from its own board. At most four. */
130
+ function otherProducts(D) {
131
+ const av = (D.brief && D.brief.products && D.brief.products.available) || [];
132
+ const own = ((D.board && D.board.board) || {}).ws || WS;
133
+ return av.filter((a) => a.on && a.ws && a.ws !== own).slice(0, 4);
134
+ }
135
+ async function loadIni() {
136
+ const id = S.ini;
137
+ if (!id || id === 'product') { S.IM = null; S.IMid = id; S.D.files = []; return; }
138
+ const b = (S.D.board && S.D.board.board) || {};
139
+ const r = await getRetry('/api/initiative-premium?id=' + encodeURIComponent(id) + (b.ws ? '&ws=' + encodeURIComponent(b.ws) : wsQ('&')) + (b.id ? '&board=' + encodeURIComponent(b.id) : boardQ('&')), 16);
140
+ S.IM = r && r.ok && r.model ? r.model : null; S.IMid = id;
141
+ if (S.IM) { import('./premium-vw-jira.js').catch(() => {}); import('./premium-vw-item.js').catch(() => {}); } // the Overview's ticket, sprint and record views, ready before a press
142
+ S.D.files = S.IM ? (S.IM.docs.rows || []).filter((d) => d.path).map((d) => ({ name: d.title, path: d.path, meta: [d.state, d.when].filter(Boolean).join(' · ') })) : [];
143
+ }
144
+ let pollT = null;
145
+ function poll() {
146
+ clearTimeout(pollT);
147
+ pollT = setTimeout(async () => {
148
+ if (!document.hidden) {
149
+ const [ses, desk] = await Promise.all([pmGet('/api/sessions'), pmGet('/api/home-desk' + wsQ())]);
150
+ if (ses && Array.isArray(ses.sessions)) S.D.sessions = ses.sessions;
151
+ if (desk && desk.ok) S.D.desk = desk;
152
+ S.D.now = Date.now();
153
+ drawList(); drawTop();
154
+ }
155
+ poll();
156
+ }, 8000);
157
+ }
158
+ setInterval(() => { if (!document.hidden) load(); }, 300000);
159
+ window.addEventListener('hm:reload', () => load());
160
+
161
+ /* ── the list ── */
162
+ const dotCls = (st) => ({ needs: 'you', blocked: 'late', working: 'ok run' }[st] || 'none');
163
+ function tileHtml(r) {
164
+ if (r.kind === 'session' || r.kind === 'person') return avHtml(r.role || { initial: r.initial || 'C' }, 30, 'hm-tile');
165
+ if (r.kind === 'update') return `<span class="hm-tile">${SVG(I.doc, 14)}</span>`;
166
+ return `<span class="hm-tile">${SVG(ROW_ICON[r.icon] || I.chat, 14)}</span>`;
167
+ }
168
+ function rowHtml(r, o = {}) {
169
+ const sel = S.sel === r.id;
170
+ const end = r.kind === 'session' && r.sid ? `<button type="button" class="hm-x" data-hm-end="${esc(r.id)}" aria-label="End ${esc(r.name)}" title="End this session">${SVG(I.x, 14, 2)}</button>`
171
+ : r.kind === 'need' && r.row ? `<button type="button" class="hm-x" data-hm-end="${esc(r.id)}" aria-label="Put off ${esc(r.name)} until tomorrow" title="Put off until tomorrow">${SVG(I.x, 14, 2)}</button>` : '';
172
+ const chip = r.chip ? `<button type="button" class="hm-kc${r.chip.loud ? ' loud' : ''}" data-hm-kids="${esc(r.id)}" aria-expanded="${S.kids.has(r.id)}" aria-label="${esc(r.chip.text)} in ${esc(r.name)}. Show">${esc(r.chip.text)}${SVG(S.kids.has(r.id) ? I.down : I.chev, 12, 2.2)}</button>` : '';
173
+ const kids = r.kids && S.kids.has(r.id) ? `<div class="hm-kids" role="group" aria-label="In ${esc(r.name)}">${r.kids.map((k) => rowHtml(k, { kid: true })).join('') || '<p class="hm-none">Nothing here now.</p>'}</div>` : '';
174
+ return `<div class="hm-r${sel ? ' sel' : ''}${o.kid ? ' kid' : ''} st-${esc(r.state)}" data-id="${esc(r.id)}">`
175
+ + `<button type="button" class="hm-rm" data-hm-sel="${esc(r.id)}"${sel ? ' aria-current="true"' : ''}><i class="hm-dot ${dotCls(r.state)}" aria-hidden="true"></i>${tileHtml(r)}`
176
+ + `<span class="hm-rt"><b>${esc(r.name)}</b><em>${esc(r.hint || '')}</em></span></button>${chip}${end}</div>${kids}`;
177
+ }
178
+ function groupHtml(key, title, rows, extra = '', head = '') {
179
+ const shut = S.shut.has(key);
180
+ return `<section class="hm-g" aria-label="${esc(title)}"><div class="hm-ghr"><button type="button" class="hm-gh" data-hm-group="${esc(key)}" aria-expanded="${!shut}">${SVG(shut ? I.chev : I.down, 12, 2.2)}<span>${esc(title)}</span></button>${head}</div>`
181
+ + (shut ? '' : rows.map((r) => rowHtml(r)).join('') + extra) + '</section>';
182
+ }
183
+ /* ── the one list (premium-uncovered-features: HmMyWork, HmProducts, HmDay, HmMic, HmReview, HmPhone) ── */
184
+ const NOW = () => S.D.now || Date.now();
185
+ function recOf() { // a recording that is on and is no calendar meeting: the Today card shows it (HmMic)
186
+ const r = recLive(); if (!r) return null;
187
+ const n = REC && REC.note ? REC.note(r.id) : null;
188
+ const meeting = !!(n && (n.meeting || n.event || n.calendar));
189
+ return { id: r.id, title: r.title || (n && n.title) || '', at: (REC && REC.started && REC.started()) || (n && (n.started || n.created)) || null, paused: !!(n && n.state === 'paused'), meeting };
190
+ }
191
+ function todayModel() {
192
+ const T = L.todayCard(S.D, { now: NOW(), rec: recOf(), hidden: S.eodHidden, titleOf: (id) => iniTitle(id) });
193
+ const R = L.reviewModel(S.D, NOW());
194
+ if (T.mode === 'day' && R.open && R.started) {
195
+ const left = R.steps.filter((x) => !x.done).length;
196
+ return { mode: 'review', big: 'Friday. Your weekly review is open.', sub: 'Step ' + (R.at + 1) + ' of 4 · about ' + left * 3 + ' minutes left' };
197
+ }
198
+ return T;
199
+ }
200
+ function homeListHtml() {
201
+ const M = L.homeList(S.D, { now: NOW(), filter: S.filter, product: S.product && L.productsOf(S.D).some((p) => p.key === S.product) ? S.product : null });
202
+ S.M = M;
203
+ const R = L.reviewModel(S.D, NOW());
204
+ // the first initiative where it is your turn shows what is under it, until the PM closes it
205
+ const firstTurn = M.groups.filter((g) => g.kind === 'product').flatMap((g) => g.inis).find((x) => x.turn);
206
+ const open = (id) => S.kids.has(id) || (!!firstTurn && firstTurn.id === id && !S.kidsOff.has(id));
207
+ const pOpen = (g) => (g.key in S.pg ? !!S.pg[g.key] : g.primary || M.products.length === 1 || (!!S.product && S.product === g.product.key));
208
+ const nPick = M.products.length > 1 ? M.counts.products + ' products · ' + M.counts.initiatives + ' initiatives' : '';
209
+ const pins = H.needsOf(S.D).filter((r) => S.pin.has(r.key)).length;
210
+ return TD.listHtml(M, todayModel(), {
211
+ sel: S.sel, isOpen: open, pOpen, restOpen: (k) => S.rest.has(k), pin: S.pin, avHtml, ready: S.ready, err: S.D.err.length ? S.D.err[0] : '',
212
+ product: S.product, review: R, mic: canDictate(), sub: pins ? pins + ' pinned' : nPick || 'Each one sits under its initiative',
213
+ });
214
+ }
215
+
216
+ /* ── the initiative card ── */
217
+ function iniRowOf(id) { return H.boardRows(S.D).find((r) => r.id === id) || null; }
218
+ function headOf(id) {
219
+ const M = S.IM && S.IMid === id ? { ...S.IM } : { head: { stage: (iniRowOf(id) || {}).stage }, acts: (iniRowOf(id) || {}).acts || {} };
220
+ const t = S.D.trail && S.D.trail.items && S.D.trail.items[id];
221
+ const k = String((M.head && M.head.stage) || (iniRowOf(id) || {}).stage || '').toLowerCase();
222
+ const u = S.D.trail && S.D.trail.usual && S.D.trail.usual[k];
223
+ if (t && t.since) M.stageSince = t.since;
224
+ if (u && u.n >= 3 && u.days != null) M.usualDays = u.days;
225
+ const h = headModel(M, S.D.now);
226
+ // the Needs-you rows of this initiative make it the PM's turn too
227
+ const need = H.needsOf(S.D).find((r) => r.ini === id);
228
+ if (need && h.turn !== 'you') { h.turn = 'you'; h.turnLabel = 'Your turn'; h.rest.push({ kind: 'you', label: need.name }); h.cta = 'Open: ' + need.name; h.need = need; h.primary = true; }
229
+ if (!need && S.D.sessions.some((s) => H.iniOfSession(s) === id && s.shown === 'working') && h.turn === 'agents') h.primary = false;
230
+ return h;
231
+ }
232
+ /* An item's mark (AgInitAgents, AgInitStalled): done ✓, the PM's ring, the working agent's avatar, an empty grey circle for a step that is
233
+ * next, ! for a risk, J for Jira. Its tag: You; Working (a plain word), or Stuck (an outlined pill) when the initiative is stalled; Next. */
234
+ const markHtml = (k, role) => (k === 'done' ? `<span class="hm-mk done" aria-hidden="true">${SVG(I.check, 12, 3)}</span>` : k === 'risk' ? '<span class="hm-mk risk" aria-hidden="true">!</span>' : k === 'jira' ? '<span class="hm-mk jira" aria-hidden="true">J</span>'
235
+ : k === 'agent' && role ? avHtml(role, 20, 'hm-mk-av') : `<span class="hm-mk ${esc(k)}" aria-hidden="true"></span>`);
236
+ const TAG = { you: 'You', agent: 'Working', wait: 'Next', jira: 'Jira', risk: 'At risk' };
237
+ const itemHtml = (x, o = {}) => {
238
+ const k = x.kind === 'agent' && !o.role && !o.stalled ? 'wait' : x.kind; // an agent step with no agent at work on it waits: it is next
239
+ const tag = k === 'agent' && o.stalled ? 'Stuck' : TAG[k];
240
+ return `<div class="hm-it ${esc(k)}"${x.note ? ` title="${esc(x.note)}"` : ''}>${markHtml(k, o.role)}<span class="l">${esc(x.label)}</span>${k !== 'done' && tag ? `<span class="tag ${esc(k)}${tag === 'Stuck' ? ' stuck' : ''}">${tag}</span>` : ''}</div>`;
241
+ };
242
+ const MS = '<i class="cz-ms" aria-hidden="true"></i>'; // the milestone mark (◆), drawn as a shape
243
+ const msStep = (label) => !!(STEPS.find((s) => s.label === label) || {}).ms;
244
+ /** "To reach ◆ Deliver": the milestone mark before a milestone's name in the checklist's title. */
245
+ const ckTitle = (t, ms) => { const m = ms && /^(To reach |To finish )(.+)$/.exec(String(t || '')); return m ? esc(m[1]) + MS + esc(m[2]) : esc(t); };
246
+ function cardHtml(id) {
247
+ const prod = id === 'product';
248
+ let kind, title, turn, turnLabel, stage, lad = '', bars = '', ckh, items, then, time, cta, primary, over = false, foldSum = '', msNext = false;
249
+ if (prod) {
250
+ const C = H.productCard(S.D, S.D.now);
251
+ kind = C.kind; title = C.name; turn = C.turn === 'you' ? 'you' : 'agents'; turnLabel = C.turn === 'you' ? 'Your turn' : 'Sent this week';
252
+ stage = C.stage; ckh = [C.title, C.of];
253
+ items = C.items.map((x) => itemHtml({ kind: x.kind === 'ok' ? 'done' : 'risk', label: x.label })).join('') || '<p class="hm-none">No KR or budget is anchored on this board.</p>';
254
+ then = C.payoff; time = C.time; cta = C.cta; primary = !C.sent;
255
+ const risk = C.items.filter((x) => x.kind === 'risk').length;
256
+ foldSum = C.of + (risk ? ' · ' + risk + ' at risk' : '');
257
+ } else {
258
+ const r = iniRowOf(id) || { title: (S.IM && S.IM.title) || id };
259
+ const h = headOf(id); S.H = h;
260
+ kind = [r.lane ? r.lane.charAt(0).toUpperCase() + r.lane.slice(1) : 'Feature', r.kr || r.anchor || ''].filter(Boolean).join(' · ');
261
+ title = r.title; turn = h.turn; turnLabel = h.turnLabel; stage = h.stage;
262
+ lad = `<p class="hm-lad" role="img" aria-label="${esc(h.ladderAria)}">${h.prev ? `<span class="pv">${SVG(I.check, 11, 2.6)}${esc(h.prev)}</span>${SVG(I.chev, 11, 2.2)}` : ''}<b>${esc(h.cur)}</b>${h.toReach && h.toReach !== 'Done' ? SVG(I.chev, 11, 2.2) + `<span class="nx">${msStep(h.toReach) ? MS : ''}${esc(h.toReach)}</span>` : ''}</p>`;
263
+ bars = `<div class="hm-bars" aria-hidden="true">${h.steps.map((s) => `<i class="${s.cls}"></i>`).join('')}</div>`;
264
+ ckh = [h.checkTitle, h.doneOf];
265
+ const doneRow = h.done.length ? `<button type="button" class="hm-it donerow" data-hm-done aria-expanded="${S.doneOpen}">${markHtml('done')}<span class="l">${h.done.length} done${S.doneOpen ? '' : ': ' + esc(h.done.map((x) => x.label).join(' · '))}</span>${SVG(S.doneOpen ? 'M6 15l6-6 6 6' : I.down, 12, 2.2)}</button>` : '';
266
+ // the agent at work on this initiative: its avatar marks an agent step (AgInitAgents); with none at work the step is next
267
+ const at = S.D.sessions.find((s) => H.iniOfSession(s) === id && s.shown === 'working');
268
+ const io = { role: at ? H.roleOf(at, S.D.desk && S.D.desk.roles) : null, stalled: h.turn === 'stalled' };
269
+ items = doneRow + (S.doneOpen ? h.done.map((x) => itemHtml(x, io)).join('') : '') + h.rest.map((x) => itemHtml(x, io)).join('');
270
+ then = h.payoff; time = h.time; over = h.over; cta = h.cta; primary = h.primary;
271
+ foldSum = h.foldSum; msNext = msStep(h.toReach);
272
+ }
273
+ return `<section class="hm-card" aria-label="${esc(title)}"><div class="hm-ch"><span class="hm-tile sq">${SVG(prod ? I.flag : I.flag, 15)}</span>`
274
+ + `<button type="button" class="hm-sw" data-hm-switch aria-haspopup="menu" aria-label="${esc(title)}. Switch"><span class="k">${esc(kind)}</span><b>${esc(title)}</b></button>`
275
+ + `<button type="button" class="hm-ib sm" data-hm-switch aria-hidden="true" tabindex="-1">${SVG(I.down, 14, 2)}</button>`
276
+ + `<button type="button" class="hm-plus" data-hm-newin aria-label="New session in ${esc(title)}" title="New session">${SVG(I.plus, 16, 2)}</button></div>`
277
+ + `<div class="hm-box ${esc(turn)}"><div class="hm-br"><span class="hm-turn ${esc(turn)}"><i aria-hidden="true"></i>${esc(turnLabel)}</span><span class="st">${esc(stage)}</span></div>`
278
+ + lad + bars
279
+ // the checklist folds to one line (AgInitSpec): its title, the summary and a chevron; Then and the time line show only unfolded
280
+ + (S.cardFold
281
+ ? `<button type="button" class="hm-ckh hm-cfold" data-hm-cfold aria-expanded="false" aria-label="${esc(ckh[0])}: ${esc(foldSum || ckh[1])}. Show the list"><b>${ckTitle(ckh[0], msNext)}</b><span>${esc(foldSum || ckh[1])}</span>${SVG(I.down, 12, 2.2)}</button>`
282
+ : `<button type="button" class="hm-ckh" data-hm-cfold aria-expanded="true" title="Fold the list"><b>${ckTitle(ckh[0], msNext)}</b><span>${esc(ckh[1])}</span></button>${items}`
283
+ + (then ? `<p class="hm-then"><b>Then:</b> ${esc(then)}</p>` : '')
284
+ + (time ? `<p class="hm-time${over ? ' over' : ''}">${SVG(I.clock, 13)}${esc(time)}</p>` : ''))
285
+ + `<div class="hm-acts"><button type="button" class="hm-cta${primary ? '' : ' alt'}" data-hm-cta>${esc(cta)}</button>`
286
+ + `<button type="button" class="hm-ov" data-hm-ov aria-label="Overview of ${esc(title)} with Claude" title="Overview with Claude">${avHtml(CLAUDE, 24)}</button></div></div></section>`;
287
+ }
288
+ function iniListHtml() {
289
+ const id = S.ini;
290
+ const lay = H.iniLayout(S.D, id);
291
+ if (id === 'product') { // the product's sessions are its update and its own chats
292
+ const g = lay.groups.find((x) => x.key === 'sessions');
293
+ const upd = S.D.sessions.filter((s) => H.keyOfSession(s) === H.UPDATE_KEY.slice(5) || H.keyOfSession(s) === H.UPDATE_KEY);
294
+ if (upd.length && !g) lay.groups.splice(1, 0, { key: 'sessions', title: 'Sessions', rows: [] });
295
+ }
296
+ // Add a stakeholder is offered from the Stakeholders group's head and the card's switch menu, not as a row of the list (AgProduct, AgInitSpec)
297
+ const groups = lay.groups.map((g) => groupHtml('i:' + g.key, g.title, g.rows, '', g.key === 'people' ? `<button type="button" class="hm-gadd" data-hm-person aria-label="Add a stakeholder to ${esc(iniTitle(id))}" title="Add a stakeholder">${SVG(I.plus, 14, 2.2)}</button>` : '')).join('');
298
+ S.lay = lay;
299
+ return cardHtml(id) + groups;
300
+ }
301
+ /** The Elsewhere card of an initiative's layout: pinned to the bottom of the list column, under the groups, never over them. */
302
+ function elseHtml() {
303
+ const e = S.ini && S.lay && S.lay.elsewhere;
304
+ return e ? `<button type="button" class="hm-else" data-hm-else><i class="hm-dot you" aria-hidden="true"></i><span><em>Elsewhere</em><b>${esc(e.text)}</b></span>${SVG(I.chev, 14, 2)}</button>` : '';
305
+ }
306
+ function drawList() {
307
+ const el = $('#hmList');
308
+ // the list column: the groups scroll; the Elsewhere card is the column's foot (AgInitSpec, AgInitPhone)
309
+ let sc = el.querySelector(':scope > .hm-lsc'), ft = el.querySelector(':scope > .hm-lft');
310
+ if (!sc || !ft) { el.innerHTML = '<div class="hm-lsc"></div><div class="hm-lft"></div>'; sc = el.firstElementChild; ft = el.lastElementChild; }
311
+ const html = S.ini ? iniListHtml() : homeListHtml();
312
+ if (sc.__h !== html) {
313
+ const st = sc.scrollTop, cap = sc.querySelector('#hmCap'), capV = cap ? cap.value : '', capF = !!cap && document.activeElement === cap;
314
+ sc.__h = html; sc.innerHTML = html; sc.scrollTop = st;
315
+ sc.querySelectorAll('.hm-load i[data-f]').forEach((i) => i.style.setProperty('--bd-f', i.dataset.f)); // the day's load: run-time geometry
316
+ const c2 = sc.querySelector('#hmCap'); if (c2 && capV) { c2.value = capV; } if (c2 && capF) c2.focus(); // a task being typed survives a redraw
317
+ }
318
+ const fh = elseHtml();
319
+ if (ft.__h !== fh) { ft.__h = fh; ft.innerHTML = fh; }
320
+ iniList(sc);
321
+ // the first-run card after an import tops the list; the phone moment card sits after the groups
322
+ if (FST && sc.firstElementChild !== FST) sc.prepend(FST);
323
+ if (PHC && sc.lastElementChild !== PHC.el) sc.append(PHC.el);
324
+ document.body.classList.toggle('hm-folded', S.folded && !isPhone());
325
+ document.body.classList.toggle('hm-plist', isPhone() && !S.phoneChat); // a phone: the list is the page until a row opens its conversation (HmPhone)
326
+ }
327
+
328
+ function draw() { drawList(); drawTop(); chat.refresh(); }
329
+
330
+ /* ── rows by id ── */
331
+ function allRows() {
332
+ const out = [];
333
+ const M = S.M || L.homeList(S.D, { now: NOW() });
334
+ const add = (r) => { if (!r) return; out.push(r); (r.kids || []).forEach(add); };
335
+ H.needsOf(S.D).forEach(add);
336
+ for (const g of M.groups) { (g.flat || []).forEach(add); (g.inis || []).forEach(add); (g.rest || []).forEach(add); (g.rows || []).forEach(add); }
337
+ if (M.list) M.list.rows.forEach(add);
338
+ if (S.filter !== 'today') { const T = L.homeList(S.D, { now: NOW() }); T.groups.forEach((g) => { (g.rows || []).forEach(add); (g.inis || []).concat(g.rest || []).forEach(add); }); }
339
+ if (S.lay) S.lay.groups.forEach((g) => g.rows.forEach(add));
340
+ for (const s of S.D.sessions) { const r = { id: 's:' + s.id, kind: 'session', sid: s.id, key: H.keyOfSession(s), ini: H.iniOfSession(s), name: (s.hx && s.hx.title) || s.name, role: H.roleOf(s, S.D.desk && S.D.desk.roles), state: s.shown }; out.push(r); }
341
+ return out;
342
+ }
343
+ const rowById = (id) => allRows().find((r) => r.id === id) || null;
344
+
345
+ /* ── the top bar (phone) ── */
346
+ function drawTop() {
347
+ const n = H.needsOf(S.D).length;
348
+ const cur = S.cur || { title: 'Home', sub: '' };
349
+ $('#hmTopTitle').textContent = cur.title; $('#hmTopSub').textContent = cur.sub || '';
350
+ $('#hmNeedsN').textContent = !S.ready ? 'Reading' : n ? n + (n === 1 ? ' next step' : ' next steps') : 'Today';
351
+ $('#hmNeeds').classList.toggle('loud', n > 0);
352
+ document.title = 'PMOS · ' + (cur.title || 'Home');
353
+ }
354
+
355
+ /* ── the chat ── */
356
+ const chat = mountChat($('#hmChat'), {
357
+ esc, toast, pmGet, pmPost, pressHeaders: () => { const h = pmHeaders(); delete h['Content-Type']; return h; },
358
+ roles: () => (S.D.desk && S.D.desk.roles) || [],
359
+ seen: (key) => (S.D.desk && S.D.desk.seen && S.D.desk.seen[key]) || null,
360
+ markSeen: (key) => { pmPost('/api/home-desk/seen', { key }).then((r) => { if (r && r.ok && S.D.desk) S.D.desk.seen = { ...S.D.desk.seen, [key]: r.seen }; }); },
361
+ session: (id) => S.D.sessions.find((s) => s.id === id) || null,
362
+ queued: (sid) => (sid && S.D.desk && S.D.desk.queued && S.D.desk.queued[sid]) || [],
363
+ queue: (sid, text) => pmPost('/api/home-desk/queue', { session: sid, text }).then((r) => { if (r && r.ok && S.D.desk) { const q = { ...(S.D.desk.queued || {}) }; q[sid] = (q[sid] || []).concat({ text, at: r.at }); S.D.desk.queued = q; chat.refresh(); } }),
364
+ unqueue: (sid, at) => { pmPost('/api/home-desk/queue-drop', { session: sid, at }); if (S.D.desk && S.D.desk.queued && S.D.desk.queued[sid]) S.D.desk.queued[sid] = S.D.desk.queued[sid].filter((x) => x.at !== at); },
365
+ onScope: (b) => menu(b, scopeItems(), 'Where this goes'),
366
+ onLink: (b, t) => menu(b, H.boardRows(S.D).map((r) => ({ label: r.title, sub: r.stage, go: () => link(t.sid, r.id) })), 'Link it to an initiative'),
367
+ onTo: (b) => menu(b, toItems(), 'Who reads this'),
368
+ workItem: (text, t) => workItem(text, t),
369
+ openTerminal: (sid) => openTerminal(sid),
370
+ viewerClosed: () => !VW.isOpen() && !isPhone(),
371
+ wait: MORE.WAIT, // the Notes viewer only: the Home canvas does not draw it
372
+ desk: () => !isPhone(),
373
+ reopenViewer: () => reopenViewer(),
374
+ });
375
+ function scopeItems() {
376
+ return [{ label: 'All work', sub: 'Home', go: () => select(null) }, { label: H.productName(S.D) + ' · product', go: () => goIni('product') }]
377
+ .concat(H.boardRows(S.D).map((r) => ({ label: r.title, sub: [r.lane, r.stage].filter(Boolean).join(' · '), go: () => goIni(r.id) })));
378
+ }
379
+ function toItems() {
380
+ const id = S.ini;
381
+ const ses = S.D.sessions.filter((s) => H.iniOfSession(s) === id && s.shown !== 'exited');
382
+ return [{ label: 'Claude', sub: 'The chat of this initiative', go: () => openTarget(iniTarget(id)) }]
383
+ .concat(ses.map((s) => { const r = H.roleOf(s, S.D.desk && S.D.desk.roles); return { label: r.name, sub: (s.hx && s.hx.title) || s.name, go: () => openTarget(sessionTarget(s)) }; }))
384
+ .concat([{ label: 'A new session', sub: 'Starts in ' + iniTitle(id), go: () => newIn(id) }]);
385
+ }
386
+ async function link(sid, ini) {
387
+ const r = await pmPost('/api/session/initiative', { id: sid, initiative: ini });
388
+ if (!r || !r.ok) { toast((r && r.error) || 'The session was not linked.'); return; }
389
+ toast('Linked to ' + iniTitle(ini) + '.'); await load(); goIni(ini);
390
+ }
391
+ async function workItem(text, t) {
392
+ const ini = (t && t.ini) || S.ini;
393
+ if (!ini || ini === 'product') { toast('Open the initiative this belongs to, then make the work-item there.'); return; }
394
+ const b = (S.D.board && S.D.board.board) || {};
395
+ const r = await pmPost('/api/home-desk/work-item', { ws: b.ws || WS || undefined, initiative: ini, text, key: (t && (t.key || t.sid)) || '' });
396
+ toast(r && r.ok ? 'Drafted ' + (r.id || 'a work-item') + ' in ' + iniTitle(ini) + '. Nothing reaches Jira until your Commit.' : (r && r.error) || 'The work-item was not drafted.');
397
+ }
398
+ const iniTitle = (id) => (id === 'product' ? H.productName(S.D) + ' · product' : (iniRowOf(id) || {}).title || (S.IM && S.IM.title) || id);
399
+ const scopeOf = (ini) => (ini ? { text: iniTitle(ini), icon: I.flag } : { text: 'All work', icon: I.home, loose: false });
400
+ const rich = () => !!S.ini;
401
+ function iniTarget(id) {
402
+ const h = S.H || {};
403
+ return { key: 'init:' + id, ini: id, ws: WS || undefined, title: iniTitle(id), sub: (S.IMid === id && h.stage) || '', scope: scopeOf(id), rich: true, placeholder: 'Message Claude about ' + iniTitle(id),
404
+ empty: 'Ask about ' + iniTitle(id) + '. Claude reads its records and works in a real Claude Code session.', also: alsoOf(id),
405
+ // the initiative's conversation opens on where it stands (AgInitYou), until it has messages of its own
406
+ intro: S.IMid === id && h.cur ? { role: CLAUDE, onlyEmpty: true, text: h.cur + '. ' + h.doneOf + '.' + (h.rest.length ? ' Waiting: ' + h.rest.map((x) => x.label).join(', ') + '.' : ''), pills: [{ label: h.cta, primary: true, go: () => cta() }, { label: 'Discuss', go: () => chat.focus() }] } : undefined, context: h.payoff ? 'Initiative ' + id + ': ' + (h.stage || '') + '. ' + (h.time || '') : undefined };
407
+ }
408
+ function sessionTarget(s) {
409
+ const key = H.keyOfSession(s);
410
+ const ini = H.iniOfSession(s);
411
+ const role = H.roleOf(s, S.D.desk && S.D.desk.roles);
412
+ const t = { title: (s.hx && s.hx.title) || s.name, sub: [role.name, ini ? iniTitle(ini) : 'Loose'].join(' · '), ini, role, scope: ini ? scopeOf(ini) : { text: 'Loose', icon: I.chat, loose: true }, rich: rich(), to: rich() ? role : null, also: alsoOf(ini) };
413
+ if (key && /^(decision|blocked|waited|src|ev|work|board|init|doc|ins|chat|pop):/.test(key)) { t.key = key; t.sid = undefined; } else t.sid = s.id;
414
+ if (!t.key) t.sid = s.id;
415
+ return t;
416
+ }
417
+ function alsoOf(ini) {
418
+ const other = H.needsOf(S.D).filter((r) => !ini || r.ini !== ini || true).filter((r) => !(S.sel && S.sel === r.id));
419
+ const n = other.find((r) => r.ini === ini) || other[0];
420
+ return n ? { text: n.name, go: () => select(n.id) } : null;
421
+ }
422
+ /* HmDecide: a decision is recorded in the chat, on a card under the agent's question: the choices, Why (kept in the journal), Record,
423
+ * Later (Later today, Tomorrow 09:00, Next week) and Pin. Nothing changes until the PM presses Record (POST /api/briefing-premium/decide). */
424
+ function decisionCard(r) {
425
+ const d = r.row.dialog || {};
426
+ const st = S.rec[r.key] || (S.rec[r.key] = { choice: d.sel || null, why: '', ret: null, note: '' });
427
+ if (st.whyShown == null) st.whyShown = st.why;
428
+ const ok = () => !!st.choice && st.why.trim().length >= 3;
429
+ return {
430
+ html: () => `<div class="ut-card ut-dec" role="group" aria-label="Your decision"><p class="ut-lbl">Your decision</p><div role="radiogroup" aria-label="Choices">${(d.opts || []).map((o) => `<button type="button" class="ut-radio" role="radio" aria-checked="${st.choice === o.k}" data-dc-opt="${esc(o.k)}"><span class="o" aria-hidden="true"></span><span><b>${esc(o.t)}</b>${o.d ? `<br><span class="ut-small ut-mut">${esc(o.d)}</span>` : ''}</span></button>`).join('')}</div>`
431
+ + `<div class="ut-field"><label for="dcWhy">Why <span class="ut-mut">· kept in the journal</span></label><textarea id="dcWhy" rows="2" placeholder="The reason goes in pm-decisions.md with your choice">${esc(st.whyShown)}</textarea></div>`
432
+ + `<div class="ut-acts"><button type="button" class="ut-btn pri" data-dc-rec${ok() ? '' : ' disabled'}>Record</button><button type="button" class="ut-btn" data-dc-later aria-haspopup="menu">Later${TD.svg(TD.P.chevD, 14)}</button>`
433
+ + `<button type="button" class="ut-ib${S.pin.has(r.key) ? ' on' : ''}" data-dc-pin aria-pressed="${S.pin.has(r.key)}" aria-label="${S.pin.has(r.key) ? 'Unpin' : 'Pin to the top'}" title="${S.pin.has(r.key) ? 'Unpin' : 'Pin to the top'}">${TD.svg(TD.P.pin, 16)}</button><span class="sp">Nothing changes until you press Record</span></div>`
434
+ + '<p class="ut-small ut-mut" role="status" id="dcMsg"></p></div>',
435
+ input: (t, card) => { if (t.id !== 'dcWhy') return; st.why = t.value; const b = card.querySelector('[data-dc-rec]'); if (b) b.disabled = !ok(); },
436
+ press: async (b) => {
437
+ st.whyShown = st.why; // a redraw after a press keeps what was typed; typing itself never changes the card's html
438
+ const say = (m) => { const el = document.getElementById('dcMsg'); if (el) el.textContent = m; };
439
+ if (b.dataset.dcOpt) { st.choice = b.dataset.dcOpt; return true; }
440
+ if ('dcPin' in b.dataset) { if (S.pin.has(r.key)) S.pin.delete(r.key); else S.pin.add(r.key); store.set('pmos.home.pin', JSON.stringify([...S.pin])); drawList(); return true; }
441
+ if ('dcLater' in b.dataset) {
442
+ const at = new Date(NOW() + 3 * 3600000);
443
+ const put = async (until) => { const res = await bpPost('put-off', { key: r.key, until }); if (res.ok) { toast('Put off. It comes back by itself, and it is not counted as done.'); delete S.rec[r.key]; VW.close(); await load(); select(null); } else say(res.error); };
444
+ menu(b, [{ label: 'Later today', k: H.hm(at.toISOString()), go: () => put('later') }, { label: 'Tomorrow', k: '09:00', go: () => put('tomorrow') }, { label: 'Next week', k: 'Mon', go: () => put('nextweek') }], '');
445
+ return false;
446
+ }
447
+ if ('dcRec' in b.dataset) {
448
+ b.disabled = true;
449
+ const res = await bpPost('decide', { key: r.key, choice: st.choice, why: st.why });
450
+ if (!res.ok) { b.disabled = false; say(res.error); return false; }
451
+ delete S.rec[r.key];
452
+ toast('Recorded in pm-decisions.md.');
453
+ VW.close(); await load(); select(null);
454
+ }
455
+ return false;
456
+ },
457
+ };
458
+ }
459
+ function needTarget(r) {
460
+ const row = r.row, d = row.dialog || {};
461
+ const pills = [];
462
+ const dec = d.write && d.write.kind === 'decision';
463
+ if (!dec) for (const o of d.opts || []) pills.push({ label: o.t, primary: o.k === (d.prim || d.sel), go: () => { S.rec[r.key] = { ...(S.rec[r.key] || {}), choice: o.k }; openNeedViewer(r, true); } });
464
+ if (d.write && d.write.kind === 'start') pills.unshift({ label: 'Start the agent', primary: true, go: () => start(r) });
465
+ if (d.write && d.write.kind === 'return') pills.push({ label: 'Return it', go: () => openNeedViewer(r, true) });
466
+ if (!dec) pills.push({ label: 'Discuss', go: () => chat.focus() });
467
+ return { key: r.key, ini: r.ini, ws: WS || undefined, title: r.name, sub: r.hint || '', scope: scopeOf(r.ini), rich: rich(), role: CLAUDE,
468
+ intro: { role: CLAUDE, text: d.say || row.subject || row.title, pills: dec ? [] : pills, card: dec ? decisionCard(r) : undefined }, placeholder: dec ? 'Answer, or type /' : 'Ask about ' + r.name, also: null };
469
+ }
470
+ function updateTarget() {
471
+ const U = H.weeklyUpdate(S.D, S.D.now);
472
+ const flags = U.sections.flatMap(([, , L]) => L).filter((x) => x.flag);
473
+ const text = 'The weekly update is drafted from the ladders and run logs, not from memory.' + (flags.length ? ' One thing to check before it goes out: ' + flags[0].title + ' looks green, but ' + flags[0].flag.replace(/^Looks green, but /, '').toLowerCase() + ', so I marked it.' : '');
474
+ const sent = (U.sent || []).find((x) => x.week === U.week.iso);
475
+ // the product's conversation shows its In: scope chip (AgProduct); To: is for a running role session only (AgChatRunning)
476
+ return { key: H.UPDATE_KEY, ini: 'product', ws: WS || undefined, title: 'Weekly update', sub: 'Communicator · ' + (sent ? 'sent this week' : 'ready to send'), scope: scopeOf('product'), rich: rich(), role: COMMS, to: null,
477
+ intro: { role: COMMS, text: sent ? 'This week\'s update went out from your mail on ' + new Date(sent.at).toDateString() + '.' : text,
478
+ pills: sent ? [{ label: 'Read it', primary: true, go: () => openUpdateViewer() }] : [{ label: 'Send now', primary: true, go: () => sendUpdate() }, { label: 'Edit', go: () => { openUpdateViewer(); chat.focus(); } }] },
479
+ context: 'The weekly update draft for ' + H.productName(S.D) + ':\n' + H.updateText(U, H.productName(S.D)) + '\nRecipients: ' + (U.to.join(', ') || 'none yet') + '. You can change the draft; the PM sends it from their own mail.',
480
+ placeholder: 'Tell Communicator what to change', also: null };
481
+ }
482
+ function homeTarget() {
483
+ return { key: 'chat:main', ws: WS || undefined, title: 'Home', scope: { text: 'All work', icon: I.home }, rich: false, placeholder: 'Message Claude', role: CLAUDE,
484
+ empty: 'Ask anything about your work. Claude reads your repositories and works in a real Claude Code session.', also: alsoOf(null) };
485
+ }
486
+ function openTarget(t) {
487
+ S.cur = { title: t.title, sub: t.sub != null && t.sub !== '' ? t.sub : t.scope && t.scope.text !== t.title ? t.scope.text : '' };
488
+ chat.open(t); drawTop();
489
+ }
490
+
491
+ /* ── selection ── */
492
+ function select(id, o = {}) {
493
+ S.sel = id;
494
+ const r = id ? rowById(id) : null;
495
+ if (isPhone()) sheet(false);
496
+ if (!r) { S.phoneChat = false; if (S.ini) openTarget(iniTarget(S.ini)); else openTarget(homeTarget()); drawList(); return; }
497
+ if (r.kind === 'ini') { goIni(r.ini); return; }
498
+ if (r.kind === 'product') { goIni('product'); return; }
499
+ // a row with a conversation opens it; on a phone it opens over the list, with a back bar (HmPhone2)
500
+ if (isPhone() && (r.kind === 'update' || (r.kind === 'need' && r.row) || r.kind === 'session' || r.needSession)) S.phoneChat = true;
501
+ if (r.kind === 'update') { openTarget(updateTarget()); if (!o.keepViewer) openUpdateViewer(); }
502
+ else if (r.kind === 'need' && r.row) { openTarget(needTarget(r)); if (!o.keepViewer) openNeedViewer(r); }
503
+ else if (r.kind === 'session' || r.needSession) { const s = S.D.sessions.find((x) => x.id === r.sid); if (s) { openTarget(sessionTarget(s)); if (isMetricsSession(s) && !o.keepViewer && !isPhone()) openMetricsViewer(); } }
504
+ else if (r.kind === 'task') { openBoardTask(r.task); }
505
+ else if (r.kind === 'item') { import('./home-work.js').then((M) => M.openWorkItem(r.key)); }
506
+ else if (r.kind === 'mention') { openMention(r); }
507
+ else if (r.kind === 'finished') { openFinished(r.finished); }
508
+ else if (r.kind === 'meeting') { openMeeting(r.meeting); }
509
+ else if (r.kind === 'routine') { if (isMetrics(r.schedule)) openMetrics(o); else openRoutine(r.schedule); }
510
+ else if (r.kind === 'file') { openFile(r.file); }
511
+ else if (r.kind === 'person') { openPerson(r.person); }
512
+ drawList();
513
+ syncUrl();
514
+ }
515
+ async function goIni(id) {
516
+ S.ini = id; S.sel = null; S.doneOpen = false;
517
+ if (isPhone()) sheet(false);
518
+ syncUrl();
519
+ drawList();
520
+ await loadIni();
521
+ if (S.ini !== id) return;
522
+ drawList();
523
+ if (id === 'product') { openTarget(updateTarget()); if (!VW.isOpen() && !isPhone()) openUpdateViewer(); }
524
+ else openTarget(iniTarget(id));
525
+ }
526
+ function goHome() { S.ini = null; S.sel = null; S.IM = null; syncUrl(); drawList(); openTarget(homeTarget()); }
527
+ function syncUrl() {
528
+ const q = new URLSearchParams(location.search);
529
+ ['ini', 'open', 'item', 'session', 'ask', 'say', 'q', 'about', 'label', 'meeting', 'id', 'view'].forEach((k) => { if (!(k === 'open' && /^(report|chart|dashboard):/.test(q.get('open') || ''))) q.delete(k); });
530
+ if (S.ini) q.set('ini', S.ini);
531
+ const r = S.sel ? rowById(S.sel) : null;
532
+ if (r && r.key && r.kind !== 'session') q.set('open', r.key); else if (r && r.sid) q.set('session', r.sid);
533
+ const s = q.toString();
534
+ history.replaceState(null, '', location.pathname + (s ? '?' + s : ''));
535
+ }
536
+
537
+ /* ── the one list's own views: a task, a mention, finished work, the weekly review (premium-uncovered-features) ── */
538
+ const boardWs = () => ((S.D.board && S.D.board.board) || {}).ws || WS || undefined;
539
+ const boardId = () => ((S.D.board && S.D.board.board) || {}).id || BOARD || undefined;
540
+ const HTTPS = /^https:\/\//;
541
+ function openBoardTask(t) {
542
+ if (!t) return;
543
+ import('./home-task.js').then((M) => M.openTask(t, {
544
+ VW, pmPost, toast, now: NOW, ws: t.ws || boardWs(), board: t.board || boardId(), iniTitle,
545
+ docs: (id) => (S.IMid === id && S.IM ? (S.IM.docs.rows || []).filter((d) => d.path && !d.tech).map((d) => ({ title: d.title, path: d.path })) : []),
546
+ openIni: (id) => goIni(id), openDoc: (d) => openFile({ path: d.path, name: d.title }),
547
+ askInChat: (task) => {
548
+ S.phoneChat = isPhone();
549
+ openTarget({ ...iniTarget(task.ini), placeholder: 'Ask about ' + task.title });
550
+ setTimeout(() => { const ta = $('#hmIn'); if (ta) { ta.value = 'About the task "' + task.title + '": '; ta.dispatchEvent(new Event('input', { bubbles: true })); ta.focus(); } }, 0);
551
+ drawList();
552
+ },
553
+ openRecord: (task) => import('./premium-vw-item.js').then((V) => V.openWorkItem({ kind: 'task', ini: task.ini, key: 'task:' + task.uid, title: task.title, ws: boardWs(), board: boardId() })).catch(() => toast('The record could not open.')),
554
+ onChange: () => load(),
555
+ }));
556
+ }
557
+ function openMention(r) {
558
+ const m = r.mention || {};
559
+ const draw = (b) => {
560
+ b.innerHTML = `<div class="ut-vc"><div><h2 class="ut-h2">${esc(r.name)}</h2><p class="ut-sub">${esc(['Mention', m.where || m.source, m.at ? H.hm(m.at) : ''].filter(Boolean).join(' · '))}</p></div>`
561
+ + (m.text ? `<div class="ut-box">${esc(m.text)}</div>` : '') + (m.reply ? `<p class="ut-lbl">A reply you could send</p><div class="ut-box">${esc(m.reply)}</div>` : '')
562
+ + `<div class="ut-foot">${HTTPS.test(m.link || '') ? `<a class="ut-btn pri" href="${esc(m.link)}" target="_blank" rel="noopener noreferrer">Open it</a>` : ''}<button type="button" class="ut-btn" data-mn-read>Mark it read</button></div>`
563
+ + '<p class="ut-small ut-mut">PMOS sends nothing. Reply where the mention is.</p></div>';
564
+ };
565
+ const body = VW.open({ id: 'mention:' + (m.id || r.id), kind: 'Mention', title: r.name, icon: 'info', render: draw });
566
+ body.onclick = async (e) => {
567
+ if (!e.target.closest('[data-mn-read]')) return;
568
+ const res = await pmPost('/api/mentions/read', { id: m.id, read: true });
569
+ if (res && res.ok) { toast('Marked read.'); VW.close(); load(); } else toast((res && res.error) || 'Not marked read.');
570
+ };
571
+ }
572
+ function openFinished(f) {
573
+ if (!f) return;
574
+ VW.open({ id: 'fin:' + (f.id || f.title), kind: f.status === 'review' ? 'Finished · waits for your review' : 'Finished', title: f.title, icon: 'doc',
575
+ html: `<div class="ut-vc">${f.summary ? `<p class="ut-sub">${esc(f.summary)}</p>` : ''}${f.body ? `<article class="hv-doc">${mdHtml(f.body)}</article>` : ''}${HTTPS.test(f.link || '') ? `<div class="ut-foot"><a class="ut-btn" href="${esc(f.link)}" target="_blank" rel="noopener noreferrer">Open it</a></div>` : ''}</div>` });
576
+ }
577
+ function openReviewVw() {
578
+ S.sel = 'review'; drawList();
579
+ import('./home-review.js').then((M) => M.openReview({
580
+ VW, pmPost, toast, D: () => S.D, reload: () => load(), ws: () => boardWs(), iniTitle, now: NOW,
581
+ openWork: () => MORE.openMyWork(),
582
+ askAbout: (st, act) => {
583
+ S.phoneChat = isPhone();
584
+ const owner = st.owner ? ' It is ' + st.owner + '’s.' : ' It has no owner.';
585
+ openTarget({ ...homeTarget(), key: 'chat:review-' + st.id, title: 'Weekly review · ' + st.title, scope: { text: st.title, icon: I.flag },
586
+ intro: { role: CLAUDE, text: st.title + ' has had no change for ' + st.days + ' days, in ' + (st.stage || 'its stage') + '.' + owner + ' Do you want to hold it, or keep it going?',
587
+ pills: [{ label: 'Hold it', go: async () => { if (await act.hold()) chat.focus(); } }, { label: 'Keep it going', go: () => act.keep() }, { label: 'Skip', go: () => chat.focus() }] },
588
+ placeholder: 'Answer, or type /', context: 'Weekly review: ' + st.title + ' (' + st.id + ') has had no change for ' + st.days + ' days.' });
589
+ drawList();
590
+ },
591
+ }));
592
+ }
593
+ /* the capture box: a typed task goes under the initiative it names (POST /api/boards/tasks/add), else on the PM's own list (POST /api/pm-items/add) */
594
+ async function capture(text) {
595
+ const line = String(text || '').trim(); if (!line) return false;
596
+ const ini = L.fileUnder(line, H.boardRows(S.D).filter(H.OPEN));
597
+ const b = (S.D.board && S.D.board.board) || {};
598
+ const r = ini && b.id ? await pmPost('/api/boards/tasks/add', { ws: b.ws || WS || undefined, board: b.id, initiative: ini, title: line })
599
+ : await pmPost('/api/pm-items/add', { line });
600
+ if (!r || r.ok !== true) { toast((r && r.error) || 'The task was not added.'); return false; }
601
+ toast(ini ? 'Added under ' + iniTitle(ini) + '.' : 'Added. It names no initiative, so it is under Not in an initiative.');
602
+ if (ini) { S.kids.add('i:' + ini); S.kidsOff.delete('i:' + ini); }
603
+ await load();
604
+ return true;
605
+ }
606
+ /* a check in the list: a task or a note is done (the board's task route, or My work's) */
607
+ async function checkRow(id) {
608
+ const r = rowById(id); if (!r) return;
609
+ let res = null;
610
+ if (r.kind === 'task' && r.task) res = await pmPost('/api/boards/tasks/state', { ws: r.task.ws || boardWs(), board: r.task.board || boardId(), task: r.task.uid, state: 'Done' });
611
+ else if (r.kind === 'item' && r.item) res = await pmPost('/api/pm-items/done', { id: r.item.id });
612
+ else return;
613
+ if (!res || !res.ok) { toast((res && res.error) || 'Not marked done.'); return; }
614
+ toast('Done.');
615
+ await load();
616
+ }
617
+ /* the products picker (HmProducts): All products, each product with its goals, Add a product */
618
+ function pickProduct(anchor) {
619
+ const M = S.M || L.homeList(S.D, { now: NOW() });
620
+ const items = [{ label: 'All products', sub: 'Home only · Board and Insights show one', checked: !S.product, go: () => setProduct(null) }, { sep: true }]
621
+ .concat(M.products.map((p) => {
622
+ const g = M.groups.find((x) => x.product && x.product.key === p.key);
623
+ const n = g ? g.count : ((p.model && p.model.initiatives && p.model.initiatives.list && p.model.initiatives.list.rows) || []).filter(H.OPEN).length;
624
+ return { label: p.name, sub: [n + (n === 1 ? ' initiative' : ' initiatives'), p.goals && p.goals.n ? p.goals.ok + ' of ' + p.goals.n + ' goals' : ''].filter(Boolean).join(' · '), tile: p.initials, primary: p.primary, checked: S.product === p.key, go: () => setProduct(p.key) };
625
+ }))
626
+ .concat([{ sep: true }, { label: 'Add a product', icon: TD.P.plus, go: () => MORE.openProducts() }]);
627
+ menu(anchor, items, '');
628
+ }
629
+ function setProduct(key) { S.product = key; store.set('pmos.home.product', key); if (key) S.pg['p:' + key] = true; drawList(); }
630
+
631
+ /* ── the Viewer: needs rows, the weekly update, the overview, files, people, routines ── */
632
+ let lastViewer = null;
633
+ VW.onChange((d) => { if (d.open) lastViewer = d.id; chat.refresh(); document.body.classList.toggle('hm-vw-open', d.open); });
634
+ function reopenViewer() {
635
+ if (/^vw:/.test(lastViewer || '')) { import('./premium-viewer.js').then((M) => { if (!M.vwReopen()) { lastViewer = null; reopenViewer(); } }); return; } // the last file, chart or report shown
636
+ const r = S.sel ? rowById(S.sel) : null;
637
+ if (r) { select(r.id); return; }
638
+ if (S.ini === 'product') { openUpdateViewer(); return; }
639
+ if (S.ini) { openOverview(); return; }
640
+ MORE.openMyWork();
641
+ }
642
+ function factsHtml(rows) { return rows && rows.length ? `<dl class="hv-facts">${rows.map(([k, v]) => `<div><dt>${esc(k)}</dt><dd>${esc(v)}</dd></div>`).join('')}</dl>` : ''; }
643
+ function openNeedViewer(r, focusWhy) {
644
+ const row = r.row, d = row.dialog || {}, w = d.write || {};
645
+ const st = S.rec[r.key] || (S.rec[r.key] = { choice: d.sel || null, why: '', ret: null });
646
+ const draw = (b) => {
647
+ const pane = d.pane || {};
648
+ const facts = factsHtml(pane.rows || d.facts || []);
649
+ // a source row (mail, Jira, Confluence, from the morning brief): why it is here now, and its own https link; nothing is recorded or sent
650
+ const src = row.kind === 'source';
651
+ const intro = pane.intro ? `<p class="hv-intro">${src ? '<b>Why now</b> ' : ''}${esc(pane.intro)}</p>` : '';
652
+ const paras = (pane.paras || []).length ? `<section class="hv-sec"><h4>${esc(pane.parasTitle || 'More')}</h4>${pane.paras.map((x) => `<p class="hx-n">${esc(x)}</p>`).join('')}</section>` : '';
653
+ const link = /^https:\/\//.test(d.link || '') ? `<a class="hx-b hv-link" id="srcLink" href="${esc(d.link)}" target="_blank" rel="noopener noreferrer">${esc(d.linkLabel || 'Open it')}</a>` : '';
654
+ let rec = '';
655
+ if (w.kind === 'decision') {
656
+ // the decision is recorded on the chat's card (HmDecide); the Viewer keeps the facts it rests on
657
+ rec = '<p class="ut-small ut-mut">Record your decision on the card in the chat.</p>';
658
+ } else if (w.kind === 'return') {
659
+ // HmDecide, the Viewer's "Return a run": why it goes back, what to change, Return it or Keep it as is
660
+ b.innerHTML = `<div class="ut-vc"><div><h2 class="ut-h2">${esc(r.name)}</h2><p class="ut-sub">${esc(r.hint || pane.h || '')}</p></div>${facts}`
661
+ + `<p class="ut-lbl">Why it goes back</p><div class="ut-chips" role="group" aria-label="Why it goes back">${RET_REASONS.map((x) => `<button type="button" class="cz-chip${st.ret === x ? ' on' : ''}" aria-pressed="${st.ret === x}" data-hv-ret="${esc(x)}">${esc(RET_LABEL[x] || x)}</button>`).join('')}</div>`
662
+ + `<div class="ut-field"><label for="hvNote">What to change</label><textarea id="hvNote" rows="3" placeholder="Say what the agent should change">${esc(st.note || '')}</textarea></div>`
663
+ + '<div class="ut-box ut-small">The agent gets this note in its conversation and tries again. It counts as one correction.</div>'
664
+ + `<div class="ut-foot"><button type="button" class="ut-btn dark" data-hv-rec${st.ret ? '' : ' disabled'}>Return it</button><button type="button" class="ut-btn ghost" data-hv-keep>Keep it as is</button></div>`
665
+ + '<p class="ut-small ut-mut" role="status" id="hvMsg"></p></div>';
666
+ if (focusWhy) { const t = b.querySelector('#hvNote'); if (t) setTimeout(() => t.focus(), 0); focusWhy = false; }
667
+ return;
668
+ } else if (w.kind === 'start') {
669
+ rec = `<section class="hv-sec"><h4>Start</h4><p class="hx-n">The agent drafts ${esc(w.what || 'it')} in a real session. Its draft waits for you to read.</p><div class="hv-acts"><button type="button" class="hx-b pri" data-hv-start>Start the agent</button>${laterHtml()}${pinHtml(r)}</div></section>`;
670
+ } else rec = `<div class="hv-acts">${link}${src ? '' : laterHtml()}${pinHtml(r)}</div>`; // a source row cannot be put off (the server refuses it)
671
+ b.innerHTML = `<div class="hv">${pane.note ? `<p class="hv-note">${esc(pane.note)}</p>` : ''}${pane.h ? `<h4 class="hv-h">${esc(pane.h)}</h4>` : ''}${intro}${facts}${paras}${rec}<p class="hx-n" role="status" id="hvMsg"></p></div>`;
672
+ if (focusWhy) { const t = b.querySelector('#hvWhy'); if (t) setTimeout(() => t.focus(), 0); focusWhy = false; }
673
+ };
674
+ const body = VW.open({ id: 'need:' + r.key, kind: ({ decision: 'Decision', blocked: 'Blocked', waited: 'Waiting', src: 'Source', ev: 'Event' }[row.kind] || 'Needs you'), title: r.name, icon: 'info', url: d.pane && d.pane.file ? '/premium-board.html?doc=' + encodeURIComponent(d.pane.file) : '', render: draw });
675
+ body.oninput = (e) => { if (e.target.id === 'hvNote') { st.note = e.target.value; return; } if (e.target.id === 'hvWhy') { st.why = e.target.value; const b = body.querySelector('[data-hv-rec]'); if (b) b.disabled = !(st.choice && st.why.trim().length >= 3); } };
676
+ body.onclick = async (e) => {
677
+ const t = e.target.closest('button'); if (!t || t.disabled) return;
678
+ const say = (m) => { const el = body.querySelector('#hvMsg'); if (el) el.textContent = m; };
679
+ if (t.dataset.hvOpt) { st.choice = t.dataset.hvOpt; draw(body); return; }
680
+ if (t.dataset.hvRet) { st.ret = t.dataset.hvRet; draw(body); return; }
681
+ if ('hvLater' in t.dataset) { const m = t.nextElementSibling; m.hidden = !m.hidden; t.setAttribute('aria-expanded', String(!m.hidden)); return; }
682
+ if (t.dataset.hvUntil) { const res = await bpPost('put-off', { key: r.key, until: t.dataset.hvUntil }); if (res.ok) { toast('Put off. It comes back by itself, and it is not counted as done.'); VW.close(); await load(); select(null); } else say(res.error); return; }
683
+ if ('hvPin' in t.dataset) { if (S.pin.has(r.key)) S.pin.delete(r.key); else S.pin.add(r.key); store.set('pmos.home.pin', JSON.stringify([...S.pin])); draw(body); drawList(); return; }
684
+ if ('hvStart' in t.dataset) { start(r); return; }
685
+ if ('hvKeep' in t.dataset) { delete S.rec[r.key]; VW.close(); return; }
686
+ if ('hvRec' in t.dataset) {
687
+ t.disabled = true;
688
+ const res = w.kind === 'decision' ? await bpPost('decide', { key: r.key, choice: st.choice, why: st.why }) : await bpPost('return', { run: w.run, reason: st.ret, ...(w.ws ? { ws: w.ws } : {}) });
689
+ if (!res.ok) { t.disabled = false; say(res.error); return; }
690
+ delete S.rec[r.key];
691
+ toast(w.kind === 'decision' ? 'Recorded in pm-decisions.md.' : 'Returned to the agent. It counts as a correction.');
692
+ const note = w.kind === 'return' && String(st.note || '').trim();
693
+ if (note && chat.current() && chat.current().key === r.key) chat.send('What to change: ' + note);
694
+ VW.close(); await load(); select(null);
695
+ }
696
+ };
697
+ }
698
+ const laterHtml = () => `<span class="hv-later"><button type="button" class="hx-b" data-hv-later aria-haspopup="menu" aria-expanded="false">Put off</button><span class="hv-lm" role="menu" hidden>${[['later', 'Later today'], ['tomorrow', 'Tomorrow'], ['nextweek', 'Next week']].map(([k, t]) => `<button type="button" role="menuitem" data-hv-until="${k}">${t}</button>`).join('')}</span></span>`;
699
+ const pinHtml = (r) => `<button type="button" class="hx-b" data-hv-pin aria-pressed="${S.pin.has(r.key)}">${S.pin.has(r.key) ? 'Unpin' : 'Pin to the top'}</button>`;
700
+ async function bpPost(act, body) {
701
+ const r = await pmPost('/api/briefing-premium/' + act + wsQ(), body);
702
+ return r && r.ok === true ? r : { ok: false, error: (r && r.error) || 'The record was not written.' };
703
+ }
704
+ async function start(r) {
705
+ const w = r.row.dialog.write;
706
+ const res = await startAgent({ ws: w.ws || WS || undefined, task: 'draft', initiative: w.initiative, what: w.what });
707
+ toast(res.ok ? 'The agent started. Its draft waits for you to read.' : 'Not started: ' + res.error);
708
+ if (res.ok) load();
709
+ }
710
+
711
+ /* the weekly update: the recipients are editable; Send opens a mail draft in the PM's own mail and records that it was sent */
712
+ function openUpdateViewer() {
713
+ const draw = (b) => {
714
+ const U = H.weeklyUpdate(S.D, S.D.now);
715
+ const sent = (U.sent || []).find((x) => x.week === U.week.iso);
716
+ const sec = U.sections.map(([k, h, L]) => `<section class="hv-up ${k}"><h4><i aria-hidden="true"></i>${esc(h)}</h4>${L.length ? L.map((x) => `<button type="button" class="hv-ui" data-hv-ini="${esc(x.id)}"><span class="t"><b>${esc(x.title)}</b><em>${esc(x.meta)}</em></span><span class="d">${esc(x.text)}</span>${x.flag ? `<span class="flag">${esc(x.flag)}</span>` : ''}</button>`).join('') : '<p class="hx-n">None this week.</p>'}</section>`).join('');
717
+ b.innerHTML = `<div class="hv"><p class="hv-note">Drafted by Communicator from the ladders and run logs at ${esc(H.hm(new Date(S.D.now).toISOString()))}. Every line links to its source.</p>`
718
+ + `<div class="hv-to"><span>To</span>${U.to.map((x, i) => `<button type="button" class="hv-chip" data-hv-rm="${i}" aria-label="Remove ${esc(x)}" title="Remove">${esc(x)}</button>`).join('')}<input id="hvTo" placeholder="${U.to.length ? 'Add' : 'Who gets it: a name, a mail or #channel'}" aria-label="Add a recipient"></div>`
719
+ + sec + `<div class="hv-acts">${sent ? `<p class="hx-n">Sent from your mail ${esc(new Date(sent.at).toDateString())} to ${esc(sent.to.join(', '))}.</p>` : ''}<button type="button" class="hx-b pri" data-hv-send>${sent ? 'Send again' : 'Send now'}</button></div>`
720
+ + '<p class="hx-n">Send opens a draft in your own mail app. PMOS sends nothing by itself; it records that you opened the draft.</p><p class="hx-n" role="status" id="hvMsg"></p></div>';
721
+ };
722
+ const U0 = H.weeklyUpdate(S.D, S.D.now);
723
+ const body = VW.open({ id: 'update', kind: 'Weekly update', title: H.productName(S.D) + ' · week of ' + U0.week.label, icon: 'doc', url: selfUrl({ ini: 'product' }), render: draw });
724
+ const saveTo = async (to) => { const r = await pmPost('/api/home-desk/recipients', { ws: deskWs(), to }); if (r && r.ok) { S.D.desk.product = { ...(S.D.desk.product || {}), recipients: r.recipients }; draw(body); drawList(); } else toast((r && r.error) || 'The recipients were not saved.'); };
725
+ body.onkeydown = (e) => { if (e.target.id === 'hvTo' && (e.key === 'Enter' || e.key === ',')) { e.preventDefault(); const v = e.target.value.trim(); if (v) saveTo(H.weeklyUpdate(S.D).to.concat(v)); } };
726
+ body.onclick = async (e) => {
727
+ const t = e.target.closest('button'); if (!t) return;
728
+ if (t.dataset.hvRm) { const to = H.weeklyUpdate(S.D).to.slice(); to.splice(+t.dataset.hvRm, 1); saveTo(to); return; }
729
+ if (t.dataset.hvIni) { goIni(t.dataset.hvIni); return; }
730
+ if ('hvSend' in t.dataset) sendUpdate();
731
+ };
732
+ }
733
+ /** This page's address for one view (the Viewer's Open in a new tab): the workspace and board of this page, and the view's own keys. */
734
+ const selfUrl = (o) => { const q = new URLSearchParams(); if (WS) q.set('ws', WS); if (BOARD) q.set('board', BOARD); for (const [k, v] of Object.entries(o)) q.set(k, v); return location.pathname + '?' + q.toString(); };
735
+ const deskWs = () => (S.D.desk && S.D.desk.ws) || ((S.D.board && S.D.board.board) || {}).ws || WS || undefined;
736
+ async function sendUpdate() {
737
+ const U = H.weeklyUpdate(S.D, S.D.now);
738
+ if (!U.to.length) { openUpdateViewer(); toast('Say who the update goes to first.'); setTimeout(() => { const i = $('#hvTo'); if (i) i.focus(); }, 0); return; }
739
+ const name = H.productName(S.D), subject = name + ' · week of ' + U.week.label;
740
+ const mails = U.to.filter((x) => /@/.test(x));
741
+ location.href = 'mailto:' + mails.map(encodeURIComponent).join(',') + '?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(H.updateText(U, name) + (U.to.length > mails.length ? '\n\nAlso for: ' + U.to.filter((x) => !/@/.test(x)).join(', ') : ''));
742
+ const r = await pmPost('/api/home-desk/update-sent', { ws: deskWs(), week: U.week.iso, to: U.to, subject });
743
+ if (r && r.ok) { toast('The draft is open in your mail. Recorded as sent this week.'); await load(); if (S.ini === 'product') openTarget(updateTarget()); }
744
+ else toast((r && r.error) || 'The send was not recorded.');
745
+ }
746
+
747
+ /* the overview of an initiative: stage moves and hold, Tasks, Core documents (no design yet: a minimal version) */
748
+ function openOverview() {
749
+ if (iniOverview()) return;
750
+ const id = S.ini; if (!id || id === 'product') return;
751
+ let M = S.IM;
752
+ let ask = null; // on-hold | cancelled while its reason is asked
753
+ const draw = (b) => {
754
+ if (!M) { b.innerHTML = MORE.WAIT + '<p class="hx-n">The initiative could not be read.</p>'; return; }
755
+ const stages = (M.acts && M.acts.stages) || [];
756
+ const move = stages.length && !(M.acts && M.acts.self) ? `<div class="hx-tabs" role="group" aria-label="Move to a stage">${stages.map((s) => `<button type="button" aria-pressed="${s === M.acts.stage}" data-ov-move="${esc(s)}">${esc(s)}</button>`).join('')}</div>` : '<p class="hx-n">The stage of this board comes from the workflow engine.</p>';
757
+ const life = M.acts && M.acts.life ? `<button type="button" class="hx-b" data-ov-life="active">Resume</button>`
758
+ : ask ? `<label class="hv-why"><span>${ask === 'on-hold' ? 'Put on hold' : 'Cancel'}: why? It goes on the record.</span><input id="ovWhy" autocomplete="off"></label><button type="button" class="hx-b pri" data-ov-life-go>Record</button><button type="button" class="hx-b" data-ov-life-no>Not now</button>`
759
+ : `<button type="button" class="hx-b" data-ov-life="on-hold">Put on hold</button><button type="button" class="hx-b" data-ov-life="cancelled">Cancel</button>`;
760
+ const tasks = (M.tasks.rows || []).slice(0, 40).map((t) => `<div class="hx-row" data-ov-tkrow="${esc(t.key)}"><span class="hx-t"><b>${esc(t.title)}</b><em>${esc([t.src, t.state, t.owner].filter(Boolean).join(' · '))}</em></span><button type="button" class="hx-b" data-ov-tk="${esc(t.key)}" aria-label="Open ${esc(t.title)}">Open</button>${t.pmos && t.uid ? `<select data-ov-task="${esc(t.uid)}" aria-label="Status of ${esc(t.title)}">${['To do', 'In progress', 'In review', 'Done'].map((s) => `<option${t.state === s ? ' selected' : ''}>${s}</option>`).join('')}</select>` : ''}</div>`).join('') || `<p class="hx-n">${esc(M.tasks.note || 'No task.')}</p>`;
761
+ const docs = (M.docs.rows || []).filter((d) => !d.tech).map((d) => `<div class="hx-row" data-ov-doc="${esc(d.key)}"><span class="hx-t"><b>${esc(d.title)}</b><em>${esc([d.state, d.by, d.when || (d.added ? 'added ' + d.added : '')].filter(Boolean).join(' · '))}</em>${d.link ? `<small>${esc(d.link.kind + ': ' + d.link.url)}</small>` : ''}</span>${d.path && d.st === 'draft' && d.slot ? `<button type="button" class="hx-b" data-ov-dread="${esc(d.key)}">Read</button>` : d.path ? `<button type="button" class="hx-b" data-ov-open="${esc(d.path)}" data-ov-name="${esc(d.title)}">Open</button>` : ''}${d.act && d.act.kind === 'draft' && !d.running ? `<button type="button" class="hx-b pri" data-ov-draft="${esc(d.key)}">Draft it</button>` : d.running ? '<em class="hx-n">Drafting</em>' : ''}</div>`).join('');
762
+ b.innerHTML = MORE.WAIT + `<div class="hv-acts"><button type="button" class="hx-b" data-ov-record>Open the full record</button>${M.board && M.board.id ? '<button type="button" class="hx-b" data-ov-sprint>Sprint</button>' : ''}</div><section class="hx-sec"><h4>Stage</h4>${move}<div class="hv-acts">${life}</div></section>`
763
+ + `<section class="hx-sec"><h4>Tasks</h4>${tasks}<div class="hx-add"><input id="ovTask" placeholder="Add a task" aria-label="Add a task"><button type="button" class="hx-b pri" data-ov-add>Add</button></div></section>`
764
+ + `<section class="hx-sec"><h4>Core documents</h4>${M.docs.cap ? `<p class="hx-n" data-ov-dsum>${esc(M.docs.cap)}</p>` : ''}${docs || '<p class="hx-n">No core document.</p>'}<div class="hv-acts"><button type="button" class="hx-b" data-ov-adddoc>Add a document</button></div></section><p class="hx-n" role="status" id="ovMsg"></p>`;
765
+ };
766
+ const body = VW.open({ id: 'ov:' + id, kind: 'Overview', title: iniTitle(id), icon: 'goal', render: draw });
767
+ if (!M) { body.innerHTML = MORE.WAIT + '<p class="hx-n" role="status">Reading the initiative.</p>'; loadIni().then(() => { if (S.ini !== id || !body.isConnected) return; M = S.IM; draw(body); drawList(); }); } // a slow first read: read it again rather than say it failed
768
+ const bw = () => ({ ws: M.board.ws, board: M.board.id });
769
+ const after = async (r, ok) => { if (r && r.ok !== false) { toast(ok); await load(); if (S.ini === id && S.IM) M = S.IM; draw(body); } else { const m = body.querySelector('#ovMsg'); if (m) m.textContent = (r && r.error) || 'Nothing was changed.'; } };
770
+ body.onclick = async (e) => {
771
+ const t = e.target.closest('button'); if (!t || !M) return;
772
+ if (t.dataset.ovMove) { if (t.getAttribute('aria-pressed') === 'true') return; after(await pmPost('/api/boards/move', { ...bw(), id, to: t.dataset.ovMove }), 'Moved to ' + t.dataset.ovMove + '.'); return; }
773
+ if (t.dataset.ovLife === 'active') { after(await pmPost('/api/lifecycle', { ws: M.board.ws, initiative_id: id, state: 'active', reason: '' }), 'Recorded.'); return; }
774
+ if (t.dataset.ovLife) { ask = t.dataset.ovLife; draw(body); const w = body.querySelector('#ovWhy'); if (w) w.focus(); return; } // the reason is asked inline, not in a browser dialog
775
+ if ('ovLifeNo' in t.dataset) { ask = null; draw(body); return; }
776
+ if ('ovLifeGo' in t.dataset) { const reason = (body.querySelector('#ovWhy').value || '').trim(); if (reason.length < 3) { const m = body.querySelector('#ovMsg'); if (m) m.textContent = 'Say why in a few words. It goes on the record.'; return; } const st = ask; ask = null; after(await pmPost('/api/lifecycle', { ws: M.board.ws, initiative_id: id, state: st, reason }), 'Recorded.'); return; }
777
+ if ('ovAdd' in t.dataset) { const v = body.querySelector('#ovTask').value.trim(); if (v) after(await pmPost('/api/boards/tasks/add', { ...bw(), initiative: id, title: v }), 'Task added.'); return; }
778
+ if (t.dataset.ovDraft) { after(await pmPost('/api/core-docs/draft', { ws: M.board.ws, scope: M.docs.scope, key: t.dataset.ovDraft }), 'The draft started. It waits for you to read.'); return; }
779
+ if (t.dataset.ovOpen) openFile({ path: t.dataset.ovOpen, name: t.dataset.ovName });
780
+ if (t.dataset.ovTk || 'ovRecord' in t.dataset || 'ovSprint' in t.dataset) { // the record, a task or a Jira ticket, the sprint: the Viewer's own views
781
+ const o = { ws: M.board.ws, board: M.board.id };
782
+ if ('ovSprint' in t.dataset) { (await import('./premium-vw-jira.js')).openSprint(o); return; }
783
+ if ('ovRecord' in t.dataset) { (await import('./premium-vw-item.js')).openWorkItem({ kind: 'initiative', id, title: M.title, ...o }); return; }
784
+ const row = (M.tasks.rows || []).find((x) => x.key === t.dataset.ovTk); if (!row) return;
785
+ if (!row.pmos && row.ref) { (await import('./premium-vw-jira.js')).openTicket({ ...o, initiative: id, ref: row.ref }); return; }
786
+ (await import('./premium-vw-item.js')).openWorkItem({ kind: 'task', ini: id, key: row.key, title: row.title, ...o });
787
+ return;
788
+ }
789
+ if (t.dataset.ovDread) { // a draft: read it, edit it, Issue it (home-draft.js, in the Viewer's card shape)
790
+ const d = (M.docs.rows || []).find((x) => x.key === t.dataset.ovDread); if (!d) return;
791
+ const A = await import('./home-draft.js');
792
+ A.openDraftVw({ VW, pmGet, pmPost, toast, ws: M.board.ws, scope: M.docs.scope, doc: d, onIssued: () => load() });
793
+ return;
794
+ }
795
+ if ('ovAdddoc' in t.dataset) { // the form in the Viewer (home-adddoc.js): it posts to /api/custom-docs/add only
796
+ const A = await import('./home-adddoc.js');
797
+ A.openAddDocVw({ VW, pmPost, toast, ws: M.board.ws, scope: M.docs.scope, phases: (M.acts && M.acts.stages) || [], title: iniTitle(id), back: () => openOverview(), onAdded: async () => { await load(); if (S.ini === id) openOverview(); } });
798
+ }
799
+ };
800
+ body.onchange = async (e) => { const s = e.target.closest('[data-ov-task]'); if (s) after(await pmPost('/api/boards/tasks/state', { ...bw(), task: s.dataset.ovTask, state: s.value }), 'Status changed.'); };
801
+ }
802
+ async function openFile(f) {
803
+ const V = window.czViews || {};
804
+ if (typeof V.openDoc === 'function') { try { return V.openDoc(f.path, { ws: deskWs() }); } catch { /* the plain view below */ } }
805
+ // a Markdown document opens as its page (premium-vw-doc.js): read, edit, its edit log, health, relations and copies, in the Viewer
806
+ const fws = () => (S.ini && S.IM && S.IM.board && S.IM.board.ws) || deskWs(); // an initiative's document lives in its board's workspace
807
+ if (/\.md$/i.test(f.path)) { try { const M = await import('./premium-vw-doc.js'); if (M.openDocPage({ path: f.path, title: f.name || f.path.split('/').pop() }, { ws: () => fws() })) return; } catch { /* the plain view below */ } }
808
+ const body = VW.open({ id: 'file:' + f.path, kind: 'File · ' + f.path, title: f.name || f.path, icon: 'doc', html: '<p class="hx-n hv">Reading the file.</p>' });
809
+ let txt = null;
810
+ try { const r = await fetch('/api/doc?path=' + encodeURIComponent(f.path) + (deskWs() ? '&ws=' + encodeURIComponent(deskWs()) : ''), { credentials: 'same-origin' }); txt = r.ok ? await r.text() : null; } catch { txt = null; }
811
+ if (VW.current() && VW.current().id === 'file:' + f.path) body.innerHTML = txt == null ? '<p class="hx-n hv">The file could not be read.</p>' : `<article class="hv hv-doc">${mdHtml(txt.replace(/^---\n[\s\S]*?\n---\n/, ''))}</article>`;
812
+ }
813
+ function openPerson(p) {
814
+ const id = S.ini;
815
+ const body = VW.open({ id: 'person:' + p.name, kind: 'Stakeholder', title: p.name, icon: 'info', html: `<div class="hv">${factsHtml([['Role', p.role], ['Note', p.note], ['Added', p.at ? new Date(p.at).toDateString() : '']].filter((x) => x[1]))}<div class="hv-acts"><button type="button" class="hx-b" data-hv-rmp>Remove from ${esc(iniTitle(id))}</button></div></div>` });
816
+ body.onclick = async (e) => { if (!e.target.closest('[data-hv-rmp]')) return; const r = await pmPost('/api/home-desk/stakeholder', { ws: deskWs(), initiative: id, name: p.name, remove: true }); if (r && r.ok) { VW.close(); await load(); } else toast((r && r.error) || 'Not removed.'); };
817
+ }
818
+ function addPerson() {
819
+ const id = S.ini;
820
+ const body = VW.open({ id: 'person:new', kind: 'Stakeholder', title: 'Add a stakeholder to ' + iniTitle(id), icon: 'info',
821
+ html: '<div class="hv"><label class="hv-why"><span>Name</span><input id="hpN" autocomplete="off"></label><label class="hv-why"><span>Role</span><input id="hpR" placeholder="e.g. Head of Sales"></label><label class="hv-why"><span>Note</span><input id="hpT" placeholder="What they care about"></label><div class="hv-acts"><button type="button" class="hx-b pri" data-hv-addp>Add</button></div></div>' });
822
+ setTimeout(() => { const i = body.querySelector('#hpN'); if (i) i.focus(); }, 0);
823
+ body.onclick = async (e) => {
824
+ if (!e.target.closest('[data-hv-addp]')) return;
825
+ const name = body.querySelector('#hpN').value.trim(); if (!name) return;
826
+ const r = await pmPost('/api/home-desk/stakeholder', { ws: deskWs(), initiative: id, name, role: body.querySelector('#hpR').value.trim(), note: body.querySelector('#hpT').value.trim() });
827
+ if (r && r.ok) { toast('Added ' + name + '.'); VW.close(); await load(); } else toast((r && r.error) || 'Not added.');
828
+ };
829
+ }
830
+ /* ── the metrics review (AgMetrics): the Strategist's conversation, and the review in the Viewer: three tiles, the correction rate by week
831
+ * (the current week in blue) and what moved it. Every number is a record of the product's repository (GET /api/board-metrics-premium:
832
+ * corrections from its run log, merges from its trunk, blocked from its workflow state); a measure that is not read says so. ── */
833
+ const STRAT = { key: 'strategy', name: 'Strategist', initial: 'St' };
834
+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
835
+ const isMetrics = (s) => /metric/i.test(String((s && [s.task, s.skill, s.name, s.label].filter(Boolean).join(' ')) || ''));
836
+ const isMetricsSession = (s) => /^chat:metrics-review/.test(H.keyOfSession(s) || '') || (H.roleOf(s, S.D.desk && S.D.desk.roles).key === 'strategy' && /metric/i.test((s.hx && s.hx.title) || s.name || ''));
837
+ let MET = null;
838
+ async function metricsModel() {
839
+ if (MET && MET.model && Date.now() - MET.at < 60000) return MET.model;
840
+ const b = (S.D.board && S.D.board.board) || {};
841
+ const r = await getRetry('/api/board-metrics-premium?weeks=8' + (b.ws ? '&ws=' + encodeURIComponent(b.ws) : wsQ('&')), 6);
842
+ MET = { at: Date.now(), model: r && r.ok && r.model ? r.model : null, error: r && !r.ok ? r.error || 'the metrics were not read' : '' };
843
+ return MET.model;
844
+ }
845
+ /** The review from the metrics model: { tiles, bars, moved, line }. Pure over the model and the product card. */
846
+ function metricsView(m) {
847
+ const T = (k) => ((m && m.tiles) || []).find((t) => t.key === k) || null;
848
+ const two = (v) => (v == null ? null : (v / 100).toFixed(2)); // per 100 runs → per agent run, as the mockup reads it
849
+ const cor = T('corrections'), mer = T('merges'), blk = T('blocked');
850
+ const ser = cor && !cor.absent ? cor.ser : [];
851
+ const idx = ser.map((v, i) => (v != null ? i : -1)).filter((i) => i >= 0);
852
+ const cur = idx.length ? ser[idx[idx.length - 1]] : null, prev = idx.length > 1 ? ser[idx[idx.length - 2]] : null;
853
+ const tile = (t, label, value, note) => (!t ? null : t.absent ? { label, value: '–', note: t.absent } : { label, value, note });
854
+ const tiles = [
855
+ tile(cor, 'Correction rate', two(cur), prev != null ? 'Was ' + two(prev) + ' the week before' : cor && cor.text),
856
+ tile(mer, 'Merged a week', mer && mer.value, mer && (mer.change ? mer.change.txt : mer.text)),
857
+ tile(blk, 'Blocked', blk && blk.value, blk && blk.text),
858
+ ].filter(Boolean);
859
+ const last6 = ser.slice(-6), wk = (cor && cor.wk ? cor.wk : []).slice(-6);
860
+ const mx = Math.max(0, ...last6.filter((v) => v != null)) || 1;
861
+ const bars = last6.map((v, i) => ({ v: v == null ? '–' : two(v), h: v == null ? 0 : Math.max(4, Math.round(v / mx * 100)), w: 'W' + (i + 1), week: wk[i] || '', now: i === last6.length - 1 }));
862
+ const moved = ((m && m.tiles) || []).filter((t) => !t.absent && t.change && t.change.txt !== 'No change').map((t) => [t.label + (t.text ? ' · ' + t.text : ''), t.change.txt]);
863
+ for (const x of H.productCard(S.D, S.D.now).items.filter((i) => i.kind === 'risk')) moved.push([x.label, 'At risk']);
864
+ const month = MONTHS[new Date(S.D.now).getMonth()];
865
+ const line = cur == null ? month + ': no week has enough agent runs to count a correction rate yet.'
866
+ : month + ' in one line: the correction rate ' + (prev == null ? 'is ' + two(cur) + ' per agent run' : prev === cur ? 'held at ' + two(cur) + ' per agent run' : (cur < prev ? 'fell' : 'rose') + ' from ' + two(prev) + ' to ' + two(cur) + ' per agent run' + (cur < prev ? ', the direction you want' : ', the wrong direction')) + '.'
867
+ + (moved.length ? ' ' + moved.length + (moved.length === 1 ? ' thing' : ' things') + ' moved this month.' : '');
868
+ return { tiles, bars, moved, line, month, empty: !m };
869
+ }
870
+ function openMetricsViewer() {
871
+ const draw = (b) => {
872
+ const m = MET && MET.model, V = metricsView(m);
873
+ if (!m) { b.innerHTML = `<div class="hv"><p class="hx-n" role="status">${MET && MET.error ? 'The metrics were not read: ' + esc(MET.error) + '.' : 'Reading the metrics.'}</p></div>`; return; }
874
+ b.innerHTML = `<div class="hv hm-met"><div class="hm-kpis">${V.tiles.map((t) => `<div class="hm-kpi"><p>${esc(t.label)}</p><b>${esc(t.value)}</b><span>${esc(t.note || '')}</span></div>`).join('')}</div>`
875
+ + (V.bars.length ? `<figure class="hm-fig"><figcaption>Correction rate per agent run, by week (lower is better)</figcaption><div class="hm-chart" role="img" aria-label="${esc('Correction rate by week: ' + V.bars.map((x) => x.w + ' ' + x.v).join(', '))}">${V.bars.map((x) => `<div title="${esc(x.week ? 'Week to ' + x.week : x.w)}"><span>${esc(x.v)}</span><i class="${x.now ? 'now' : ''}" data-h="${x.h}"></i></div>`).join('')}</div><div class="hm-chx" aria-hidden="true">${V.bars.map((x) => `<span>${x.w}</span>`).join('')}</div></figure>` : '')
876
+ + `<table class="hm-moved"><thead><tr><th scope="col">What moved it</th><th scope="col">Effect</th></tr></thead><tbody>${V.moved.map(([n, e]) => `<tr><td>${esc(n)}</td><td>${esc(e)}</td></tr>`).join('') || '<tr><td colspan="2">Nothing moved since the week before.</td></tr>'}</tbody></table>`
877
+ + `<p class="hx-n">${esc((m && m.note) || '')}</p></div>`;
878
+ b.querySelectorAll('.hm-chart i[data-h]').forEach((i) => i.style.setProperty('--bd-h', i.dataset.h + 'px')); // each bar's height: run-time geometry
879
+ };
880
+ const body = VW.open({ id: 'metrics', kind: 'Metrics review', title: H.productName(S.D) + ' · ' + MONTHS[new Date(S.D.now).getMonth()], icon: I.chart, url: selfUrl({ ini: 'product', view: 'metrics' }), render: draw });
881
+ if (!(MET && MET.model)) metricsModel().then(() => { if (VW.current() && VW.current().id === 'metrics' && body.isConnected) draw(body); });
882
+ }
883
+ function metricsTarget() {
884
+ const V = metricsView(MET && MET.model);
885
+ return { key: 'chat:metrics-review', ini: 'product', ws: WS || undefined, title: 'Metrics review', sub: 'Strategist · ' + V.month, scope: scopeOf('product'), rich: rich(), role: STRAT, to: null,
886
+ intro: { role: STRAT, text: MET ? V.line : 'Reading the metrics of ' + H.productName(S.D) + '.', pills: [{ label: 'Open the review', primary: true, go: () => openMetricsViewer() }, { label: 'Discuss', go: () => chat.focus() }] },
887
+ context: 'The metrics review of ' + H.productName(S.D) + ': ' + V.tiles.map((t) => t.label + ' ' + t.value + (t.note ? ' (' + t.note + ')' : '')).join('; ') + '. What moved: ' + (V.moved.map((x) => x.join(' ')).join('; ') || 'nothing') + '.',
888
+ placeholder: 'Ask Strategist about the metrics', also: null };
889
+ }
890
+ async function openMetrics(o = {}) {
891
+ const id = S.sel;
892
+ openTarget(metricsTarget());
893
+ if (!o.keepViewer && !isPhone()) openMetricsViewer();
894
+ await metricsModel();
895
+ if (S.sel !== id) return;
896
+ openTarget(metricsTarget());
897
+ }
898
+ function openRoutine(s) {
899
+ VW.open({ id: 'routine:' + (s.id || s.name), kind: 'Routine', title: String(s.name || s.task || s.skill || 'Routine'), icon: 'cal',
900
+ html: `<div class="hv">${MORE.WAIT}${factsHtml([['Task', s.task || s.skill], ['Next run', s.next ? new Date(s.next).toString().slice(0, 21) : 'Not scheduled'], ['Repeats', s.cron || s.every || s.when || ''], ['On', s.enabled === false ? 'Off' : 'On']].filter((x) => x[1]))}</div>` });
901
+ }
902
+
903
+ /* the agent's terminal, read only, in the Viewer (term-view.js) */
904
+ function openTerminal(sid) {
905
+ const s = S.D.sessions.find((x) => x.id === sid);
906
+ import('./term-view.js').then((M) => M.openTermView(sid, { title: s ? (s.hx && s.hx.title) || s.name : sid }));
907
+ }
908
+
909
+ /* ── meetings and the calendar (the Viewer's own modules, through window.czViews) ── */
910
+ const views = import('./premium-vw-open.js').catch(() => null);
911
+ async function V() { await views; return window.czViews || {}; }
912
+ async function openMeeting(m) {
913
+ const v = await V();
914
+ if (typeof v.openMeeting === 'function') return v.openMeeting(m.note ? { note: m.note } : m, { ws: deskWs() });
915
+ try { const M = await import('./premium-vw-mtg.js'); return M.openMeeting(m.note ? { note: m.note } : m, { ws: deskWs() }); } catch { return VW.placeholder('Meeting', { icon: 'meet' }); }
916
+ }
917
+ async function openCalendar() {
918
+ const v = await V();
919
+ if (typeof v.openCalendar === 'function') return v.openCalendar({ ws: deskWs(), view: 'day' });
920
+ return VW.placeholder('Calendar', { icon: 'cal' });
921
+ }
922
+
923
+ /* the record dot shows a recording that is on: this page's recorder, or a note the server holds as recording */
924
+ let REC = null;
925
+ import('./premium-meeting.js').then((M) => { REC = M.recCore({ pmGet, pmPost, ws: () => WS || null }); REC.refresh().then(() => drawList()); }).catch(() => { REC = null; });
926
+ addEventListener('premium-rec', () => drawList());
927
+ function recLive() {
928
+ if (!REC) return null;
929
+ const h = REC.holding && REC.holding();
930
+ const n = (REC.notes() || []).find((x) => (h && x.id === h.id) || x.state === 'recording');
931
+ return n ? { id: n.id, title: n.title } : h ? { id: h.id, title: '' } : null;
932
+ }
933
+
934
+ /* ── New, end, kids ── */
935
+ function newItems() {
936
+ const here = S.ini && S.ini !== 'product' ? S.ini : null;
937
+ const inis = H.boardRows(S.D);
938
+ return [
939
+ { label: 'Next step of an initiative', sub: 'Open where it waits', go: (b) => menu(b, inis.map((r) => ({ label: r.title, sub: r.stage, go: () => goIni(r.id) })), 'Which initiative') },
940
+ { label: here ? 'New session in ' + iniTitle(here) : 'New session in an initiative', sub: 'A fresh chat with its own history', go: (b) => (here ? newIn(here) : menu(b, inis.map((r) => ({ label: r.title, sub: r.stage, go: () => newIn(r.id) })), 'In which initiative')) },
941
+ { label: 'Quick ask', sub: 'Your own chat, about all work', go: () => { goHome(); chat.focus(); } },
942
+ { label: 'Something unrelated', sub: 'A loose chat; link it later', go: () => newLoose() },
943
+ { label: 'Record a note now', sub: 'A conversation that is not on the calendar', go: () => MORE.openRecorder().then(() => drawList()) },
944
+ ];
945
+ }
946
+ function newIn(id) {
947
+ const used = new Set(S.D.sessions.map((s) => H.keyOfSession(s)).filter(Boolean));
948
+ let n = 2; while (used.has('init:' + id + ':' + n)) n++;
949
+ if (S.ini !== id) { S.ini = id; drawList(); loadIni().then(drawList); syncUrl(); }
950
+ S.sel = null;
951
+ openTarget({ ...iniTarget(id), key: 'init:' + id + ':' + n, title: 'New session · ' + iniTitle(id), empty: 'A new session in ' + iniTitle(id) + '. Say what it is for.' });
952
+ chat.focus();
953
+ }
954
+ function newLoose() {
955
+ const d = new Date(), p = (x) => String(x).padStart(2, '0');
956
+ const key = 'chat:loose-' + d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '-' + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds());
957
+ if (S.ini) { S.ini = null; drawList(); syncUrl(); }
958
+ S.sel = null;
959
+ openTarget({ key, ws: WS || undefined, title: 'New chat', scope: { text: 'Loose', icon: I.chat, loose: true }, rich: false, placeholder: 'Message Claude', empty: 'A loose chat. Link it to an initiative when it turns into one.', onSent: () => setTimeout(load, 1500) });
960
+ chat.focus();
961
+ }
962
+ async function endRow(id) {
963
+ const r = rowById(id); if (!r) return;
964
+ if (r.kind === 'session' && r.sid) {
965
+ // an inline confirmation (no browser dialog): the first press arms the ×, a second press within five seconds ends the session
966
+ if (S.endArm !== id) { S.endArm = id; clearTimeout(S.endT); S.endT = setTimeout(() => { S.endArm = null; }, 5000); toast('Press × again to end ' + r.name + '. Its conversation is kept.'); return; }
967
+ S.endArm = null;
968
+ const res = await pmPost('/api/session/remove', { id: r.sid });
969
+ if (!res || !res.ok) { toast((res && res.error) || 'The session did not end.'); return; }
970
+ toast('Ended. The conversation is kept.');
971
+ } else if (r.kind === 'need') {
972
+ const res = await bpPost('put-off', { key: r.key, until: 'tomorrow' });
973
+ if (!res.ok) { toast(res.error); return; }
974
+ toast('Put off until tomorrow. It comes back by itself.');
975
+ }
976
+ if (S.sel === id) S.sel = null;
977
+ await load();
978
+ }
979
+
980
+ /* ── the small menus (one at a time; Escape closes it first) ── */
981
+ const menuEl = $('#hmMenu');
982
+ let menuItems = [];
983
+ function menu(anchor, items, label) {
984
+ menuItems = items;
985
+ // an item: { label, sub?, go, disabled? } and, for the products picker and Later (HmProducts, HmDecide): tile (initials), checked
986
+ // (a radio item with its check), icon (a path), k (the time on the right), or { sep: true } for a hairline
987
+ const itemHtml = (x, i) => {
988
+ if (x.sep) return '<div class="ut-hr" role="separator"></div>';
989
+ const rich = x.tile || x.checked != null || x.icon || x.k;
990
+ const role = x.checked != null ? `role="menuitemradio" aria-checked="${!!x.checked}"` : 'role="menuitem"';
991
+ if (!rich) return `<button type="button" ${role} data-hm-mi="${i}"${x.disabled ? ' disabled' : ''}><b>${esc(x.label)}</b>${x.sub ? `<em>${esc(x.sub)}</em>` : ''}</button>`;
992
+ return `<button type="button" ${role} class="ut-mi${x.tile ? ' tall' : ''}" data-hm-mi="${i}"${x.disabled ? ' disabled' : ''}>${x.tile ? `<span class="ut-it${x.primary ? ' p' : ''}" aria-hidden="true">${esc(x.tile)}</span>` : ''}${x.icon ? TD.svg(x.icon, 16) : ''}`
993
+ + `<span><b>${esc(x.label)}</b>${x.sub ? `<em>${esc(x.sub)}</em>` : ''}</span>${x.k ? `<span class="k">${esc(x.k)}</span>` : ''}${x.checked ? TD.svg(TD.P.check, 16) : ''}</button>`;
994
+ };
995
+ menuEl.innerHTML = (label ? `<p class="hm-ml">${esc(label)}</p>` : '') + items.map(itemHtml).join('') || '<p class="hm-ml">Nothing to choose.</p>';
996
+ menuEl.hidden = false; menuEl.setAttribute('data-esc-layer', '');
997
+ // the menu sits under (or over) the button that opened it: CSS anchor positioning reads .hm-anc, so no geometry is set from here
998
+ if (menu.anchor && menu.anchor !== anchor) menu.anchor.classList.remove('hm-anc');
999
+ anchor.classList.add('hm-anc');
1000
+ menu.anchor = anchor;
1001
+ menuEl.classList.toggle('top', !!anchor.closest('.hm-top')); // the phone's ⋯ menu drops from its button at the top right
1002
+ const f = menuEl.querySelector('button'); if (f) f.focus();
1003
+ }
1004
+ function closeMenu() { if (menuEl.hidden) return; menuEl.hidden = true; menuEl.removeAttribute('data-esc-layer'); if (menu.anchor) menu.anchor.classList.remove('hm-anc'); if (menu.anchor && menu.anchor.isConnected) menu.anchor.focus(); }
1005
+ menuEl.onclick = (e) => { // delegated: every item is a <button role=menuitem>
1006
+ const b = e.target.closest('[data-hm-mi]'); if (!b) return;
1007
+ const it = menuItems[+b.dataset.hmMi]; const a = menu.anchor;
1008
+ menuEl.hidden = true; menuEl.removeAttribute('data-esc-layer'); if (a) a.classList.remove('hm-anc');
1009
+ if (it && it.go) it.go(a);
1010
+ };
1011
+ document.addEventListener('click', (e) => { if (!menuEl.hidden && !menuEl.contains(e.target) && !(menu.anchor && menu.anchor.contains(e.target))) closeMenu(); }, true);
1012
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !menuEl.hidden) { e.stopPropagation(); closeMenu(); } else if (e.key === 'Escape' && S.sheet) sheet(false); }, true);
1013
+ function moreMenu(anchor) {
1014
+ const go = {
1015
+ work: () => MORE.openMyWork(), around: () => MORE.openAround(), inbox: () => MORE.openInbox(searchGo), eod: () => MORE.openEndOfDay(), cal: () => openCalendar(),
1016
+ rec: () => MORE.openRecorder(), search: () => MORE.openSearch(searchGo), products: () => MORE.openProducts(), sources: () => MORE.openSources(), settings: () => MORE.openSettings(),
1017
+ };
1018
+ menu(anchor, MORE.moreItems.map(([k, l]) => ({ label: l, go: go[k] })), 'Waiting for design');
1019
+ }
1020
+ function searchGo(d) {
1021
+ if (d.ini) goIni(d.ini);
1022
+ else if (d.doc) openFile({ path: d.doc, name: d.doc.split('/').pop() });
1023
+ else if (d.ses) { const s = S.D.sessions.find((x) => x.id === d.ses); if (s) { S.sel = 's:' + s.id; openTarget(sessionTarget(s)); drawList(); } }
1024
+ else if (d.link) location.href = d.link;
1025
+ }
1026
+
1027
+ /* ── the phone sheet ── */
1028
+ function sheet(on) {
1029
+ S.sheet = !!on;
1030
+ document.body.classList.toggle('hm-sheet', S.sheet);
1031
+ $('#hmNeeds').setAttribute('aria-expanded', String(S.sheet));
1032
+ if (S.sheet) { const f = $('#hmList button'); if (f) f.focus(); }
1033
+ }
1034
+ $('#hmNeeds').onclick = () => sheet(!S.sheet);
1035
+ // a phone: the back bar of a conversation returns to the list, which is the page (HmPhone2)
1036
+ // My work's "Weekly review" (home-work.js) asks Home, which holds the data the review reads
1037
+ addEventListener('hm:review', (e) => { e.preventDefault(); openReviewVw(); });
1038
+ $('#hmBack').onclick = () => { S.phoneChat = false; S.sel = null; drawList(); syncUrl(); const f = $('#hmList .hm-rm'); if (f) f.focus(); };
1039
+ $('#hmMoreP').onclick = (e) => moreMenu(e.currentTarget);
1040
+ $('#hmDesk').onclick = (e) => { if (S.sheet && e.target === $('#hmDesk')) sheet(false); }; // a press beside the sheet closes it; Escape and the N need you button do too
1041
+
1042
+ /* ── presses on the list ── */
1043
+ $('#hmList').onclick = (e) => { // delegated: every press on the list is a <button>
1044
+ const b = e.target.closest('button'); if (!b) return;
1045
+ const d = b.dataset;
1046
+ if (d.hmSel) { select(d.hmSel); return; }
1047
+ if (d.hmKids) { // the chevron of an initiative: what sits under it shows or hides
1048
+ if (b.getAttribute('aria-expanded') === 'true') { S.kids.delete(d.hmKids); S.kidsOff.add(d.hmKids); } else { S.kids.add(d.hmKids); S.kidsOff.delete(d.hmKids); }
1049
+ drawList(); const f = $(`#hmList [data-hm-kids="${CSS.escape(d.hmKids)}"]`); if (f) f.focus(); return;
1050
+ }
1051
+ if (d.hmPg) { const open = b.getAttribute('aria-expanded') === 'true'; S.pg[d.hmPg] = !open; store.set('pmos.home.pg', JSON.stringify(S.pg)); drawList(); const f = $(`#hmList [data-hm-pg="${CSS.escape(d.hmPg)}"]`); if (f) f.focus(); return; }
1052
+ if ('hmProd' in d) { goIni('product'); return; }
1053
+ if (d.hmRest) { if (S.rest.has(d.hmRest)) S.rest.delete(d.hmRest); else S.rest.add(d.hmRest); drawList(); return; }
1054
+ if (d.hmFilter) { S.filter = d.hmFilter; drawList(); const f = $(`#hmList [data-hm-filter="${d.hmFilter}"]`); if (f) f.focus(); return; }
1055
+ if (d.hmCheck) { checkRow(d.hmCheck); return; }
1056
+ if ('hmReview' in d) { openReviewVw(); return; }
1057
+ if ('hmWork' in d) { MORE.openMyWork(); return; }
1058
+ if ('hmPick' in d) { pickProduct(b); return; }
1059
+ if ('hmCapmic' in d) { const i = $('#hmCap'); if (i) capMic(i, b); return; }
1060
+ if (d.hmTc) { todayPress(d.hmTc, b); return; }
1061
+ if (d.hmEnd) { endRow(d.hmEnd); return; }
1062
+ if (d.hmGroup) { if (S.shut.has(d.hmGroup)) S.shut.delete(d.hmGroup); else S.shut.add(d.hmGroup); store.set('pmos.home.shut', JSON.stringify([...S.shut])); drawList(); return; }
1063
+ if ('hmAllneeds' in d) { S.allNeeds = !S.allNeeds; drawList(); return; }
1064
+ if ('hmNew' in d) { menu(b, newItems(), 'What is it for?'); return; }
1065
+ if ('hmFold' in d) { S.folded = true; store.set('pmos.home.fold', '1'); drawList(); return; }
1066
+ if ('hmMeet' in d) { const m = H.meetLineOf(S.D.today); if (m) openMeeting(m.meeting); return; }
1067
+ if ('hmCal' in d) { openCalendar(); return; }
1068
+ if ('hmRec' in d) { MORE.openRecorder().then(() => drawList()); return; }
1069
+ if (d.hmRecopen) { openMeeting({ note: d.hmRecopen }); return; }
1070
+ if ('hmSwitch' in d) { menu(b, [{ label: 'Home', sub: 'All work', go: () => goHome() }].concat(scopeItems().slice(1), S.ini ? [{ label: 'Add a stakeholder', sub: 'To ' + iniTitle(S.ini), go: () => addPerson() }] : []), 'Switch'); return; }
1071
+ if ('hmNewin' in d) { if (S.ini === 'product') { openTarget(updateTarget()); chat.focus(); } else newIn(S.ini); return; }
1072
+ if ('hmDone' in d) { S.doneOpen = !S.doneOpen; drawList(); return; }
1073
+ if ('hmCfold' in d) { S.cardFold = !S.cardFold; store.set('pmos.home.cardfold', S.cardFold ? '1' : null); drawList(); const f = $('#hmList [data-hm-cfold]'); if (f) f.focus(); return; }
1074
+ if ('hmCta' in d) { cta(); return; }
1075
+ if ('hmOv' in d) { if (S.ini === 'product') openUpdateViewer(); else openOverview(); return; }
1076
+ if ('hmElse' in d) { const f = S.lay && S.lay.elsewhere && S.lay.elsewhere.first; goHome(); if (f) select(f.id); return; }
1077
+ if ('hmPerson' in d) addPerson();
1078
+ };
1079
+ $('#hmList').addEventListener('submit', async (e) => { // the capture box: Enter adds the task
1080
+ if (e.target.id !== 'hmCapF') return;
1081
+ e.preventDefault();
1082
+ const i = $('#hmCap'); if (!i || !i.value.trim()) return;
1083
+ i.disabled = true;
1084
+ const ok = await capture(i.value);
1085
+ const j = $('#hmCap'); if (j) { j.disabled = false; if (ok) j.value = ''; j.focus(); }
1086
+ });
1087
+ /* the mic of the capture box: the words are typed into it, nothing is saved as audio (home-dictate.js) */
1088
+ let capDict = null;
1089
+ function capMic(input, b) {
1090
+ if (capDict && capDict.on()) { capDict.stop(); return; }
1091
+ capDict = dictate(input, { onState: (x) => {
1092
+ const btn = $('#hmList [data-hm-capmic]'), form = $('#hmCapF');
1093
+ if (btn) { btn.classList.toggle('on', !!x.on); btn.setAttribute('aria-label', x.on ? 'Stop listening' : 'Say it instead'); }
1094
+ if (form) form.classList.toggle('on', !!x.on);
1095
+ if (x.error) toast(x.error);
1096
+ } });
1097
+ b.classList.add('on');
1098
+ }
1099
+ /* the Today card's presses (HmDay, HmMic): the calendar, the meeting's prep, the live meeting, the recording, the end of the day */
1100
+ async function todayPress(k, b) {
1101
+ const T = todayModel();
1102
+ if (k === 'cal') { openCalendar(); return; }
1103
+ if ((k === 'prep' || k === 'open') && T.meeting) { openMeeting(T.meeting); return; }
1104
+ if (k === 'record') { MORE.openRecorder().then(() => drawList()); return; }
1105
+ if (k === 'hl') { const r = REC && await REC.highlight(); toast(r && r.ok ? 'Highlighting the last 30 seconds and the next ones.' : (r && r.error) || 'The highlight did not start.'); return; }
1106
+ if (k === 'pause' || k === 'resume' || k === 'stop') {
1107
+ if (!REC || T.mode !== 'rec') return;
1108
+ b.disabled = true;
1109
+ const r = k === 'pause' ? await REC.pause() : k === 'resume' ? await REC.resume(T.id) : await REC.stop(T.id);
1110
+ if (!r || !r.ok) toast((r && r.error) || 'The recording did not change.');
1111
+ else if (k === 'stop') toast(r.discarded ? 'Stopped. Nothing was said, so nothing was kept.' : 'Stopped. The notes are under Not in an initiative until you link them.');
1112
+ await REC.refresh(); drawList();
1113
+ if (k === 'stop') load();
1114
+ return;
1115
+ }
1116
+ if (k === 'hide') { S.eodHidden = true; store.set('pmos.home.eod', L.dayOf()); drawList(); return; }
1117
+ if (k === 'now' && T.block) { select(T.block.id); return; }
1118
+ if (k === 'tomorrow' && T.block && T.block.key) {
1119
+ const res = await bpPost('put-off', { key: T.block.key, until: 'tomorrow' });
1120
+ if (!res.ok) { toast(res.error); return; }
1121
+ toast('Tomorrow 09:00. It comes back by itself, and it is not counted as done.');
1122
+ load();
1123
+ }
1124
+ }
1125
+ $('#hmDesk').insertAdjacentHTML('afterbegin', `<button type="button" class="hm-unfold" id="hmUnfold" aria-label="Show the list" title="Show the list">${SVG(I.fold, 16)}</button>`);
1126
+ $('#hmUnfold').onclick = () => { S.folded = false; store.set('pmos.home.fold', null); drawList(); };
1127
+ function cta() {
1128
+ if (S.ini === 'product') { const C = H.productCard(S.D); if (C.sent) openUpdateViewer(); else { select('n:update'); } return; }
1129
+ const h = S.H || {};
1130
+ if (h.need) { select(h.need.id); return; }
1131
+ const t = iniTarget(S.ini);
1132
+ openTarget(t);
1133
+ if (h.ask) chat.send(h.ask);
1134
+ }
1135
+
1136
+ /* ── start ── */
1137
+ mountIni({ S, VW, pmGet, pmPost, toast, load: () => load(), loadIni: () => loadIni(), openFile: (f) => openFile(f), iniTitle: (id) => iniTitle(id), drawList: () => drawList(), wait: MORE.WAIT });
1138
+ mountNav('home', document, { more: () => moreMenu, settings: () => MORE.openSettings() });
1139
+ PHC = mountPhoneCard({ pmGet, pmPost, toast, ws: () => WS || null, openMeeting: (m) => openMeeting(m) }); drawList();
1140
+ drawList(); drawTop();
1141
+ { // a conversation the address names opens at once, before the lists are read, so nothing typed or attached lands in the Home chat
1142
+ const a = P.get('about') || '', early = /^(decision|blocked|waited|src|ev|work|board|doc|ins|chat|pop):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/.test(a) && !P.get('open') && !P.get('session') ? a : null;
1143
+ const sidAt = !early && !P.get('open') && /^[A-Za-z0-9._:-]{1,120}$/.test(P.get('session') || ''); // a session link: read nothing until its session is known, so Home's own chat never shows first
1144
+ if (early || sidAt) { S.phoneChat = isPhone(); drawList(); } // a phone: a conversation the address names is the page, not the list (HmPhone2)
1145
+ openTarget(early ? { ...homeTarget(), key: early, title: (P.get('label') || '').slice(0, 80) || early }
1146
+ : sidAt ? { ...homeTarget(), key: '', title: 'Reading', empty: 'Reading the session.' }
1147
+ : S.ini ? (S.ini === 'product' ? { ...homeTarget(), title: 'Reading' } : iniTarget(S.ini)) : homeTarget());
1148
+ }
1149
+ /* The address: ?ini=<id> an initiative's layout · ?open=<row key> a Needs-you row · ?session=<id> a session · ?ask=<initiative id> | board:<key> |
1150
+ * insights | verdict with the question in ?q, or ?about=<key>&label=<name>: that conversation · ?open=report:|chart:|dashboard:<id> that one in the
1151
+ * Viewer · ?say=<words> or ?q a first message in the box, not sent · ?meeting=<note id> the meeting card. */
1152
+ const KEY = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins|chat|pop):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/;
1153
+ load().then(() => {
1154
+ const open = P.get('open') || P.get('item'), sid = P.get('session'), mt = P.get('meeting');
1155
+ const ask = P.get('ask') || '';
1156
+ const blockOpen = /^(report|chart|dashboard):([A-Za-z0-9][A-Za-z0-9._:-]{0,119})$/.exec(open || '');
1157
+ const say = (P.get('say') || P.get('q') || '').slice(0, 500);
1158
+ const asked = !ask ? '' : /^board:/.test(ask) ? ask : /^(insights|verdict)$/.test(ask) ? 'ins:' + ask : 'init:' + ask;
1159
+ const about = KEY.test(P.get('about') || '') ? P.get('about') : KEY.test(asked) ? asked : null;
1160
+ if (isPhone() && ((open && !blockOpen) || sid || about)) { S.phoneChat = true; drawList(); } // the conversation the address names, not the list
1161
+ if (open && !blockOpen) { const r = allRows().find((x) => x.key === open); if (r) select(r.id); else if (KEY.test(open)) openTarget({ ...homeTarget(), key: open, title: open }); }
1162
+ else if (sid) { const s = S.D.sessions.find((x) => x.id === sid); if (s) { S.sel = 's:' + s.id; openTarget(sessionTarget(s)); drawList(); } else { openTarget(homeTarget()); toast('That session is not on this machine.'); } }
1163
+ else if (about && /^init:/.test(about) && iniRowOf(about.slice(5))) goIni(about.slice(5));
1164
+ else if (about) openTarget({ ...homeTarget(), key: about, title: (P.get('label') || '').slice(0, 80) || about });
1165
+ else if (S.ini && P.get('view') === 'metrics') goIni(S.ini).then(() => openMetrics()); // ?view=metrics: the metrics review, as its Open in a new tab names it
1166
+ else if (S.ini) goIni(S.ini);
1167
+ else if (!isPhone() && !blockOpen && !say && !VW.isOpen()) { const first = H.needsOf(S.D)[0]; if (first) select(first.id); } // a card the PM opened while Home was reading stays
1168
+ if (blockOpen) {
1169
+ const b = { kind: blockOpen[1], id: blockOpen[2] };
1170
+ (b.kind === 'report' ? import('./premium-report-tab.js').then((M) => M.openReportTab(b)) : import('./premium-chart-tab.js').then((M) => M.openChartTab(b))).catch(() => toast('That view could not open.'));
1171
+ }
1172
+ if (say) setTimeout(() => { const ta = $('#hmIn'); if (ta) { ta.value = say; ta.dispatchEvent(new Event('input', { bubbles: true })); ta.focus(); ta.setSelectionRange(say.length, say.length); } }, 0);
1173
+ if (mt) openMeeting({ note: mt });
1174
+ if (/^(prop|men|pulse|scan|rep|src)$/.test(P.get('around') || '')) MORE.openAround(P.get('around')); // ?around=<row>: that Around you view (home-around.js)
1175
+ poll();
1176
+ });
1177
+ addEventListener('resize', () => { if (!isPhone() && S.sheet) sheet(false); drawList(); });
1178
+ // Ctrl K (Cmd K) opens Search in the Viewer, as the ⋯ menu's Search does
1179
+ addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (e.key === 'k' || e.key === 'K')) { e.preventDefault(); MORE.openSearch(searchGo); } });