create-pmos 0.396.0 → 0.398.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 (177) 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/scripts/nine-stages.js +49 -20
  6. package/payload/state/discoveries.md +1 -1
  7. package/payload/state/log.md +1 -1
  8. package/workspace/briefing-premium-adddoc-test.js +103 -74
  9. package/workspace/briefing-premium-board-test.js +316 -154
  10. package/workspace/briefing-premium-calendar-2-test.js +135 -195
  11. package/workspace/briefing-premium-calendar-3-test.js +143 -413
  12. package/workspace/briefing-premium-calendar-test.js +86 -185
  13. package/workspace/briefing-premium-doc-edit-test.js +95 -83
  14. package/workspace/briefing-premium-initiative-test.js +166 -294
  15. package/workspace/briefing-premium-insights-test.js +351 -214
  16. package/workspace/briefing-premium-metrics-test.js +53 -118
  17. package/workspace/briefing-premium-products-test.js +40 -27
  18. package/workspace/briefing-premium-sources-test.js +91 -52
  19. package/workspace/briefing-premium-test.js +150 -633
  20. package/workspace/briefing-premium-work-test.js +88 -269
  21. package/workspace/changelog.json +24 -0
  22. package/workspace/fixtures/board-premium-facts.js +2 -1
  23. package/workspace/fixtures/board-premium-jira.js +28 -0
  24. package/workspace/fixtures/board-premium-trail.js +32 -0
  25. package/workspace/fixtures/initiative-premium-facts.js +2 -1
  26. package/workspace/fixtures/initiatives-api/list.json +30 -42
  27. package/workspace/fixtures/initiatives-api/roadmap.json +40 -56
  28. package/workspace/fixtures/initiatives-api/sheet.json +10 -14
  29. package/workspace/fixtures/insights-premium-facts.js +11 -2
  30. package/workspace/fixtures/premium-viewer-fixtures.js +182 -0
  31. package/workspace/guide/briefing-premium.md +3 -1
  32. package/workspace/guide/home.md +47 -0
  33. package/workspace/guide/index.md +2 -0
  34. package/workspace/guide/lifecycle.md +51 -0
  35. package/workspace/home-shot.js +38 -0
  36. package/workspace/lib/agent-roles.js +71 -0
  37. package/workspace/lib/board-premium.js +160 -3
  38. package/workspace/lib/board-trail.js +223 -0
  39. package/workspace/lib/engine/boards.js +15 -14
  40. package/workspace/lib/engine/nine-stages.js +49 -20
  41. package/workspace/lib/engine/signals/detectors.js +13 -11
  42. package/workspace/lib/home-work-item.js +58 -0
  43. package/workspace/lib/insights-goals.js +196 -0
  44. package/workspace/lib/insights-premium.js +126 -1
  45. package/workspace/lib/insights-records.js +101 -0
  46. package/workspace/lib/jira-tickets.js +1 -1
  47. package/workspace/lib/route-modules.js +4 -0
  48. package/workspace/lib/routes-board-premium.js +3 -2
  49. package/workspace/lib/routes-board-trail.js +33 -0
  50. package/workspace/lib/routes-home-desk.js +176 -0
  51. package/workspace/lib/routes-initiatives.js +1 -1
  52. package/workspace/lib/routes-insights-premium.js +19 -3
  53. package/workspace/lib/routes-insights-records.js +129 -0
  54. package/workspace/lib/routes-notes.js +1 -0
  55. package/workspace/lib/routes-viewer.js +108 -0
  56. package/workspace/lib/transcript-steps.js +123 -0
  57. package/workspace/lib/vendor/scripts/nine-stages.js +49 -20
  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-agreed-viewer-shots.js +76 -0
  63. package/workspace/premium-board-actions-test.js +85 -73
  64. package/workspace/premium-briefing-depth-test.js +66 -53
  65. package/workspace/premium-chat-attach-test.js +54 -63
  66. package/workspace/premium-chat-chart-tab-test.js +35 -36
  67. package/workspace/premium-chat-context-test.js +22 -19
  68. package/workspace/premium-chat-goal-view-test.js +28 -26
  69. package/workspace/premium-chat-notes-test.js +29 -33
  70. package/workspace/premium-chat-report-tab-test.js +35 -25
  71. package/workspace/premium-chat-term-test.js +16 -14
  72. package/workspace/premium-chat-viewer-test.js +60 -53
  73. package/workspace/premium-core-doc-issue-test.js +50 -41
  74. package/workspace/premium-html-viewer-test.js +17 -18
  75. package/workspace/premium-phone-card-test.js +8 -2
  76. package/workspace/premium-phone-room-test.js +42 -31
  77. package/workspace/premium-report-read-test.js +115 -197
  78. package/workspace/premium-viewer-download-test.js +19 -22
  79. package/workspace/premium-viewer-flicker-test.js +11 -16
  80. package/workspace/premium-viewer-share-test.js +6 -9
  81. package/workspace/premium-viewer-test.js +41 -60
  82. package/workspace/premium-vw-backlog-test.js +53 -31
  83. package/workspace/premium-vw-cal-test.js +82 -123
  84. package/workspace/premium-vw-copy-test.js +17 -33
  85. package/workspace/premium-vw-doc-test.js +12 -11
  86. package/workspace/premium-vw-item-test.js +50 -48
  87. package/workspace/premium-vw-jira-test.js +55 -26
  88. package/workspace/premium-vw-meet-test.js +118 -187
  89. package/workspace/premium-vw-notes-test.js +85 -107
  90. package/workspace/premium-vw-rec-test.js +72 -193
  91. package/workspace/premium-vw-slides-test.js +46 -50
  92. package/workspace/premium-welcome-test.js +3 -2
  93. package/workspace/premium-work-depth-test.js +63 -51
  94. package/workspace/public/pm/bd-acts.js +305 -0
  95. package/workspace/public/pm/bd-span.js +224 -0
  96. package/workspace/public/pm/bd-stages.js +47 -0
  97. package/workspace/public/pm/c3-doc-sheet.js +1 -1
  98. package/workspace/public/pm/c3-md.js +3 -395
  99. package/workspace/public/pm/c3-phone-detail.js +1 -1
  100. package/workspace/public/pm/c3-phone-model.js +3 -68
  101. package/workspace/public/pm/chat-term.js +3 -3
  102. package/workspace/public/pm/cozy-board.css +640 -0
  103. package/workspace/public/pm/cozy-home.css +580 -0
  104. package/workspace/public/pm/cozy-home.js +172 -0
  105. package/workspace/public/pm/cozy-initiative.css +138 -0
  106. package/workspace/public/pm/cozy-insights.css +421 -0
  107. package/workspace/public/pm/cozy-md.js +396 -0
  108. package/workspace/public/pm/cozy-nav.js +65 -0
  109. package/workspace/public/pm/cozy-placeholder.js +26 -0
  110. package/workspace/public/pm/cozy-viewer.css +143 -0
  111. package/workspace/public/pm/cozy-viewer.js +144 -0
  112. package/workspace/public/pm/cozy-vw.css +485 -0
  113. package/workspace/public/pm/cozy.css +254 -0
  114. package/workspace/public/pm/home-adddoc.js +48 -0
  115. package/workspace/public/pm/home-app.js +905 -0
  116. package/workspace/public/pm/home-around.js +515 -0
  117. package/workspace/public/pm/home-chat.js +459 -0
  118. package/workspace/public/pm/home-data.js +312 -0
  119. package/workspace/public/pm/home-draft.js +68 -0
  120. package/workspace/public/pm/home-more.js +249 -0
  121. package/workspace/public/pm/home-phone-card.js +109 -0
  122. package/workspace/public/pm/home-work.js +519 -0
  123. package/workspace/public/pm/lifecycle-lens-model.js +45 -27
  124. package/workspace/public/pm/lifecycle-lens.js +22 -11
  125. package/workspace/public/pm/phone-moment.js +69 -0
  126. package/workspace/public/pm/pm-work-view.js +1 -1
  127. package/workspace/public/pm/premium-attach.js +4 -0
  128. package/workspace/public/pm/premium-board.js +544 -253
  129. package/workspace/public/pm/premium-brief.js +1 -1
  130. package/workspace/public/pm/premium-chart-tab.js +110 -62
  131. package/workspace/public/pm/premium-chat.js +17 -10
  132. package/workspace/public/pm/premium-deck.js +3 -3
  133. package/workspace/public/pm/premium-first.js +25 -21
  134. package/workspace/public/pm/premium-initiative-head.js +138 -0
  135. package/workspace/public/pm/premium-initiative.js +28 -4
  136. package/workspace/public/pm/premium-insights.js +950 -440
  137. package/workspace/public/pm/premium-meeting.js +61 -549
  138. package/workspace/public/pm/premium-notes.js +1 -1
  139. package/workspace/public/pm/premium-report-frame.css +20 -0
  140. package/workspace/public/pm/premium-report-read.js +509 -480
  141. package/workspace/public/pm/premium-report-tab.js +87 -63
  142. package/workspace/public/pm/premium-shell.js +107 -124
  143. package/workspace/public/pm/premium-viewer.js +27 -1
  144. package/workspace/public/pm/premium-vw-cal.js +187 -48
  145. package/workspace/public/pm/premium-vw-doc.css +6 -0
  146. package/workspace/public/pm/premium-vw-doc.js +40 -2
  147. package/workspace/public/pm/premium-vw-file.js +2 -2
  148. package/workspace/public/pm/premium-vw-jira-model.js +22 -5
  149. package/workspace/public/pm/premium-vw-jira.css +11 -0
  150. package/workspace/public/pm/premium-vw-jira.js +11 -4
  151. package/workspace/public/pm/premium-vw-meet.js +6 -83
  152. package/workspace/public/pm/premium-vw-mtg.js +731 -0
  153. package/workspace/public/pm/premium-vw-notes.js +56 -69
  154. package/workspace/public/pm/premium-vw-open.js +35 -0
  155. package/workspace/public/pm/premium-vw-page.js +16 -0
  156. package/workspace/public/pm/premium-vw-rec.js +11 -215
  157. package/workspace/public/pm/premium-vw-slides.css +5 -0
  158. package/workspace/public/pm/premium-vw-slides.js +44 -8
  159. package/workspace/public/pm/term-view.js +22 -0
  160. package/workspace/public/premium-board.html +57 -64
  161. package/workspace/public/premium-chat.html +7 -33
  162. package/workspace/public/premium-initiative.html +8 -41
  163. package/workspace/public/premium-insights.html +63 -62
  164. package/workspace/public/premium-viewer.html +20 -0
  165. package/workspace/public/premium-work.html +6 -72
  166. package/workspace/public/premium.html +21 -66
  167. package/workspace/public/vendor/nunito-var.woff2 +0 -0
  168. package/workspace/server.js +25 -3
  169. package/workspace/test-files.json +1 -0
  170. package/workspace/test-lists/home-libs.json +9 -0
  171. package/workspace/test-lists/premium-agreed-viewer.json +9 -0
  172. package/workspace/test-lists/premium-report-read.json +1 -1
  173. package/workspace/test-lists/premium-vw-agreed.json +9 -0
  174. package/workspace/test-lists/premium-vw-notes.json +1 -1
  175. package/workspace/third-party/README.md +1 -0
  176. package/workspace/public/pm/premium-work.js +0 -719
  177. package/workspace/public/pm/premium.js +0 -1133
@@ -0,0 +1,905 @@
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*).
3
+ *
4
+ * One desk. The list on the left: Today with New and the fold, the meeting line (+N, the record dot), then only three groups, Needs you
5
+ * (the top 3 and "N more · Show"), Initiatives (the product first) and Loose. An initiative is a layout of this page (?ini=<id>): its card
6
+ * sits at the top of the list with its own groups and the Elsewhere card under it. The chat is in the middle (home-chat.js) and the Viewer
7
+ * on the right (cozy-viewer.js). On a phone the chat is the page; the top bar names what is open and "N need you" opens the list as a sheet.
8
+ *
9
+ * The models are in home-data.js (pure). This file reads the routes, draws, and wires the presses. Every write is the PM's press (pmPost).
10
+ * The features the design does not draw yet open from a quiet entry (the ⋯ menu on a phone, the place menu on desktop) as minimal
11
+ * versions with a "Waiting for design" marker (home-more.js). Nothing here opens the old dialog or links to the console. */
12
+ import { mountNav } from './cozy-nav.js';
13
+ import * as VW from './cozy-viewer.js';
14
+ import { pmGet, pmPost, pmHeaders } from './http.js';
15
+ import * as H from './home-data.js';
16
+ import { mountChat, avHtml } from './home-chat.js';
17
+ import * as MORE from './home-more.js';
18
+ import { headModel, STEPS } from './premium-initiative-head.js';
19
+ import { startAgent } from './page-agent.js';
20
+ import { mdHtml } from './chat-md.js';
21
+ import { mountPhoneCard } from './home-phone-card.js';
22
+ import { mountFirst } from './premium-first.js';
23
+
24
+ const $ = (s, r = document) => r.querySelector(s);
25
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
26
+ const P = new URLSearchParams(location.search);
27
+ const WS = P.get('ws') || '';
28
+ let PHC = null; // the phone moment card (home-phone-card.js): the top of the phone's sheet
29
+ const FST = mountFirst(); // the first-run card after an import (?first=<import id>, premium-first.js): the top of the list, Waiting for design
30
+ const wsQ = (pre = '?') => (WS ? pre + 'ws=' + encodeURIComponent(WS) : '');
31
+ const BOARD = P.get('board') || ''; // the Board's expand link names its board: Home reads that board, not the default one
32
+ const boardQ = (pre = '?') => (BOARD ? pre + 'board=' + encodeURIComponent(BOARD) : '');
33
+ const PHONE = 760;
34
+ const isPhone = () => innerWidth <= PHONE;
35
+ 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>`;
36
+ const I = {
37
+ 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',
38
+ 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',
39
+ 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',
40
+ 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',
41
+ 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',
42
+ };
43
+ 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 };
44
+ const COMMS = { key: 'comms', name: 'Communicator', initial: 'Co' };
45
+ const CLAUDE = { key: 'claude', name: 'Claude', initial: 'C' };
46
+ const RET_REASONS = ['wrong facts', 'wrong scope', 'not now', 'too long'];
47
+ const store = {
48
+ get(k) { try { return localStorage.getItem(k); } catch { return null; } },
49
+ set(k, v) { try { if (v == null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch { /* a private window */ } },
50
+ };
51
+
52
+ /* ── theme ── */
53
+ (function theme() {
54
+ const t = P.get('theme') || store.get('pmos.c3.theme');
55
+ const dark = t === 'dark' || (t !== 'light' && matchMedia && matchMedia('(prefers-color-scheme: dark)').matches);
56
+ document.documentElement.dataset.theme = dark ? 'dark' : 'light';
57
+ if (P.get('theme')) store.set('pmos.c3.theme', P.get('theme'));
58
+ }());
59
+
60
+ /* ── state ── */
61
+ const S = {
62
+ D: { now: Date.now(), sessions: [], err: [], files: [] }, ready: false,
63
+ ini: P.get('ini') || null, // the initiative layout ('product' for the product)
64
+ sel: null, // the selected row's id
65
+ allNeeds: false, kids: new Set(), shut: new Set(JSON.parse(store.get('pmos.home.shut') || '[]')), folded: store.get('pmos.home.fold') === '1',
66
+ IM: null, IMid: null, // the selected initiative's model (GET /api/initiative-premium)
67
+ doneOpen: false, sheet: false, rec: {}, pin: new Set(JSON.parse(store.get('pmos.home.pin') || '[]')),
68
+ cardFold: store.get('pmos.home.cardfold') === '1', // the card's checklist folded to one line (AgInitSpec), kept in this browser
69
+ };
70
+ const toast = (t) => { const el = $('#toast'); el.textContent = t; el.classList.add('on'); clearTimeout(toast.t); toast.t = setTimeout(() => el.classList.remove('on'), 4200); };
71
+
72
+ /* ── reading ── */
73
+ async function getRetry(path, tries = 20) {
74
+ for (let i = 0; i < tries; i++) {
75
+ const r = await pmGet(path);
76
+ if (!(r && (r.state === 'reading' || r.status === 202 || r.pending && !r.model))) return r;
77
+ await new Promise((ok) => setTimeout(ok, 2500));
78
+ }
79
+ return { ok: false, error: 'still reading' };
80
+ }
81
+ async function load() {
82
+ const [brief, board, ses, desk, today, sch] = await Promise.all([
83
+ getRetry('/api/briefing-premium' + wsQ()), getRetry('/api/board-premium' + wsQ() + boardQ(WS ? '&' : '?')), pmGet('/api/sessions'), pmGet('/api/home-desk' + wsQ()),
84
+ pmGet('/api/brief-page' + wsQ()), pmGet('/api/schedules' + wsQ()),
85
+ ]);
86
+ const D = S.D;
87
+ D.brief = brief && brief.ok && brief.model ? brief.model : null;
88
+ D.board = board && board.ok && board.model ? board.model : null;
89
+ D.sessions = ses && Array.isArray(ses.sessions) ? ses.sessions : [];
90
+ D.desk = desk && desk.ok ? desk : null;
91
+ D.today = today && today.ok ? today : null;
92
+ D.schedules = sch && Array.isArray(sch.schedules) ? sch : null;
93
+ D.now = Date.now();
94
+ D.err = [brief, board].filter((x) => !x || !x.ok).map((x) => (x && x.error) || 'the server did not answer');
95
+ const rows = H.boardRows(D);
96
+ if (rows.length) {
97
+ const b = (D.board && D.board.board) || {};
98
+ 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('&')));
99
+ D.trail = tr && tr.ok ? tr : null;
100
+ }
101
+ S.ready = true;
102
+ await loadIni();
103
+ draw();
104
+ }
105
+ async function loadIni() {
106
+ const id = S.ini;
107
+ if (!id || id === 'product') { S.IM = null; S.IMid = id; S.D.files = []; return; }
108
+ const b = (S.D.board && S.D.board.board) || {};
109
+ 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);
110
+ S.IM = r && r.ok && r.model ? r.model : null; S.IMid = id;
111
+ 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
112
+ 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(' · ') })) : [];
113
+ }
114
+ let pollT = null;
115
+ function poll() {
116
+ clearTimeout(pollT);
117
+ pollT = setTimeout(async () => {
118
+ if (!document.hidden) {
119
+ const [ses, desk] = await Promise.all([pmGet('/api/sessions'), pmGet('/api/home-desk' + wsQ())]);
120
+ if (ses && Array.isArray(ses.sessions)) S.D.sessions = ses.sessions;
121
+ if (desk && desk.ok) S.D.desk = desk;
122
+ S.D.now = Date.now();
123
+ drawList(); drawTop();
124
+ }
125
+ poll();
126
+ }, 8000);
127
+ }
128
+ setInterval(() => { if (!document.hidden) load(); }, 300000);
129
+ window.addEventListener('hm:reload', () => load());
130
+
131
+ /* ── the list ── */
132
+ const dotCls = (st) => ({ needs: 'you', blocked: 'late', working: 'ok run' }[st] || 'none');
133
+ function tileHtml(r) {
134
+ if (r.kind === 'session' || r.kind === 'person') return avHtml(r.role || { initial: r.initial || 'C' }, 30, 'hm-tile');
135
+ if (r.kind === 'update') return `<span class="hm-tile">${SVG(I.doc, 14)}</span>`;
136
+ return `<span class="hm-tile">${SVG(ROW_ICON[r.icon] || I.chat, 14)}</span>`;
137
+ }
138
+ function rowHtml(r, o = {}) {
139
+ const sel = S.sel === r.id;
140
+ 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>`
141
+ : 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>` : '';
142
+ 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>` : '';
143
+ 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>` : '';
144
+ return `<div class="hm-r${sel ? ' sel' : ''}${o.kid ? ' kid' : ''} st-${esc(r.state)}" data-id="${esc(r.id)}">`
145
+ + `<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)}`
146
+ + `<span class="hm-rt"><b>${esc(r.name)}</b><em>${esc(r.hint || '')}</em></span></button>${chip}${end}</div>${kids}`;
147
+ }
148
+ function groupHtml(key, title, rows, extra = '', head = '') {
149
+ const shut = S.shut.has(key);
150
+ 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>`
151
+ + (shut ? '' : rows.map((r) => rowHtml(r)).join('') + extra) + '</section>';
152
+ }
153
+ function meetHtml() {
154
+ const m = H.meetLineOf(S.D.today);
155
+ const live = recLive();
156
+ const rec = live ? `<button type="button" class="hm-mp rec on" data-hm-recopen="${esc(live.id)}" aria-label="Recording: ${esc(live.title || 'a meeting')}. Open it" title="Recording: ${esc(live.title || 'a meeting')}"><i aria-hidden="true"></i></button>`
157
+ : `<button type="button" class="hm-mp rec" data-hm-rec aria-label="Record a note now" title="Record a note now"><i aria-hidden="true"></i></button>`;
158
+ if (!m) return `<div class="hm-meet"><button type="button" class="hm-mt" data-hm-cal>${SVG(I.clock, 16)}<span><b>No meeting left today</b></span></button>${rec}</div>`;
159
+ return `<div class="hm-meet"><button type="button" class="hm-mt" data-hm-meet aria-label="${esc(m.aria)}">${SVG(I.clock, 16)}<span><b>${esc(m.time)}</b> ${esc(m.meeting.title)}${m.note ? ` · <em>${esc(m.note)}</em>` : ''}</span></button>`
160
+ + (m.more ? `<button type="button" class="hm-mp" data-hm-cal aria-label="${m.more} more ${m.more === 1 ? 'meeting' : 'meetings'} today. Open the calendar">+${m.more}</button>` : '') + rec + '</div>';
161
+ }
162
+ function homeListHtml() {
163
+ const L = H.homeLists(S.D, { allNeeds: S.allNeeds });
164
+ S.L = L;
165
+ const pinned = L.needs.rows.filter((r) => S.pin.has(r.key));
166
+ const needRows = pinned.concat(L.needs.rows.filter((r) => !S.pin.has(r.key)));
167
+ const more = !S.allNeeds && L.needs.more ? `<button type="button" class="hm-more" data-hm-allneeds>${L.needs.more} more · Show</button>` : S.allNeeds && L.needs.all > 3 ? '<button type="button" class="hm-more" data-hm-allneeds>Show fewer</button>' : '';
168
+ const err = !S.ready ? '<p class="hm-none" role="status">Reading your work.</p>' : S.D.err.length && !L.initiatives.length && !L.needs.all ? `<p class="hm-none" role="status">Home could not read the repository: ${esc(S.D.err[0])}.</p>` : '';
169
+ return `<div class="hm-hd"><h1>Today</h1><button type="button" class="hm-new" data-hm-new aria-haspopup="menu">${SVG(I.plus, 14, 2.2)}New</button>`
170
+ + `<button type="button" class="hm-ib" data-hm-fold aria-label="Fold the list" title="Fold the list">${SVG(I.fold, 16)}</button></div>`
171
+ + meetHtml() + err
172
+ + (L.needs.all ? groupHtml('needs', 'Needs you', needRows, more) : S.ready ? '<section class="hm-g"><p class="hm-none">Nothing needs you now.</p></section>' : '')
173
+ + (L.initiatives.length ? groupHtml('inis', 'Initiatives', L.initiatives) : '')
174
+ + (L.loose.length ? groupHtml('loose', 'Loose', L.loose) : '');
175
+ }
176
+
177
+ /* ── the initiative card ── */
178
+ function iniRowOf(id) { return H.boardRows(S.D).find((r) => r.id === id) || null; }
179
+ function headOf(id) {
180
+ const M = S.IM && S.IMid === id ? { ...S.IM } : { head: { stage: (iniRowOf(id) || {}).stage }, acts: (iniRowOf(id) || {}).acts || {} };
181
+ const t = S.D.trail && S.D.trail.items && S.D.trail.items[id];
182
+ const k = String((M.head && M.head.stage) || (iniRowOf(id) || {}).stage || '').toLowerCase();
183
+ const u = S.D.trail && S.D.trail.usual && S.D.trail.usual[k];
184
+ if (t && t.since) M.stageSince = t.since;
185
+ if (u && u.n >= 3 && u.days != null) M.usualDays = u.days;
186
+ const h = headModel(M, S.D.now);
187
+ // the Needs-you rows of this initiative make it the PM's turn too
188
+ const need = H.needsOf(S.D).find((r) => r.ini === id);
189
+ 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; }
190
+ if (!need && S.D.sessions.some((s) => H.iniOfSession(s) === id && s.shown === 'working') && h.turn === 'agents') h.primary = false;
191
+ return h;
192
+ }
193
+ /* 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
194
+ * 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. */
195
+ 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>'
196
+ : k === 'agent' && role ? avHtml(role, 20, 'hm-mk-av') : `<span class="hm-mk ${esc(k)}" aria-hidden="true"></span>`);
197
+ const TAG = { you: 'You', agent: 'Working', wait: 'Next', jira: 'Jira', risk: 'At risk' };
198
+ const itemHtml = (x, o = {}) => {
199
+ 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
200
+ const tag = k === 'agent' && o.stalled ? 'Stuck' : TAG[k];
201
+ 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>`;
202
+ };
203
+ const MS = '<i class="cz-ms" aria-hidden="true"></i>'; // the milestone mark (◆), drawn as a shape
204
+ const msStep = (label) => !!(STEPS.find((s) => s.label === label) || {}).ms;
205
+ /** "To reach ◆ Deliver": the milestone mark before a milestone's name in the checklist's title. */
206
+ 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); };
207
+ function cardHtml(id) {
208
+ const prod = id === 'product';
209
+ let kind, title, turn, turnLabel, stage, lad = '', bars = '', ckh, items, then, time, cta, primary, over = false, foldSum = '', msNext = false;
210
+ if (prod) {
211
+ const C = H.productCard(S.D, S.D.now);
212
+ kind = C.kind; title = C.name; turn = C.turn === 'you' ? 'you' : 'agents'; turnLabel = C.turn === 'you' ? 'Your turn' : 'Sent this week';
213
+ stage = C.stage; ckh = [C.title, C.of];
214
+ 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>';
215
+ then = C.payoff; time = C.time; cta = C.cta; primary = !C.sent;
216
+ const risk = C.items.filter((x) => x.kind === 'risk').length;
217
+ foldSum = C.of + (risk ? ' · ' + risk + ' at risk' : '');
218
+ } else {
219
+ const r = iniRowOf(id) || { title: (S.IM && S.IM.title) || id };
220
+ const h = headOf(id); S.H = h;
221
+ kind = [r.lane ? r.lane.charAt(0).toUpperCase() + r.lane.slice(1) : 'Feature', r.kr || r.anchor || ''].filter(Boolean).join(' · ');
222
+ title = r.title; turn = h.turn; turnLabel = h.turnLabel; stage = h.stage;
223
+ 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>`;
224
+ bars = `<div class="hm-bars" aria-hidden="true">${h.steps.map((s) => `<i class="${s.cls}"></i>`).join('')}</div>`;
225
+ ckh = [h.checkTitle, h.doneOf];
226
+ 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>` : '';
227
+ // the agent at work on this initiative: its avatar marks an agent step (AgInitAgents); with none at work the step is next
228
+ const at = S.D.sessions.find((s) => H.iniOfSession(s) === id && s.shown === 'working');
229
+ const io = { role: at ? H.roleOf(at, S.D.desk && S.D.desk.roles) : null, stalled: h.turn === 'stalled' };
230
+ items = doneRow + (S.doneOpen ? h.done.map((x) => itemHtml(x, io)).join('') : '') + h.rest.map((x) => itemHtml(x, io)).join('');
231
+ then = h.payoff; time = h.time; over = h.over; cta = h.cta; primary = h.primary;
232
+ foldSum = h.foldSum; msNext = msStep(h.toReach);
233
+ }
234
+ 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>`
235
+ + `<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>`
236
+ + `<button type="button" class="hm-ib sm" data-hm-switch aria-hidden="true" tabindex="-1">${SVG(I.down, 14, 2)}</button>`
237
+ + `<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>`
238
+ + `<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>`
239
+ + lad + bars
240
+ // the checklist folds to one line (AgInitSpec): its title, the summary and a chevron; Then and the time line show only unfolded
241
+ + (S.cardFold
242
+ ? `<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>`
243
+ : `<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}`
244
+ + (then ? `<p class="hm-then"><b>Then:</b> ${esc(then)}</p>` : '')
245
+ + (time ? `<p class="hm-time${over ? ' over' : ''}">${SVG(I.clock, 13)}${esc(time)}</p>` : ''))
246
+ + `<div class="hm-acts"><button type="button" class="hm-cta${primary ? '' : ' alt'}" data-hm-cta>${esc(cta)}</button>`
247
+ + `<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>`;
248
+ }
249
+ function iniListHtml() {
250
+ const id = S.ini;
251
+ const lay = H.iniLayout(S.D, id);
252
+ if (id === 'product') { // the product's sessions are its update and its own chats
253
+ const g = lay.groups.find((x) => x.key === 'sessions');
254
+ const upd = S.D.sessions.filter((s) => H.keyOfSession(s) === H.UPDATE_KEY.slice(5) || H.keyOfSession(s) === H.UPDATE_KEY);
255
+ if (upd.length && !g) lay.groups.splice(1, 0, { key: 'sessions', title: 'Sessions', rows: [] });
256
+ }
257
+ // 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)
258
+ 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('');
259
+ S.lay = lay;
260
+ return cardHtml(id) + groups;
261
+ }
262
+ /** The Elsewhere card of an initiative's layout: pinned to the bottom of the list column, under the groups, never over them. */
263
+ function elseHtml() {
264
+ const e = S.ini && S.lay && S.lay.elsewhere;
265
+ 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>` : '';
266
+ }
267
+ function drawList() {
268
+ const el = $('#hmList');
269
+ // the list column: the groups scroll; the Elsewhere card is the column's foot (AgInitSpec, AgInitPhone)
270
+ let sc = el.querySelector(':scope > .hm-lsc'), ft = el.querySelector(':scope > .hm-lft');
271
+ if (!sc || !ft) { el.innerHTML = '<div class="hm-lsc"></div><div class="hm-lft"></div>'; sc = el.firstElementChild; ft = el.lastElementChild; }
272
+ const html = S.ini ? iniListHtml() : homeListHtml();
273
+ if (sc.__h !== html) { const st = sc.scrollTop; sc.__h = html; sc.innerHTML = html; sc.scrollTop = st; }
274
+ const fh = elseHtml();
275
+ if (ft.__h !== fh) { ft.__h = fh; ft.innerHTML = fh; }
276
+ // the first-run card after an import tops the list; the phone moment card (not in the Agreed design, Waiting for design) sits after the groups
277
+ if (FST && sc.firstElementChild !== FST) sc.prepend(FST);
278
+ if (PHC && sc.lastElementChild !== PHC.el) sc.append(PHC.el);
279
+ document.body.classList.toggle('hm-folded', S.folded && !isPhone());
280
+ }
281
+
282
+ function draw() { drawList(); drawTop(); chat.refresh(); }
283
+
284
+ /* ── rows by id ── */
285
+ function allRows() {
286
+ const out = [];
287
+ const L = S.L || H.homeLists(S.D, { allNeeds: true });
288
+ const add = (r) => { if (!r) return; out.push(r); (r.kids || []).forEach(add); };
289
+ H.needsOf(S.D).forEach(add); L.initiatives.forEach(add); L.loose.forEach(add);
290
+ if (S.lay) S.lay.groups.forEach((g) => g.rows.forEach(add));
291
+ 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); }
292
+ return out;
293
+ }
294
+ const rowById = (id) => allRows().find((r) => r.id === id) || null;
295
+
296
+ /* ── the top bar (phone) ── */
297
+ function drawTop() {
298
+ const n = H.needsOf(S.D).length;
299
+ const cur = S.cur || { title: 'Home', sub: '' };
300
+ $('#hmTopTitle').textContent = cur.title; $('#hmTopSub').textContent = cur.sub || '';
301
+ $('#hmNeedsN').textContent = !S.ready ? 'Reading' : n ? n + (n === 1 ? ' needs you' : ' need you') : 'Your list';
302
+ $('#hmNeeds').classList.toggle('loud', n > 0);
303
+ document.title = 'PMOS · ' + (cur.title || 'Home');
304
+ }
305
+
306
+ /* ── the chat ── */
307
+ const chat = mountChat($('#hmChat'), {
308
+ esc, toast, pmGet, pmPost, pressHeaders: () => { const h = pmHeaders(); delete h['Content-Type']; return h; },
309
+ roles: () => (S.D.desk && S.D.desk.roles) || [],
310
+ seen: (key) => (S.D.desk && S.D.desk.seen && S.D.desk.seen[key]) || null,
311
+ 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 }; }); },
312
+ session: (id) => S.D.sessions.find((s) => s.id === id) || null,
313
+ queued: (sid) => (sid && S.D.desk && S.D.desk.queued && S.D.desk.queued[sid]) || [],
314
+ 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(); } }),
315
+ 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); },
316
+ onScope: (b) => menu(b, scopeItems(), 'Where this goes'),
317
+ 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'),
318
+ onTo: (b) => menu(b, toItems(), 'Who reads this'),
319
+ workItem: (text, t) => workItem(text, t),
320
+ openTerminal: (sid) => openTerminal(sid),
321
+ viewerClosed: () => !VW.isOpen() && !isPhone(),
322
+ wait: MORE.WAIT,
323
+ desk: () => !isPhone(),
324
+ reopenViewer: () => reopenViewer(),
325
+ });
326
+ function scopeItems() {
327
+ return [{ label: 'All work', sub: 'Home', go: () => select(null) }, { label: H.productName(S.D) + ' · product', go: () => goIni('product') }]
328
+ .concat(H.boardRows(S.D).map((r) => ({ label: r.title, sub: [r.lane, r.stage].filter(Boolean).join(' · '), go: () => goIni(r.id) })));
329
+ }
330
+ function toItems() {
331
+ const id = S.ini;
332
+ const ses = S.D.sessions.filter((s) => H.iniOfSession(s) === id && s.shown !== 'exited');
333
+ return [{ label: 'Claude', sub: 'The chat of this initiative', go: () => openTarget(iniTarget(id)) }]
334
+ .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)) }; }))
335
+ .concat([{ label: 'A new session', sub: 'Starts in ' + iniTitle(id), go: () => newIn(id) }]);
336
+ }
337
+ async function link(sid, ini) {
338
+ const r = await pmPost('/api/session/initiative', { id: sid, initiative: ini });
339
+ if (!r || !r.ok) { toast((r && r.error) || 'The session was not linked.'); return; }
340
+ toast('Linked to ' + iniTitle(ini) + '.'); await load(); goIni(ini);
341
+ }
342
+ async function workItem(text, t) {
343
+ const ini = (t && t.ini) || S.ini;
344
+ if (!ini || ini === 'product') { toast('Open the initiative this belongs to, then make the work-item there.'); return; }
345
+ const b = (S.D.board && S.D.board.board) || {};
346
+ const r = await pmPost('/api/home-desk/work-item', { ws: b.ws || WS || undefined, initiative: ini, text, key: (t && (t.key || t.sid)) || '' });
347
+ 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.');
348
+ }
349
+ const iniTitle = (id) => (id === 'product' ? H.productName(S.D) + ' · product' : (iniRowOf(id) || {}).title || (S.IM && S.IM.title) || id);
350
+ const scopeOf = (ini) => (ini ? { text: iniTitle(ini), icon: I.flag } : { text: 'All work', icon: I.home, loose: false });
351
+ const rich = () => !!S.ini;
352
+ function iniTarget(id) {
353
+ const h = S.H || {};
354
+ 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),
355
+ empty: 'Ask about ' + iniTitle(id) + '. Claude reads its records and works in a real Claude Code session.', also: alsoOf(id),
356
+ // the initiative's conversation opens on where it stands (AgInitYou), until it has messages of its own
357
+ 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 };
358
+ }
359
+ function sessionTarget(s) {
360
+ const key = H.keyOfSession(s);
361
+ const ini = H.iniOfSession(s);
362
+ const role = H.roleOf(s, S.D.desk && S.D.desk.roles);
363
+ 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) };
364
+ 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;
365
+ if (!t.key) t.sid = s.id;
366
+ return t;
367
+ }
368
+ function alsoOf(ini) {
369
+ const other = H.needsOf(S.D).filter((r) => !ini || r.ini !== ini || true).filter((r) => !(S.sel && S.sel === r.id));
370
+ const n = other.find((r) => r.ini === ini) || other[0];
371
+ return n ? { text: n.name, go: () => select(n.id) } : null;
372
+ }
373
+ function needTarget(r) {
374
+ const row = r.row, d = row.dialog || {};
375
+ const pills = [];
376
+ 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); } });
377
+ if (d.write && d.write.kind === 'start') pills.unshift({ label: 'Start the agent', primary: true, go: () => start(r) });
378
+ if (d.write && d.write.kind === 'return') pills.push({ label: 'Return it', go: () => openNeedViewer(r, true) });
379
+ pills.push({ label: 'Discuss', go: () => chat.focus() });
380
+ return { key: r.key, ini: r.ini, ws: WS || undefined, title: r.name, sub: r.hint || '', scope: scopeOf(r.ini), rich: rich(), role: CLAUDE,
381
+ intro: { role: CLAUDE, text: d.say || row.subject || row.title, pills }, placeholder: 'Ask about ' + r.name, also: null };
382
+ }
383
+ function updateTarget() {
384
+ const U = H.weeklyUpdate(S.D, S.D.now);
385
+ const flags = U.sections.flatMap(([, , L]) => L).filter((x) => x.flag);
386
+ 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.' : '');
387
+ const sent = (U.sent || []).find((x) => x.week === U.week.iso);
388
+ // the product's conversation shows its In: scope chip (AgProduct); To: is for a running role session only (AgChatRunning)
389
+ 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,
390
+ intro: { role: COMMS, text: sent ? 'This week\'s update went out from your mail on ' + new Date(sent.at).toDateString() + '.' : text,
391
+ pills: sent ? [{ label: 'Read it', primary: true, go: () => openUpdateViewer() }] : [{ label: 'Send now', primary: true, go: () => sendUpdate() }, { label: 'Edit', go: () => { openUpdateViewer(); chat.focus(); } }] },
392
+ 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.',
393
+ placeholder: 'Tell Communicator what to change', also: null };
394
+ }
395
+ function homeTarget() {
396
+ return { key: 'chat:main', ws: WS || undefined, title: 'Home', scope: { text: 'All work', icon: I.home }, rich: false, placeholder: 'Message Claude', role: CLAUDE,
397
+ empty: 'Ask anything about your work. Claude reads your repositories and works in a real Claude Code session.', also: alsoOf(null) };
398
+ }
399
+ function openTarget(t) {
400
+ S.cur = { title: t.title, sub: t.sub != null && t.sub !== '' ? t.sub : t.scope && t.scope.text !== t.title ? t.scope.text : '' };
401
+ chat.open(t); drawTop();
402
+ }
403
+
404
+ /* ── selection ── */
405
+ function select(id, o = {}) {
406
+ S.sel = id;
407
+ const r = id ? rowById(id) : null;
408
+ if (isPhone()) sheet(false);
409
+ if (!r) { if (S.ini) openTarget(iniTarget(S.ini)); else openTarget(homeTarget()); drawList(); return; }
410
+ if (r.kind === 'ini') { goIni(r.ini); return; }
411
+ if (r.kind === 'product') { goIni('product'); return; }
412
+ if (r.kind === 'update') { openTarget(updateTarget()); if (!o.keepViewer) openUpdateViewer(); }
413
+ else if (r.kind === 'need' && r.row) { openTarget(needTarget(r)); if (!o.keepViewer) openNeedViewer(r); }
414
+ 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(); } }
415
+ else if (r.kind === 'meeting') { openMeeting(r.meeting); }
416
+ else if (r.kind === 'routine') { if (isMetrics(r.schedule)) openMetrics(o); else openRoutine(r.schedule); }
417
+ else if (r.kind === 'file') { openFile(r.file); }
418
+ else if (r.kind === 'person') { openPerson(r.person); }
419
+ drawList();
420
+ syncUrl();
421
+ }
422
+ async function goIni(id) {
423
+ S.ini = id; S.sel = null; S.doneOpen = false;
424
+ if (isPhone()) sheet(false);
425
+ syncUrl();
426
+ drawList();
427
+ await loadIni();
428
+ if (S.ini !== id) return;
429
+ drawList();
430
+ if (id === 'product') { openTarget(updateTarget()); if (!VW.isOpen() && !isPhone()) openUpdateViewer(); }
431
+ else openTarget(iniTarget(id));
432
+ }
433
+ function goHome() { S.ini = null; S.sel = null; S.IM = null; syncUrl(); drawList(); openTarget(homeTarget()); }
434
+ function syncUrl() {
435
+ const q = new URLSearchParams(location.search);
436
+ ['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); });
437
+ if (S.ini) q.set('ini', S.ini);
438
+ const r = S.sel ? rowById(S.sel) : null;
439
+ if (r && r.key && r.kind !== 'session') q.set('open', r.key); else if (r && r.sid) q.set('session', r.sid);
440
+ const s = q.toString();
441
+ history.replaceState(null, '', location.pathname + (s ? '?' + s : ''));
442
+ }
443
+
444
+ /* ── the Viewer: needs rows, the weekly update, the overview, files, people, routines ── */
445
+ let lastViewer = null;
446
+ VW.onChange((d) => { if (d.open) lastViewer = d.id; chat.refresh(); document.body.classList.toggle('hm-vw-open', d.open); });
447
+ function reopenViewer() {
448
+ if (/^vw:/.test(lastViewer || '')) { import('./premium-viewer.js').then((M) => { if (!M.vwReopen()) { lastViewer = null; reopenViewer(); } }); return; } // the last file, chart or report shown
449
+ const r = S.sel ? rowById(S.sel) : null;
450
+ if (r) { select(r.id); return; }
451
+ if (S.ini === 'product') { openUpdateViewer(); return; }
452
+ if (S.ini) { openOverview(); return; }
453
+ MORE.openMyWork();
454
+ }
455
+ 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>` : ''; }
456
+ function openNeedViewer(r, focusWhy) {
457
+ const row = r.row, d = row.dialog || {}, w = d.write || {};
458
+ const st = S.rec[r.key] || (S.rec[r.key] = { choice: d.sel || null, why: '', ret: null });
459
+ const draw = (b) => {
460
+ const pane = d.pane || {};
461
+ const facts = factsHtml(pane.rows || d.facts || []);
462
+ // 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
463
+ const src = row.kind === 'source';
464
+ const intro = pane.intro ? `<p class="hv-intro">${src ? '<b>Why now</b> ' : ''}${esc(pane.intro)}</p>` : '';
465
+ 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>` : '';
466
+ 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>` : '';
467
+ let rec = '';
468
+ if (w.kind === 'decision') {
469
+ rec = `<section class="hv-sec"><h4>Your decision</h4><div class="hv-opts" role="radiogroup" aria-label="Choices">${(d.opts || []).map((o) => `<button type="button" role="radio" aria-checked="${st.choice === o.k}" data-hv-opt="${esc(o.k)}"><b>${esc(o.t)}</b>${o.d ? `<em>${esc(o.d)}</em>` : ''}</button>`).join('')}</div>`
470
+ + `<label class="hv-why"><span>Why</span><textarea id="hvWhy" rows="3" placeholder="The reason goes in pm-decisions.md with your choice">${esc(st.why)}</textarea></label>`
471
+ + `<div class="hv-acts"><button type="button" class="hx-b pri" data-hv-rec${st.choice && st.why.trim().length >= 3 ? '' : ' disabled'}>Record the decision</button>${laterHtml()}${pinHtml(r)}</div></section>`;
472
+ } else if (w.kind === 'return') {
473
+ rec = `<section class="hv-sec"><h4>Return this run: why</h4><div class="hv-seg">${RET_REASONS.map((x) => `<button type="button" aria-pressed="${st.ret === x}" data-hv-ret="${esc(x)}">${esc(x)}</button>`).join('')}</div>`
474
+ + `<div class="hv-acts"><button type="button" class="hx-b pri" data-hv-rec${st.ret ? '' : ' disabled'}>Return it to the agent</button>${laterHtml()}${pinHtml(r)}</div></section>`;
475
+ } else if (w.kind === 'start') {
476
+ 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>`;
477
+ } else rec = `<div class="hv-acts">${link}${src ? '' : laterHtml()}${pinHtml(r)}</div>`; // a source row cannot be put off (the server refuses it)
478
+ 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}${MORE.WAIT}${rec}<p class="hx-n" role="status" id="hvMsg"></p></div>`;
479
+ if (focusWhy) { const t = b.querySelector('#hvWhy'); if (t) setTimeout(() => t.focus(), 0); focusWhy = false; }
480
+ };
481
+ 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 });
482
+ body.oninput = (e) => { 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); } };
483
+ body.onclick = async (e) => {
484
+ const t = e.target.closest('button'); if (!t || t.disabled) return;
485
+ const say = (m) => { const el = body.querySelector('#hvMsg'); if (el) el.textContent = m; };
486
+ if (t.dataset.hvOpt) { st.choice = t.dataset.hvOpt; draw(body); return; }
487
+ if (t.dataset.hvRet) { st.ret = t.dataset.hvRet; draw(body); return; }
488
+ if ('hvLater' in t.dataset) { const m = t.nextElementSibling; m.hidden = !m.hidden; t.setAttribute('aria-expanded', String(!m.hidden)); return; }
489
+ 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; }
490
+ 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; }
491
+ if ('hvStart' in t.dataset) { start(r); return; }
492
+ if ('hvRec' in t.dataset) {
493
+ t.disabled = true;
494
+ 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 } : {}) });
495
+ if (!res.ok) { t.disabled = false; say(res.error); return; }
496
+ delete S.rec[r.key];
497
+ toast(w.kind === 'decision' ? 'Recorded in pm-decisions.md.' : 'Returned to the agent. It counts as a correction.');
498
+ VW.close(); await load(); select(null);
499
+ }
500
+ };
501
+ }
502
+ 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>`;
503
+ 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>`;
504
+ async function bpPost(act, body) {
505
+ const r = await pmPost('/api/briefing-premium/' + act + wsQ(), body);
506
+ return r && r.ok === true ? r : { ok: false, error: (r && r.error) || 'The record was not written.' };
507
+ }
508
+ async function start(r) {
509
+ const w = r.row.dialog.write;
510
+ const res = await startAgent({ ws: w.ws || WS || undefined, task: 'draft', initiative: w.initiative, what: w.what });
511
+ toast(res.ok ? 'The agent started. Its draft waits for you to read.' : 'Not started: ' + res.error);
512
+ if (res.ok) load();
513
+ }
514
+
515
+ /* the weekly update: the recipients are editable; Send opens a mail draft in the PM's own mail and records that it was sent */
516
+ function openUpdateViewer() {
517
+ const draw = (b) => {
518
+ const U = H.weeklyUpdate(S.D, S.D.now);
519
+ const sent = (U.sent || []).find((x) => x.week === U.week.iso);
520
+ 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('');
521
+ 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>`
522
+ + `<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>`
523
+ + 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>`
524
+ + '<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>';
525
+ };
526
+ const U0 = H.weeklyUpdate(S.D, S.D.now);
527
+ 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 });
528
+ 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.'); };
529
+ 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)); } };
530
+ body.onclick = async (e) => {
531
+ const t = e.target.closest('button'); if (!t) return;
532
+ if (t.dataset.hvRm) { const to = H.weeklyUpdate(S.D).to.slice(); to.splice(+t.dataset.hvRm, 1); saveTo(to); return; }
533
+ if (t.dataset.hvIni) { goIni(t.dataset.hvIni); return; }
534
+ if ('hvSend' in t.dataset) sendUpdate();
535
+ };
536
+ }
537
+ /** 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. */
538
+ 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(); };
539
+ const deskWs = () => (S.D.desk && S.D.desk.ws) || ((S.D.board && S.D.board.board) || {}).ws || WS || undefined;
540
+ async function sendUpdate() {
541
+ const U = H.weeklyUpdate(S.D, S.D.now);
542
+ if (!U.to.length) { openUpdateViewer(); toast('Say who the update goes to first.'); setTimeout(() => { const i = $('#hvTo'); if (i) i.focus(); }, 0); return; }
543
+ const name = H.productName(S.D), subject = name + ' · week of ' + U.week.label;
544
+ const mails = U.to.filter((x) => /@/.test(x));
545
+ 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(', ') : ''));
546
+ const r = await pmPost('/api/home-desk/update-sent', { ws: deskWs(), week: U.week.iso, to: U.to, subject });
547
+ 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()); }
548
+ else toast((r && r.error) || 'The send was not recorded.');
549
+ }
550
+
551
+ /* the overview of an initiative: stage moves and hold, Tasks, Core documents (no design yet: a minimal version) */
552
+ function openOverview() {
553
+ const id = S.ini; if (!id || id === 'product') return;
554
+ let M = S.IM;
555
+ let ask = null; // on-hold | cancelled while its reason is asked
556
+ const draw = (b) => {
557
+ if (!M) { b.innerHTML = MORE.WAIT + '<p class="hx-n">The initiative could not be read.</p>'; return; }
558
+ const stages = (M.acts && M.acts.stages) || [];
559
+ 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>';
560
+ const life = M.acts && M.acts.life ? `<button type="button" class="hx-b" data-ov-life="active">Resume</button>`
561
+ : 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>`
562
+ : `<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>`;
563
+ 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>`;
564
+ 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('');
565
+ 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>`
566
+ + `<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>`
567
+ + `<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>`;
568
+ };
569
+ const body = VW.open({ id: 'ov:' + id, kind: 'Overview', title: iniTitle(id), icon: 'goal', render: draw });
570
+ 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
571
+ const bw = () => ({ ws: M.board.ws, board: M.board.id });
572
+ 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.'; } };
573
+ body.onclick = async (e) => {
574
+ const t = e.target.closest('button'); if (!t || !M) return;
575
+ 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; }
576
+ if (t.dataset.ovLife === 'active') { after(await pmPost('/api/lifecycle', { ws: M.board.ws, initiative_id: id, state: 'active', reason: '' }), 'Recorded.'); return; }
577
+ 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
578
+ if ('ovLifeNo' in t.dataset) { ask = null; draw(body); return; }
579
+ 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; }
580
+ 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; }
581
+ 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; }
582
+ if (t.dataset.ovOpen) openFile({ path: t.dataset.ovOpen, name: t.dataset.ovName });
583
+ 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
584
+ const o = { ws: M.board.ws, board: M.board.id };
585
+ if ('ovSprint' in t.dataset) { (await import('./premium-vw-jira.js')).openSprint(o); return; }
586
+ if ('ovRecord' in t.dataset) { (await import('./premium-vw-item.js')).openWorkItem({ kind: 'initiative', id, title: M.title, ...o }); return; }
587
+ const row = (M.tasks.rows || []).find((x) => x.key === t.dataset.ovTk); if (!row) return;
588
+ if (!row.pmos && row.ref) { (await import('./premium-vw-jira.js')).openTicket({ ...o, initiative: id, ref: row.ref }); return; }
589
+ (await import('./premium-vw-item.js')).openWorkItem({ kind: 'task', ini: id, key: row.key, title: row.title, ...o });
590
+ return;
591
+ }
592
+ if (t.dataset.ovDread) { // a draft: read it, edit it, Issue it (a minimal reader in the Viewer, Waiting for design)
593
+ const d = (M.docs.rows || []).find((x) => x.key === t.dataset.ovDread); if (!d) return;
594
+ const A = await import('./home-draft.js');
595
+ A.openDraftVw({ VW, pmGet, pmPost, toast, wait: MORE.WAIT, ws: M.board.ws, scope: M.docs.scope, doc: d, onIssued: () => load() });
596
+ return;
597
+ }
598
+ if ('ovAdddoc' in t.dataset) { // a minimal form in the Viewer (Waiting for design): it posts to /api/custom-docs/add only
599
+ const A = await import('./home-adddoc.js');
600
+ A.openAddDocVw({ VW, pmPost, toast, wait: MORE.WAIT, 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(); } });
601
+ }
602
+ };
603
+ 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.'); };
604
+ }
605
+ async function openFile(f) {
606
+ const V = window.czViews || {};
607
+ if (typeof V.openDoc === 'function') { try { return V.openDoc(f.path, { ws: deskWs() }); } catch { /* the plain view below */ } }
608
+ // a Markdown document opens as its page (premium-vw-doc.js): read, edit, its edit log, health, relations and copies, in the Viewer
609
+ const fws = () => (S.ini && S.IM && S.IM.board && S.IM.board.ws) || deskWs(); // an initiative's document lives in its board's workspace
610
+ 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 */ } }
611
+ 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>' });
612
+ let txt = null;
613
+ 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; }
614
+ 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>`;
615
+ }
616
+ function openPerson(p) {
617
+ const id = S.ini;
618
+ 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>` });
619
+ 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.'); };
620
+ }
621
+ function addPerson() {
622
+ const id = S.ini;
623
+ const body = VW.open({ id: 'person:new', kind: 'Stakeholder', title: 'Add a stakeholder to ' + iniTitle(id), icon: 'info',
624
+ 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>' });
625
+ setTimeout(() => { const i = body.querySelector('#hpN'); if (i) i.focus(); }, 0);
626
+ body.onclick = async (e) => {
627
+ if (!e.target.closest('[data-hv-addp]')) return;
628
+ const name = body.querySelector('#hpN').value.trim(); if (!name) return;
629
+ 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() });
630
+ if (r && r.ok) { toast('Added ' + name + '.'); VW.close(); await load(); } else toast((r && r.error) || 'Not added.');
631
+ };
632
+ }
633
+ /* ── the metrics review (AgMetrics): the Strategist's conversation, and the review in the Viewer: three tiles, the correction rate by week
634
+ * (the current week in blue) and what moved it. Every number is a record of the product's repository (GET /api/board-metrics-premium:
635
+ * corrections from its run log, merges from its trunk, blocked from its workflow state); a measure that is not read says so. ── */
636
+ const STRAT = { key: 'strategy', name: 'Strategist', initial: 'St' };
637
+ const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
638
+ const isMetrics = (s) => /metric/i.test(String((s && [s.task, s.skill, s.name, s.label].filter(Boolean).join(' ')) || ''));
639
+ 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 || ''));
640
+ let MET = null;
641
+ async function metricsModel() {
642
+ if (MET && MET.model && Date.now() - MET.at < 60000) return MET.model;
643
+ const b = (S.D.board && S.D.board.board) || {};
644
+ const r = await getRetry('/api/board-metrics-premium?weeks=8' + (b.ws ? '&ws=' + encodeURIComponent(b.ws) : wsQ('&')), 6);
645
+ MET = { at: Date.now(), model: r && r.ok && r.model ? r.model : null, error: r && !r.ok ? r.error || 'the metrics were not read' : '' };
646
+ return MET.model;
647
+ }
648
+ /** The review from the metrics model: { tiles, bars, moved, line }. Pure over the model and the product card. */
649
+ function metricsView(m) {
650
+ const T = (k) => ((m && m.tiles) || []).find((t) => t.key === k) || null;
651
+ const two = (v) => (v == null ? null : (v / 100).toFixed(2)); // per 100 runs → per agent run, as the mockup reads it
652
+ const cor = T('corrections'), mer = T('merges'), blk = T('blocked');
653
+ const ser = cor && !cor.absent ? cor.ser : [];
654
+ const idx = ser.map((v, i) => (v != null ? i : -1)).filter((i) => i >= 0);
655
+ const cur = idx.length ? ser[idx[idx.length - 1]] : null, prev = idx.length > 1 ? ser[idx[idx.length - 2]] : null;
656
+ const tile = (t, label, value, note) => (!t ? null : t.absent ? { label, value: '–', note: t.absent } : { label, value, note });
657
+ const tiles = [
658
+ tile(cor, 'Correction rate', two(cur), prev != null ? 'Was ' + two(prev) + ' the week before' : cor && cor.text),
659
+ tile(mer, 'Merged a week', mer && mer.value, mer && (mer.change ? mer.change.txt : mer.text)),
660
+ tile(blk, 'Blocked', blk && blk.value, blk && blk.text),
661
+ ].filter(Boolean);
662
+ const last6 = ser.slice(-6), wk = (cor && cor.wk ? cor.wk : []).slice(-6);
663
+ const mx = Math.max(0, ...last6.filter((v) => v != null)) || 1;
664
+ 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 }));
665
+ 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]);
666
+ for (const x of H.productCard(S.D, S.D.now).items.filter((i) => i.kind === 'risk')) moved.push([x.label, 'At risk']);
667
+ const month = MONTHS[new Date(S.D.now).getMonth()];
668
+ const line = cur == null ? month + ': no week has enough agent runs to count a correction rate yet.'
669
+ : 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')) + '.'
670
+ + (moved.length ? ' ' + moved.length + (moved.length === 1 ? ' thing' : ' things') + ' moved this month.' : '');
671
+ return { tiles, bars, moved, line, month, empty: !m };
672
+ }
673
+ function openMetricsViewer() {
674
+ const draw = (b) => {
675
+ const m = MET && MET.model, V = metricsView(m);
676
+ 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; }
677
+ 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>`
678
+ + (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>` : '')
679
+ + `<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>`
680
+ + `<p class="hx-n">${esc((m && m.note) || '')}</p></div>`;
681
+ 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
682
+ };
683
+ 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 });
684
+ if (!(MET && MET.model)) metricsModel().then(() => { if (VW.current() && VW.current().id === 'metrics' && body.isConnected) draw(body); });
685
+ }
686
+ function metricsTarget() {
687
+ const V = metricsView(MET && MET.model);
688
+ 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,
689
+ 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() }] },
690
+ 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') + '.',
691
+ placeholder: 'Ask Strategist about the metrics', also: null };
692
+ }
693
+ async function openMetrics(o = {}) {
694
+ const id = S.sel;
695
+ openTarget(metricsTarget());
696
+ if (!o.keepViewer && !isPhone()) openMetricsViewer();
697
+ await metricsModel();
698
+ if (S.sel !== id) return;
699
+ openTarget(metricsTarget());
700
+ }
701
+ function openRoutine(s) {
702
+ VW.open({ id: 'routine:' + (s.id || s.name), kind: 'Routine', title: String(s.name || s.task || s.skill || 'Routine'), icon: 'cal',
703
+ 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>` });
704
+ }
705
+
706
+ /* the agent's terminal, read only, in the Viewer (term-view.js) */
707
+ function openTerminal(sid) {
708
+ const s = S.D.sessions.find((x) => x.id === sid);
709
+ import('./term-view.js').then((M) => M.openTermView(sid, { title: s ? (s.hx && s.hx.title) || s.name : sid }));
710
+ }
711
+
712
+ /* ── meetings and the calendar (the Viewer's own modules, through window.czViews) ── */
713
+ const views = import('./premium-vw-open.js').catch(() => null);
714
+ async function V() { await views; return window.czViews || {}; }
715
+ async function openMeeting(m) {
716
+ const v = await V();
717
+ if (typeof v.openMeeting === 'function') return v.openMeeting(m.note ? { note: m.note } : m, { ws: deskWs() });
718
+ 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' }); }
719
+ }
720
+ async function openCalendar() {
721
+ const v = await V();
722
+ if (typeof v.openCalendar === 'function') return v.openCalendar({ ws: deskWs(), view: 'day' });
723
+ return VW.placeholder('Calendar', { icon: 'cal' });
724
+ }
725
+
726
+ /* the record dot shows a recording that is on: this page's recorder, or a note the server holds as recording */
727
+ let REC = null;
728
+ import('./premium-meeting.js').then((M) => { REC = M.recCore({ pmGet, pmPost, ws: () => WS || null }); REC.refresh().then(() => drawList()); }).catch(() => { REC = null; });
729
+ addEventListener('premium-rec', () => drawList());
730
+ function recLive() {
731
+ if (!REC) return null;
732
+ const h = REC.holding && REC.holding();
733
+ const n = (REC.notes() || []).find((x) => (h && x.id === h.id) || x.state === 'recording');
734
+ return n ? { id: n.id, title: n.title } : h ? { id: h.id, title: '' } : null;
735
+ }
736
+
737
+ /* ── New, end, kids ── */
738
+ function newItems() {
739
+ const here = S.ini && S.ini !== 'product' ? S.ini : null;
740
+ const inis = H.boardRows(S.D);
741
+ return [
742
+ { 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') },
743
+ { 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')) },
744
+ { label: 'Quick ask', sub: 'Your own chat, about all work', go: () => { goHome(); chat.focus(); } },
745
+ { label: 'Something unrelated', sub: 'A loose chat; link it later', go: () => newLoose() },
746
+ ];
747
+ }
748
+ function newIn(id) {
749
+ const used = new Set(S.D.sessions.map((s) => H.keyOfSession(s)).filter(Boolean));
750
+ let n = 2; while (used.has('init:' + id + ':' + n)) n++;
751
+ if (S.ini !== id) { S.ini = id; drawList(); loadIni().then(drawList); syncUrl(); }
752
+ S.sel = null;
753
+ openTarget({ ...iniTarget(id), key: 'init:' + id + ':' + n, title: 'New session · ' + iniTitle(id), empty: 'A new session in ' + iniTitle(id) + '. Say what it is for.' });
754
+ chat.focus();
755
+ }
756
+ function newLoose() {
757
+ const d = new Date(), p = (x) => String(x).padStart(2, '0');
758
+ const key = 'chat:loose-' + d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '-' + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds());
759
+ if (S.ini) { S.ini = null; drawList(); syncUrl(); }
760
+ S.sel = null;
761
+ 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) });
762
+ chat.focus();
763
+ }
764
+ async function endRow(id) {
765
+ const r = rowById(id); if (!r) return;
766
+ if (r.kind === 'session' && r.sid) {
767
+ // an inline confirmation (no browser dialog): the first press arms the ×, a second press within five seconds ends the session
768
+ 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; }
769
+ S.endArm = null;
770
+ const res = await pmPost('/api/session/remove', { id: r.sid });
771
+ if (!res || !res.ok) { toast((res && res.error) || 'The session did not end.'); return; }
772
+ toast('Ended. The conversation is kept.');
773
+ } else if (r.kind === 'need') {
774
+ const res = await bpPost('put-off', { key: r.key, until: 'tomorrow' });
775
+ if (!res.ok) { toast(res.error); return; }
776
+ toast('Put off until tomorrow. It comes back by itself.');
777
+ }
778
+ if (S.sel === id) S.sel = null;
779
+ await load();
780
+ }
781
+
782
+ /* ── the small menus (one at a time; Escape closes it first) ── */
783
+ const menuEl = $('#hmMenu');
784
+ let menuItems = [];
785
+ function menu(anchor, items, label) {
786
+ menuItems = items;
787
+ menuEl.innerHTML = (label ? `<p class="hm-ml">${esc(label)}</p>` : '') + items.map((x, i) => `<button type="button" role="menuitem" data-hm-mi="${i}"${x.disabled ? ' disabled' : ''}><b>${esc(x.label)}</b>${x.sub ? `<em>${esc(x.sub)}</em>` : ''}</button>`).join('') || '<p class="hm-ml">Nothing to choose.</p>';
788
+ menuEl.hidden = false; menuEl.setAttribute('data-esc-layer', '');
789
+ // the menu sits under (or over) the button that opened it: CSS anchor positioning reads .hm-anc, so no geometry is set from here
790
+ if (menu.anchor && menu.anchor !== anchor) menu.anchor.classList.remove('hm-anc');
791
+ anchor.classList.add('hm-anc');
792
+ menu.anchor = anchor;
793
+ menuEl.classList.toggle('top', !!anchor.closest('.hm-top')); // the phone's ⋯ menu drops from its button at the top right
794
+ const f = menuEl.querySelector('button'); if (f) f.focus();
795
+ }
796
+ 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(); }
797
+ menuEl.onclick = (e) => { // delegated: every item is a <button role=menuitem>
798
+ const b = e.target.closest('[data-hm-mi]'); if (!b) return;
799
+ const it = menuItems[+b.dataset.hmMi]; const a = menu.anchor;
800
+ menuEl.hidden = true; menuEl.removeAttribute('data-esc-layer'); if (a) a.classList.remove('hm-anc');
801
+ if (it && it.go) it.go(a);
802
+ };
803
+ document.addEventListener('click', (e) => { if (!menuEl.hidden && !menuEl.contains(e.target) && !(menu.anchor && menu.anchor.contains(e.target))) closeMenu(); }, true);
804
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !menuEl.hidden) { e.stopPropagation(); closeMenu(); } else if (e.key === 'Escape' && S.sheet) sheet(false); }, true);
805
+ function moreMenu(anchor) {
806
+ const go = {
807
+ work: () => MORE.openMyWork(), around: () => MORE.openAround(), inbox: () => MORE.openInbox(searchGo), eod: () => MORE.openEndOfDay(), cal: () => openCalendar(),
808
+ rec: () => MORE.openRecorder(), search: () => MORE.openSearch(searchGo), products: () => MORE.openProducts(), sources: () => MORE.openSources(), settings: () => MORE.openSettings(),
809
+ };
810
+ menu(anchor, MORE.moreItems.map(([k, l]) => ({ label: l, go: go[k] })), 'Waiting for design');
811
+ }
812
+ function searchGo(d) {
813
+ if (d.ini) goIni(d.ini);
814
+ else if (d.doc) openFile({ path: d.doc, name: d.doc.split('/').pop() });
815
+ 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(); } }
816
+ else if (d.link) location.href = d.link;
817
+ }
818
+
819
+ /* ── the phone sheet ── */
820
+ function sheet(on) {
821
+ S.sheet = !!on;
822
+ document.body.classList.toggle('hm-sheet', S.sheet);
823
+ $('#hmNeeds').setAttribute('aria-expanded', String(S.sheet));
824
+ if (S.sheet) { const f = $('#hmList button'); if (f) f.focus(); }
825
+ }
826
+ $('#hmNeeds').onclick = () => sheet(!S.sheet);
827
+ $('#hmMoreP').onclick = (e) => moreMenu(e.currentTarget);
828
+ $('#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
829
+
830
+ /* ── presses on the list ── */
831
+ $('#hmList').onclick = (e) => { // delegated: every press on the list is a <button>
832
+ const b = e.target.closest('button'); if (!b) return;
833
+ const d = b.dataset;
834
+ if (d.hmSel) { select(d.hmSel); return; }
835
+ if (d.hmKids) { if (S.kids.has(d.hmKids)) S.kids.delete(d.hmKids); else S.kids.add(d.hmKids); drawList(); return; }
836
+ if (d.hmEnd) { endRow(d.hmEnd); return; }
837
+ 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; }
838
+ if ('hmAllneeds' in d) { S.allNeeds = !S.allNeeds; drawList(); return; }
839
+ if ('hmNew' in d) { menu(b, newItems(), 'What is it for?'); return; }
840
+ if ('hmFold' in d) { S.folded = true; store.set('pmos.home.fold', '1'); drawList(); return; }
841
+ if ('hmMeet' in d) { const m = H.meetLineOf(S.D.today); if (m) openMeeting(m.meeting); return; }
842
+ if ('hmCal' in d) { openCalendar(); return; }
843
+ if ('hmRec' in d) { MORE.openRecorder().then(() => drawList()); return; }
844
+ if (d.hmRecopen) { openMeeting({ note: d.hmRecopen }); return; }
845
+ 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; }
846
+ if ('hmNewin' in d) { if (S.ini === 'product') { openTarget(updateTarget()); chat.focus(); } else newIn(S.ini); return; }
847
+ if ('hmDone' in d) { S.doneOpen = !S.doneOpen; drawList(); return; }
848
+ 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; }
849
+ if ('hmCta' in d) { cta(); return; }
850
+ if ('hmOv' in d) { if (S.ini === 'product') openUpdateViewer(); else openOverview(); return; }
851
+ if ('hmElse' in d) { const f = S.lay && S.lay.elsewhere && S.lay.elsewhere.first; goHome(); if (f) select(f.id); return; }
852
+ if ('hmPerson' in d) addPerson();
853
+ };
854
+ $('#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>`);
855
+ $('#hmUnfold').onclick = () => { S.folded = false; store.set('pmos.home.fold', null); drawList(); };
856
+ function cta() {
857
+ if (S.ini === 'product') { const C = H.productCard(S.D); if (C.sent) openUpdateViewer(); else { select('n:update'); } return; }
858
+ const h = S.H || {};
859
+ if (h.need) { select(h.need.id); return; }
860
+ const t = iniTarget(S.ini);
861
+ openTarget(t);
862
+ if (h.ask) chat.send(h.ask);
863
+ }
864
+
865
+ /* ── start ── */
866
+ mountNav('home', document, { more: () => moreMenu, settings: () => MORE.openSettings() });
867
+ PHC = mountPhoneCard({ pmGet, pmPost, toast, ws: () => WS || null, openMeeting: (m) => openMeeting(m), wait: MORE.WAIT }); drawList();
868
+ drawList(); drawTop();
869
+ { // a conversation the address names opens at once, before the lists are read, so nothing typed or attached lands in the Home chat
870
+ 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;
871
+ 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
872
+ openTarget(early ? { ...homeTarget(), key: early, title: (P.get('label') || '').slice(0, 80) || early }
873
+ : sidAt ? { ...homeTarget(), key: '', title: 'Reading', empty: 'Reading the session.' }
874
+ : S.ini ? (S.ini === 'product' ? { ...homeTarget(), title: 'Reading' } : iniTarget(S.ini)) : homeTarget());
875
+ }
876
+ /* The address: ?ini=<id> an initiative's layout · ?open=<row key> a Needs-you row · ?session=<id> a session · ?ask=<initiative id> | board:<key> |
877
+ * insights | verdict with the question in ?q, or ?about=<key>&label=<name>: that conversation · ?open=report:|chart:|dashboard:<id> that one in the
878
+ * Viewer · ?say=<words> or ?q a first message in the box, not sent · ?meeting=<note id> the meeting card. */
879
+ const KEY = /^(decision|blocked|waited|src|ev|work|board|init|doc|ins|chat|pop):[A-Za-z0-9][A-Za-z0-9._:-]{0,100}$/;
880
+ load().then(() => {
881
+ const open = P.get('open') || P.get('item'), sid = P.get('session'), mt = P.get('meeting');
882
+ const ask = P.get('ask') || '';
883
+ const blockOpen = /^(report|chart|dashboard):([A-Za-z0-9][A-Za-z0-9._:-]{0,119})$/.exec(open || '');
884
+ const say = (P.get('say') || P.get('q') || '').slice(0, 500);
885
+ const asked = !ask ? '' : /^board:/.test(ask) ? ask : /^(insights|verdict)$/.test(ask) ? 'ins:' + ask : 'init:' + ask;
886
+ const about = KEY.test(P.get('about') || '') ? P.get('about') : KEY.test(asked) ? asked : null;
887
+ 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 }); }
888
+ 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.'); } }
889
+ else if (about && /^init:/.test(about) && iniRowOf(about.slice(5))) goIni(about.slice(5));
890
+ else if (about) openTarget({ ...homeTarget(), key: about, title: (P.get('label') || '').slice(0, 80) || about });
891
+ 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
892
+ else if (S.ini) goIni(S.ini);
893
+ 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
894
+ if (blockOpen) {
895
+ const b = { kind: blockOpen[1], id: blockOpen[2] };
896
+ (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.'));
897
+ }
898
+ 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);
899
+ if (mt) openMeeting({ note: mt });
900
+ 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)
901
+ poll();
902
+ });
903
+ addEventListener('resize', () => { if (!isPhone() && S.sheet) sheet(false); drawList(); });
904
+ // Ctrl K (Cmd K) opens Search in the Viewer, as the ⋯ menu's Search does
905
+ addEventListener('keydown', (e) => { if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && (e.key === 'k' || e.key === 'K')) { e.preventDefault(); MORE.openSearch(searchGo); } });