create-pmos 0.274.0 → 0.276.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.
@@ -4,6 +4,8 @@
4
4
  * Slice 3: the reply box asks a read-only agent. A control with nothing honest to write stays disabled and says why. */
5
5
  import { pmPost, pmGet } from './http.js';
6
6
  import { mountMeeting } from './premium-meeting.js';
7
+ import { lineItems, behindOf, refreshTargets, whenRead } from './freshness-words.js';
8
+ import { momentOf, inText } from './c3-phone-model.js';
7
9
  import { $, $$, esc, store, THEME_KEY, RM, AI, S, theme, toast, kv, H, openDlg, closeDlg, setTab, setMode, CHECK, CHEV, ptx, turnA, turnU, H1, H2, P1, UL, logHtml, loadThread, onScroll, wireRail, pvFeed } from './premium-shell.js';
8
10
  const ICON = {
9
11
  meeting: '<rect x="4" y="5" width="16" height="15" rx="3"/><path d="M4 10h16M9 3v4M15 3v4"/>',
@@ -252,8 +254,532 @@ $('#pickMenu').addEventListener('click', async (e) => {
252
254
  const again = b.dataset.ws ? $(`#pickMenu [data-ws="${CSS.escape(b.dataset.ws)}"]`) : null; if (again) again.focus();
253
255
  });
254
256
 
257
+ /* ── Around you: what the agents and the outside world left for you (initiative premium-briefing-depth) ─────────────────────────────
258
+ * One card under Today with five rows; each row opens the standard dialog. Every read is a route the console already uses and every
259
+ * write is a press that says what it does first, through the launch nonce (pmPost). A source that cannot be read is named in its row,
260
+ * never shown as empty. Which products: ?ws=<id> that one, otherwise every product the Briefing reads. */
261
+ const SRCN = { slack: 'Slack', jira: 'Jira', confluence: 'Confluence', mail: 'Mail' };
262
+ const srcName = (s) => SRCN[s] || String(s || 'a source');
263
+ const first = (s) => String(s || '').trim().split(/\s+/)[0];
264
+ const pl = (n, one, many) => n + ' ' + (n === 1 ? one : many);
265
+ const BDI = {
266
+ at: '<circle cx="12" cy="12" r="4"/><path d="M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1"/>',
267
+ prop: '<path d="M12 3l1.8 4.7L18.5 9.5l-4.7 1.8L12 16l-1.8-4.7L5.5 9.5l4.7-1.8z"/>',
268
+ pulse: '<path d="M3 12h4l3-7 4 14 3-7h4"/>',
269
+ scan: '<circle cx="11" cy="11" r="7"/><path d="m20 20-4-4"/>',
270
+ src: '<path d="M20 11a8 8 0 0 0-14.6-4.5M4 13a8 8 0 0 0 14.6 4.5"/><path d="M5 3v4h4M19 21v-4h-4"/>',
271
+ ret: '<path d="M9 14 4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12h-3"/>',
272
+ x: '<path d="M6 6l12 12M18 6 6 18"/>',
273
+ };
274
+ const bdIco = (d) => `<svg class="i" viewBox="0 0 24 24">${d}</svg>`;
275
+ const A = { prop: null, men: null, pulse: null, scan: null, src: null }; // the last answer of each source: { ok, … } or { ok: false, error }
276
+ const DEC = new Map(); // proposals decided on this visit: id → { item, st: 'kept' | 'back' | 'dropped', note, wrote, warnings }
277
+ const PNOTE = {}, PERR = {}, PBACK = new Set(); // the send-back note typed, the refusal shown, the proposals whose note box is open
278
+ const MREAD = new Map(), MADD = new Set(); // mentions marked read or unread on this visit; mentions made a task
279
+ const SDEC = new Map(); // scan proposals decided on this visit: id → { st: 'ok' | 'no', result }
280
+ const SERR = {}, SWHY = {}, SOPEN = new Set(); // a scan proposal's dismissal reason, and the proposals whose reason box is open
281
+ let MTAB = 'all', BUSY = '';
282
+ const getj = async (p) => { const r = await pmGet(p); return r && r.ok !== false ? r : { ok: false, error: (r && r.error) || 'the server did not answer' }; };
283
+ const wq = (ws) => (ws ? 'ws=' + encodeURIComponent(ws) : '');
284
+ const prods = () => {
285
+ const one = wsParam(); if (one) return [{ ws: one, name: one }];
286
+ const P = M && M.products;
287
+ return P ? P.available.filter((x) => x.on).map((x) => ({ ws: x.ws, name: x.name })) : [{ ws: '', name: '' }];
288
+ };
289
+ const said = (r) => 'could not be read: ' + (r && r.error ? r.error : 'the server did not answer');
290
+
291
+ /* reads */
292
+ async function readProps(P) {
293
+ const items = [], errs = [];
294
+ await Promise.all(P.flatMap((p) => ['initiative', 'work'].map(async (kind) => {
295
+ const r = await getj('/api/driver/open?target_kind=' + kind + (p.ws ? '&' + wq(p.ws) : ''));
296
+ if (!r.ok) { errs.push(r.error); return; }
297
+ if (r.mode !== 'approve') return; // Off and Shadow raise nothing on the Briefing (the console draws the same)
298
+ for (const [tid, list] of Object.entries(r.targets || {})) for (const pr of list) items.push({ id: pr.id, ws: r.ws, pname: P.length > 1 ? p.name : '', kind, tid, p: pr, title: '' });
299
+ })));
300
+ items.sort((a, b) => String(a.p.at).localeCompare(String(b.p.at)) || a.id.localeCompare(b.id));
301
+ if (items.some((x) => x.kind === 'work')) {
302
+ const w = await getj('/api/pm-items'), by = new Map(((w.ok && w.items) || []).map((i) => [i.id, i.title]));
303
+ items.forEach((x) => { if (x.kind === 'work') x.title = by.get(x.tid) || ''; });
304
+ }
305
+ if (!items.length && errs.length) return { ok: false, error: errs[0] };
306
+ return { ok: true, items, errs };
307
+ }
308
+ const briefPage = (force) => (BP && !force && Date.now() - BP.at < 30000 ? BP.p : (BP = { at: Date.now(), p: getj('/api/brief-page') }).p); // one read of the day for the Around you card and the phone card
309
+ let BP = null;
310
+ async function readMen() {
311
+ const r = await briefPage();
312
+ return r.ok ? { ok: true, list: Array.isArray(r.mentions) ? r.mentions : null } : r;
313
+ }
314
+ const PST = { 'on time': ['ok', 'On time'], 'at risk': ['warn', 'At risk'], delayed: ['bad', 'Delayed'], overdue: ['bad', 'Overdue'], 'no plan': ['', 'No plan'] };
315
+ /** One Calendar row as the pulse draws it. cls: bad (late) · warn (at risk) · ok (on plan) · '' (no plan date). The Calendar's own status, no forecast of ours. */
316
+ function pulseRow(g) {
317
+ const j = g.jira && Number.isInteger(g.jira.total) && g.jira.total > 0 && Number.isInteger(g.jira.done) ? g.jira : null;
318
+ const f = (g.forecast && (g.forecast.end || g.forecast.start)) || null;
319
+ if (j && (!PST[g.status] || g.status === 'no plan')) {
320
+ const all = j.done >= j.total;
321
+ return { id: g.id, title: g.title || g.id, cls: j.blocked > 0 ? 'warn' : all ? 'ok' : '', word: j.blocked > 0 ? 'Blocked' : all ? 'Done in Jira' : 'In progress',
322
+ why: j.done + ' of ' + j.total + ' done in Jira' + (j.blocked > 0 ? ', ' + j.blocked + ' blocked' : '') + '; no promised date' };
323
+ }
324
+ const k = PST[g.status] ? g.status : 'no plan', p = g.promised || null;
325
+ return { id: g.id, title: g.title || g.id, cls: PST[k][0], word: PST[k][1] + (g.slip_days > 0 ? ' +' + g.slip_days + ' d' : ''),
326
+ why: (p ? 'Forecast ' + (f || 'not set') + ' vs promised ' + p : 'No promised date' + (f ? '; forecast ' + f : '')) + (j ? '. ' + j.done + ' of ' + j.total + ' done in Jira' : '') };
327
+ }
328
+ async function readPulse(P) {
329
+ const d = new Date(), day = d.getFullYear() + '-' + STAMP(d.getMonth() + 1) + '-' + STAMP(d.getDate()), rows = [], errs = [];
330
+ let none = 0;
331
+ await Promise.all(P.map(async (p, i) => {
332
+ const r = await getj('/api/calendar-views?view=quarter&only=gantt&date=' + day + (p.ws ? '&' + wq(p.ws) : ''));
333
+ if (!r.ok) { errs.push(r.error); return; }
334
+ none += Number(r.no_plan) || 0;
335
+ for (const g of r.gantt || []) rows.push({ ...pulseRow(g), ws: p.ws, pname: P.length > 1 ? p.name : '', at: i });
336
+ }));
337
+ rows.sort((a, b) => a.at - b.at);
338
+ if (!rows.length && !none && errs.length) return { ok: false, error: errs[0] };
339
+ return { ok: true, rows, none, errs };
340
+ }
341
+ async function readScan(P) {
342
+ const got = [], errs = [];
343
+ await Promise.all(P.map(async (p, i) => {
344
+ const r = await getj('/api/scan/portfolio' + (p.ws ? '?' + wq(p.ws) : ''));
345
+ if (!r.ok) errs.push(r.error); else got.push({ ...r, pname: P.length > 1 ? p.name : '', at: i });
346
+ }));
347
+ got.sort((a, b) => a.at - b.at);
348
+ if (!got.length && errs.length) return { ok: false, error: errs[0] };
349
+ return { ok: true, scans: got, errs };
350
+ }
351
+ const readSrc = () => getj('/api/sources' + (wsParam() ? '?' + wq(wsParam()) : ''));
352
+ const readAll = async (which) => {
353
+ const P = prods(), all = !which, job = {
354
+ prop: () => readProps(P), men: () => readMen(), pulse: () => readPulse(P), scan: () => readScan(P), src: () => readSrc(),
355
+ };
356
+ await Promise.all(Object.keys(job).filter((k) => all || which.includes(k)).map(async (k) => { try { A[k] = await job[k](); } catch (e) { A[k] = { ok: false, error: String((e && e.message) || e) }; } }));
357
+ drawAround();
358
+ };
359
+
360
+ /* words */
361
+ const PWHAT = { problem: 'Problem statement', evidence: 'Evidence', sizing: 'Opportunity sizing', assumption: 'Riskiest assumption and spike brief', stakeholders: 'Stakeholders', move: 'Move', note: 'Note', 'next-step': 'Next step', 'follow-up': 'Follow-up' };
362
+ const pWhat = (p) => (p.what === 'move' && p.data && p.data.to ? 'Move to ' + p.data.to : PWHAT[p.what] || p.what);
363
+ const pKeep = (p) => ({ problem: 'Keep writes the problem statement into the stage record.', move: 'Keep moves the initiative on its board.', 'next-step': 'Keep adds the next step to your Work item.', 'follow-up': 'Keep copies the follow-up text. Nothing is sent to anyone.', doc: 'Keep issues the draft document.' }[p.what] || 'Keep records that you accept it. Nothing else changes.');
364
+ const pWrote = (w) => ({ problem: 'The problem statement is in the stage record.', move: 'The initiative moved.', doc: 'The document was issued.', 'next-step': 'The next step is in your Work item.' }[w] || 'It is recorded. Nothing else changed.');
365
+ const pText = (p) => {
366
+ const t = p.data && typeof p.data.text === 'string' ? p.data.text : '';
367
+ if (p.what === 'move') return 'Move this initiative to ' + ((p.data && p.data.to) || 'the next stage') + '.';
368
+ if (t) return t;
369
+ if (p.data && Array.isArray(p.data.items)) return pl(p.data.items.length, 'item', 'items') + ' with a pointer each.';
370
+ return '';
371
+ };
372
+ const iniTitle = (x) => { const r = A.pulse && A.pulse.ok && A.pulse.rows.find((y) => y.id === x.tid && y.ws === x.ws); return r ? r.title : ''; };
373
+ const targetOf = (x) => (x.kind === 'work' ? 'Work · ' : 'Initiative · ') + (x.title || (x.kind === 'initiative' ? iniTitle(x) : '') || x.tid);
374
+ const openProps = () => (A.prop && A.prop.ok ? A.prop.items : []);
375
+ const shownMen = () => {
376
+ const l = A.men && A.men.ok && A.men.list ? A.men.list : [];
377
+ return l.filter((m) => !m.in_needs && (MREAD.has(m.id) || !m.read)).map((m) => (MREAD.has(m.id) ? { ...m, read: MREAD.get(m.id) } : m));
378
+ };
379
+ const waitM = (l) => l.filter((m) => m.reply && !m.read);
380
+ function menLine(l) {
381
+ const w = waitM(l), rest = l.filter((m) => !m.read).length - w.length;
382
+ if (!w.length) return rest ? 'No one is waiting on a reply. ' + pl(rest, 'mention is', 'mentions are') + ' for your information.' : 'No mentions are left unread.';
383
+ const names = w.map((m) => (m.who ? first(m.who) : 'Someone') + ' in ' + srcName(m.source)), s = names.length < 2 ? names[0] : names.slice(0, -1).join(', ') + ' and ' + names[names.length - 1];
384
+ return s + (w.length === 1 ? ' is' : ' are') + ' waiting on your reply.' + (rest ? ' ' + rest + (rest === 1 ? ' more is' : ' more are') + ' for your information.' : '');
385
+ }
386
+ const mWhen = (iso) => {
387
+ if (!iso) return '';
388
+ const d = new Date(iso), n = new Date(), hm = STAMP(d.getHours()) + ':' + STAMP(d.getMinutes()), k = (x) => x.getFullYear() * 400 + x.getMonth() * 32 + x.getDate(), y = new Date(n); y.setDate(y.getDate() - 1);
389
+ return k(d) === k(n) ? hm : k(d) === k(y) ? 'yesterday ' + hm : d.getDate() + '/' + (d.getMonth() + 1) + ' ' + hm;
390
+ };
391
+ const groups = (rows) => ({ bad: rows.filter((r) => r.cls === 'bad'), warn: rows.filter((r) => r.cls === 'warn'), ok: rows.filter((r) => r.cls === 'ok'), none: rows.filter((r) => !r.cls) });
392
+ const PGW = { bad: 'Late', warn: 'At risk', ok: 'On plan', none: 'No plan date' };
393
+ const bar = (g, n, extra) => `<span class="bd-bar" aria-hidden="true">${['bad', 'warn', 'ok', 'none'].map((k) => { const c = k === 'none' ? g.none.length + extra : g[k].length; return c ? `<i class="${k}" style="width:${c / n * 100}%"></i>` : ''; }).join('')}</span>`;
394
+ const dayWord = (iso) => {
395
+ const d = new Date(iso); if (!Number.isFinite(d.getTime())) return '';
396
+ const n = new Date(), y = new Date(n), hm = STAMP(d.getHours()) + ':' + STAMP(d.getMinutes()); y.setDate(y.getDate() - 1);
397
+ return d.toDateString() === n.toDateString() ? 'today, ' + hm : d.toDateString() === y.toDateString() ? 'yesterday, ' + hm : d.getDate() + ' ' + ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()] + ', ' + hm;
398
+ };
399
+ const scanOpen = () => (A.scan && A.scan.ok ? A.scan.scans.reduce((n, s) => n + (s.proposals_waiting || 0), 0) : 0);
400
+ const behindSrc = () => {
401
+ if (!A.src || !A.src.ok) return [];
402
+ const ids = behindOf(lineItems(A.src.sources)).map((i) => i.id);
403
+ return A.src.sources.filter((s) => ids.includes(s.id));
404
+ };
405
+ const joinN = (a) => (a.length < 2 ? a.join('') : a.slice(0, -1).join(', ') + ' and ' + a[a.length - 1]);
406
+
407
+ /** The five rows of the card: { k, ic, t, s, m (count html), bar, wait }. Pure of the DOM; every word comes from A. */
408
+ function aroundRows() {
409
+ const R = [], rd = 'Reading…';
410
+ { // agent proposals
411
+ const a = A.prop, n = a && a.ok ? a.items.length : 0;
412
+ R.push({ k: 'prop', ic: BDI.prop, wait: n > 0,
413
+ t: !a ? rd : !a.ok ? 'Agent proposals ' + said(a) : n ? pl(n, 'agent proposal waits', 'agent proposals wait') + ' on you' : 'No agent proposals wait',
414
+ s: !a ? '' : !a.ok ? '' : n ? 'Keep, send back or drop each one' : 'The agent files a draft here when it has one', m: n ? `<span class="due">${n}</span>` : '' });
415
+ }
416
+ { // mentions
417
+ const a = A.men, l = shownMen(), w = waitM(l);
418
+ R.push({ k: 'men', ic: BDI.at, wait: w.length > 0,
419
+ t: !a ? rd : !a.ok ? 'Mentions ' + said(a) : a.list === null ? 'No brief for today, so no mentions were read' : l.filter((m) => !m.read).length ? menLine(l) : 'No one has mentioned you today',
420
+ s: !a || !a.ok || !l.filter((m) => !m.read).length ? '' : [...new Set(l.filter((m) => !m.read).map((m) => srcName(m.source)))].join(', '),
421
+ m: w.length ? '<span class="due od">Reply</span>' : '' });
422
+ }
423
+ { // portfolio pulse
424
+ const a = A.pulse, g = a && a.ok ? groups(a.rows) : null, n = a && a.ok ? a.rows.length + a.none : 0;
425
+ R.push({ k: 'pulse', ic: BDI.pulse, wait: !!(g && g.bad.length),
426
+ t: !a ? rd : !a.ok ? 'Portfolio pulse ' + said(a) : n ? `Portfolio pulse: ${g.bad.length} late, ${g.warn.length} at risk` : 'Portfolio pulse: nothing to compare yet',
427
+ s: !a || !a.ok ? '' : n ? `${g.ok.length} on plan · ${g.none.length + a.none} with no plan date` : 'No initiative has a promised date or a Jira read.',
428
+ bar: n ? bar(g, n, a.none) : '', m: '' });
429
+ }
430
+ { // horizon scan
431
+ const a = A.scan, S = a && a.ok ? a.scans : [], w = scanOpen(), run = S.some((x) => x.open), last = S.map((x) => x.last && x.last.at).filter(Boolean).sort().pop(), nrep = S.reduce((n, x) => n + x.reports.filter((r) => r.written && !r.parent).length, 0);
432
+ R.push({ k: 'scan', ic: BDI.scan, wait: w > 0,
433
+ t: !a ? rd : !a.ok ? 'Horizon scan ' + said(a) : run ? 'Horizon scan: scanning now' : w ? 'Horizon scan: ' + pl(w, 'proposal waits', 'proposals wait') + ' for you' : S.every((x) => x.switched_off) ? 'Horizon scan: switched off' : last ? 'Horizon scan: nothing waits' : 'Horizon scan: no scan has run yet',
434
+ s: !a || !a.ok ? '' : run ? 'Reading the web and the repository' : last ? 'Ran ' + dayWord(last).toLowerCase() + (nrep ? ' · ' + pl(nrep, 'report', 'reports') : '') : 'Start one from here', m: w ? `<span class="due">${w}</span>` : '' });
435
+ }
436
+ { // data freshness
437
+ const a = A.src, b = behindSrc();
438
+ R.push({ k: 'src', ic: BDI.src, wait: b.length > 0,
439
+ t: !a ? rd : !a.ok ? 'Data freshness ' + said(a) : b.length > 2 ? b.length + ' sources need a new read' : b.length ? joinN(b.map((s) => s.label)) + (b.length === 1 ? ' needs' : ' need') + ' a new read' : 'Every source was read recently',
440
+ s: !a || !a.ok ? '' : b.length > 2 ? joinN(b.map((s) => s.label)) + '. Read on a schedule, not live' : 'Sources are read on a schedule, not live', m: b.length ? `<span class="due">${b.length}</span>` : '' });
441
+ }
442
+ return R;
443
+ }
444
+ function drawAround() {
445
+ const B = $('#aroundBody'); if (!B) return;
446
+ const R = aroundRows(), n = R.filter((r) => r.wait).length;
447
+ B.innerHTML = R.map((r) => `<div class="wrw"><div class="wrow sm" data-bdrow="${r.k}"><span class="wgl" aria-hidden="true">${bdIco(r.ic)}</span><button type="button" class="wrh" data-bd="${r.k}" aria-haspopup="dialog"><span class="wtx"><span class="wtit">${esc(r.t)}</span>${r.s ? `<span class="ws">${esc(r.s)}</span>` : ''}${r.bar || ''}</span>${r.m ? `<span class="wm">${r.m}</span>` : ''}</button></div></div>`).join('');
448
+ $('#aroundCap').textContent = Object.values(A).some((x) => x === null) ? 'Reading' : n ? n + ' to look at' : 'quiet';
449
+ }
450
+
451
+ /* the dialogs: each draws into the dialog's Detail pane and redraws after a press. The question box stays out: these rows have no agent thread. */
452
+ function bdDlg(key, eye, title, sub, say, draw, onPress, onInput) {
453
+ openDlg({ eye, title, sub, say, stream: turnA(ptx(say)), noteKey: null, pane: '<article class="paper doc"><div class="bd-a"></div></article>', label: title });
454
+ $('#askF').hidden = true; $('#askNote').hidden = true; setMode('detail');
455
+ const o = $('#oMain'); o.dataset.bd = key;
456
+ const redraw = (focus) => {
457
+ $('.bd-a', o).innerHTML = draw();
458
+ if (focus) { const f = $(focus, o) || $('.bd-a button:not([disabled]), .bd-a a', o); if (f) f.focus(); }
459
+ };
460
+ o.onclick = (e) => { if (o.dataset.bd === key) onPress(e, redraw); };
461
+ o.oninput = (e) => { if (o.dataset.bd === key && onInput) onInput(e); };
462
+ redraw();
463
+ return redraw;
464
+ }
465
+ const bdActs = (...b) => `<div class="bd-acts">${b.join('')}</div>`;
466
+ const bdBtn = (label, act, id, alt, attrs) => `<button type="button" class="cta${alt ? ' alt' : ''}" data-bda="${act}"${id != null ? ` data-id="${esc(id)}"` : ''}${attrs || ''}>${esc(label)}</button>`;
467
+ const bdDone = (ok, text) => `<p class="bd-done" role="status">${ok ? CHECK : bdIco(BDI.x)}<span>${esc(text)}</span></p>`;
468
+ const bdChip = (t, c) => `<span class="bd-chip${c ? ' ' + c : ''}">${esc(t)}</span>`;
469
+ const bdLink = (href) => (/^https:\/\/\S+$/i.test(String(href || '')) ? href : '');
470
+ const bdFail = (id, e) => (e[id] ? `<p class="nodef err" role="alert">${esc(e[id])}</p>` : '');
471
+
472
+ /* ── agent proposals ── */
473
+ function propItem(it) {
474
+ const p = it.p, d = DEC.get(it.id), id = it.id, text = pText(p);
475
+ const src = (p.sources || []).filter((s) => s && s.ref).map((s) => (bdLink(s.ref) ? `<a href="${esc(bdLink(s.ref))}" target="_blank" rel="noopener noreferrer">${esc(s.label || s.ref)}</a>` : esc((s.label ? s.label + ': ' : '') + s.ref))).join(' · ');
476
+ let act;
477
+ if (d) act = d.st === 'kept' ? bdDone(true, 'Kept. ' + pWrote(d.wrote) + (d.warnings.length ? ' ' + d.warnings.join(' ') : '')) : d.st === 'back' ? bdDone(true, 'Sent back with your note: “' + d.note + '”. The note starts a new run.') : bdDone(false, 'Dropped. It counts as a correction.');
478
+ else if (PBACK.has(id)) {
479
+ act = `<label class="bd-l" for="bdn-${esc(id)}">What should the agent change? A note is required.</label><textarea id="bdn-${esc(id)}" data-bdn="${esc(id)}" maxlength="500" rows="3">${esc(PNOTE[id] || '')}</textarea>${bdFail(id, PERR)}`
480
+ + bdActs(bdBtn('Send back with the note', 'pback', id, false, (PNOTE[id] || '').trim() ? '' : ' disabled'), bdBtn('Cancel', 'pcancel', id, true)) + '<p class="bd-why">Send back starts a new run with your note. It cannot be undone.</p>';
481
+ } else act = bdActs(bdBtn('Keep', 'pkeep', id), bdBtn('Send back', 'pnote', id, true), bdBtn('Drop', 'pdrop', id, true)) + `<p class="bd-why">${esc(pKeep(p))} Drop counts as a correction. None of the three can be undone.</p>` + bdFail(id, PERR);
482
+ return `<div class="bd-it${d ? ' decided' : ''}" data-id="${esc(id)}"><div class="bd-h">${bdChip(pWhat(p))}${it.pname ? bdChip(it.pname, 'mono') : ''}</div><span class="bd-t">${esc(targetOf(it))}</span>${text ? `<p class="bd-q">${esc(text)}</p>` : ''}${p.why ? `<p class="bd-why">Why: ${esc(p.why)}</p>` : ''}${src ? `<p class="bd-why">Sources: ${src}</p>` : ''}${act}</div>`;
483
+ }
484
+ function propsHtml() {
485
+ const a = A.prop; if (!a.ok) return `<p class="nodef err" role="alert">Agent proposals ${esc(said(a))}</p>`;
486
+ const L = a.items.concat([...DEC.values()].map((d) => d.item).filter((it) => !a.items.some((o) => o.id === it.id)));
487
+ return (L.length ? `<p class="bd-top">${a.items.length ? pl(a.items.length, 'proposal waits', 'proposals wait') + ' for you.' : 'All decided.'} The agent drafts and asks you. Nothing it wrote has changed a record until you keep it.</p><div class="bd-list">${L.map(propItem).join('')}</div>` : `<p class="empty3">${CHECK}No agent proposals wait.</p>`)
488
+ + (a.errs.length ? `<p class="note">Not read: ${esc(a.errs[0])}</p>` : '') + '<p class="note">The agent mode (Off, Shadow, Approve) stays in the console. This list shows a kind only when its mode is Approve.</p>';
489
+ }
490
+ async function propPress(e, redraw) {
491
+ const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
492
+ const act = b.dataset.bda, id = b.dataset.id, it = openProps().find((x) => x.id === id);
493
+ if (!it) return;
494
+ if (act === 'pnote') { PBACK.add(id); redraw(`[data-bdn="${CSS.escape(id)}"]`); return; }
495
+ if (act === 'pcancel') { PBACK.delete(id); delete PERR[id]; redraw(`[data-bda="pnote"][data-id="${CSS.escape(id)}"]`); return; }
496
+ const note = (PNOTE[id] || '').trim();
497
+ if (act === 'pback' && !note) { PERR[id] = 'Write one line for the agent. A note starts its next run.'; redraw(`[data-bdn="${CSS.escape(id)}"]`); return; }
498
+ BUSY = id; b.disabled = true;
499
+ const r = await pmPost('/api/driver/' + (act === 'pkeep' ? 'keep' : act === 'pback' ? 'return' : 'drop'), { ws: it.ws, proposal: id, ...(act === 'pback' ? { note } : {}) });
500
+ BUSY = '';
501
+ if (!r || r.ok !== true) { PERR[id] = (r && r.error) || 'It was not recorded.'; redraw(); return; }
502
+ delete PERR[id]; PBACK.delete(id);
503
+ DEC.set(id, { item: it, st: act === 'pkeep' ? 'kept' : act === 'pback' ? 'back' : 'dropped', note, wrote: r.wrote, warnings: r.warnings || [] });
504
+ toast(act === 'pkeep' ? 'Kept.' : act === 'pback' ? 'Sent back with your note.' : 'Dropped. It counts as a correction.');
505
+ await readAll(['prop']); redraw(`.bd-it[data-id="${CSS.escape(id)}"] .bd-done`);
506
+ }
507
+ const openPropsDlg = () => {
508
+ const n = openProps().length;
509
+ bdDlg('prop', 'Agent proposals · real data', 'Agent proposals', 'The Initiative Driver, read from each product\'s ledger',
510
+ A.prop && A.prop.ok ? (n ? pl(n, 'proposal waits', 'proposals wait') + ' for you. Keep one to record it, send it back with a note, or drop it.' : 'No proposal waits for you.') : 'The proposals could not be read.', propsHtml, propPress,
511
+ (e) => { const t = e.target.closest('[data-bdn]'); if (!t) return; PNOTE[t.dataset.bdn] = t.value; const k = $(`[data-bda="pback"][data-id="${CSS.escape(t.dataset.bdn)}"]`, $('#oMain')); if (k) k.disabled = !t.value.trim(); });
512
+ };
513
+
514
+ /* ── mentions ── */
515
+ const taskLine = (m) => (m.reply ? 'Reply to ' + (m.who ? first(m.who) : 'the sender') + ' (' + srcName(m.source) + ') by today' : 'Read ' + (m.who ? first(m.who) : 'the sender') + '\'s note (' + srcName(m.source) + ')');
516
+ function menHtml() {
517
+ const a = A.men; if (!a.ok) return `<p class="nodef err" role="alert">Mentions ${esc(said(a))}</p>`;
518
+ if (a.list === null) return '<p class="empty3">No brief for today, so no mentions were read.</p><p class="note">Mentions come from today\'s brief. Nothing here replies, reacts or posts in Slack, Jira, Confluence or mail.</p>';
519
+ const l = shownMen(), ORD = ['slack', 'jira', 'confluence', 'mail'], srcs = ORD.filter((k) => l.some((m) => m.source === k)).concat([...new Set(l.map((m) => m.source))].filter((k) => !ORD.includes(k)));
520
+ if (MTAB !== 'all' && !srcs.includes(MTAB)) MTAB = 'all';
521
+ const rows = l.filter((m) => MTAB === 'all' || m.source === MTAB).sort((x, y) => (y.reply - x.reply) || ((y.at ? Date.parse(y.at) : 0) - (x.at ? Date.parse(x.at) : 0)));
522
+ const tabs = `<div class="seg2" role="group" aria-label="Source">${['all', ...srcs].map((k) => `<button type="button" data-bda="mtab" data-k="${esc(k)}" aria-pressed="${MTAB === k}">${k === 'all' ? 'All ' + l.length : esc(srcName(k)) + ' ' + l.filter((m) => m.source === k).length}</button>`).join('')}</div>`;
523
+ const item = (m) => {
524
+ const link = bdLink(m.link), when = mWhen(m.at);
525
+ const acts = m.read ? bdActs(bdBtn('Mark unread', 'munread', m.id, true))
526
+ : bdActs(MADD.has(m.id) ? bdDone(true, 'In your Work list.') : bdBtn('Make it a task', 'madd', m.id), bdBtn('Mark read', 'mread', m.id, true), link ? `<a class="cta alt" href="${esc(link)}" target="_blank" rel="noopener noreferrer" data-bdlink="${esc(m.id)}">Open in ${esc(srcName(m.source))}</a>` : '')
527
+ + (MADD.has(m.id) ? '' : `<p class="bd-why">Make it a task adds “${esc(taskLine(m))}” to your Work list. Mark read hides it from today's list.</p>`) + bdFail(m.id, SERR);
528
+ return `<div class="bd-it${m.read ? ' decided' : ''}" data-id="${esc(m.id)}"><div class="bd-h">${bdChip(srcName(m.source) + (m.where ? ' · ' + m.where : ''))}${when ? bdChip(when, 'mono') : ''}${m.reply ? bdChip('Needs your reply', 'warn') : bdChip('For your information')}</div><span class="bd-t">${esc(m.who || srcName(m.source))}</span><p class="bd-q">${esc(m.text)}</p>${m.initiative ? `<p class="bd-why">${esc(m.initiative)}</p>` : ''}${acts}</div>`;
529
+ };
530
+ return (l.length ? `<div class="bd-top">${tabs}</div><div class="bd-list">${rows.map(item).join('')}</div>` : '<p class="empty3">' + CHECK + 'No one has mentioned you today.</p>')
531
+ + '<p class="note">Mentions come from today\'s brief. A mention that is already a row under What you need to do is not listed here. Nothing here replies, reacts or posts in Slack, Jira, Confluence or mail.</p>';
532
+ }
533
+ async function menPress(e, redraw) {
534
+ const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
535
+ const act = b.dataset.bda, id = b.dataset.id;
536
+ if (act === 'mtab') { MTAB = b.dataset.k; redraw(`[data-bda="mtab"][data-k="${CSS.escape(MTAB)}"]`); return; }
537
+ const m = shownMen().find((x) => x.id === id); if (!m) return;
538
+ BUSY = id; b.disabled = true; delete SERR[id];
539
+ const r = act === 'madd' ? await pmPost('/api/pm-items/add', { line: taskLine(m) }) : await pmPost('/api/mentions/read', { id, read: act === 'mread' });
540
+ BUSY = '';
541
+ if (!r || r.ok === false) { SERR[id] = 'That did not go through' + (r && r.error ? ': ' + r.error : '.'); redraw(); return; }
542
+ if (act === 'madd') { MADD.add(id); toast('Added to Work: ' + taskLine(m).replace(/ by today$/, '')); redraw(`.bd-it[data-id="${CSS.escape(id)}"] [data-bda="mread"]`); }
543
+ else { MREAD.set(id, act === 'mread'); toast(act === 'mread' ? 'Marked read.' : 'Marked unread.'); redraw(`.bd-it[data-id="${CSS.escape(id)}"] button`); }
544
+ drawAround();
545
+ }
546
+ const openMen = () => {
547
+ const l = shownMen();
548
+ bdDlg('men', 'Mentions · real data', 'Mentions', 'Slack, Jira, Confluence and mail · today\'s brief', A.men && A.men.ok && A.men.list ? menLine(l) + ' Make one a task, mark it read, or open it where it was said.' : 'Mentions could not be read from today\'s brief.', menHtml, menPress);
549
+ };
550
+
551
+ /* ── portfolio pulse ── */
552
+ function pulseHtml() {
553
+ const a = A.pulse; if (!a.ok) return `<p class="nodef err" role="alert">Portfolio pulse ${esc(said(a))}</p>`;
554
+ const g = groups(a.rows), n = a.rows.length + a.none, item = (r) => `<div class="bd-it"><div class="bd-h">${bdChip(r.word, r.cls === 'bad' ? 'hot' : r.cls === 'warn' ? 'warn' : '')}${r.pname ? bdChip(r.pname, 'mono') : ''}</div><span class="bd-t">${esc(r.title)}</span><p class="bd-why">${esc(r.why)}</p>${bdActs(`<a class="cta alt" href="/premium-initiative.html?id=${encodeURIComponent(r.id)}${r.ws ? '&ws=' + encodeURIComponent(r.ws) : ''}">Open the initiative</a>`)}</div>`;
555
+ const hot = g.bad.concat(g.warn);
556
+ return `<div class="bd-leg">${['bad', 'warn', 'ok', 'none'].map((k) => `<span><i class="${k}"></i>${PGW[k]} ${k === 'none' ? g.none.length + a.none : g[k].length}</span>`).join('')}</div>${n ? bar(g, n, a.none) : ''}`
557
+ + H2('Needs a look') + (hot.length ? `<div class="bd-list">${hot.map(item).join('')}</div>` : '<p class="note">Nothing is late or at risk.</p>')
558
+ + `<details class="bd-more"><summary>${g.ok.length} on plan</summary><div class="bd-list">${g.ok.map(item).join('')}</div></details>`
559
+ + `<details class="bd-more"><summary>${g.none.length + a.none} with no plan date</summary><div class="bd-list">${g.none.map(item).join('')}</div>${a.none ? `<p class="note">${pl(a.none, 'more initiative has', 'more initiatives have')} no promised date and no Jira read, so they are not listed.</p>` : ''}</details>`
560
+ + (a.errs.length ? `<p class="note">Not read: ${esc(a.errs[0])}</p>` : '') + '<p class="note">The status is the Calendar\'s: the promised date against the forecast, or the Jira read. It is not a forecast of its own, and nothing here changes a record.</p>';
561
+ }
562
+ const openPulse = () => {
563
+ const a = A.pulse, g = a && a.ok ? groups(a.rows) : null;
564
+ bdDlg('pulse', 'Portfolio pulse · real data', 'Portfolio pulse', 'The initiatives, by the Calendar\'s own status', g ? `${g.bad.length} late and ${g.warn.length} at risk, of ${a.rows.length + a.none}. The late and at-risk ones are listed first. Opening one takes you to its page.` : 'The initiatives could not be read.', pulseHtml, () => {});
565
+ };
566
+
567
+ /* ── horizon scan ── */
568
+ const SKIND = { create: ['New initiative', 'Approve', 'The initiative was created in the first stage of the board.'], research: ['Research', 'Start the research', 'A research scan was started.'], attach: ['Evidence', 'Approve', 'An evidence line was written.'] };
569
+ const sDoes = (p) => {
570
+ const f = p.fields || {};
571
+ return p.kind === 'create' ? 'Approve creates the initiative in the first stage of the ' + (f.board || 'board') + ' workflow.' : p.kind === 'research' ? 'Start the research starts a research scan' + (f.question ? ' for “' + f.question + '”' : '') + '.' : 'Approve writes an evidence line on ' + (f.initiative || 'the initiative') + '.';
572
+ };
573
+ function scanProp(p, ws) {
574
+ const d = SDEC.get(p.id), k = SKIND[p.kind] || [p.kind, 'Approve', 'It is recorded.'], f = p.fields || {};
575
+ const act = d ? bdDone(d.st === 'ok', d.st === 'ok' ? 'Approved. ' + k[2] : 'Dismissed. It counts as a correction.') + (d.st === 'no' ? bdActs(bdBtn('Undo', 'sundo', p.id, true, ` data-ws="${esc(ws)}"`)) : '')
576
+ : SOPEN.has(p.id) ? `<label class="bd-l" for="bds-${esc(p.id)}">Why dismiss it? A reason is required.</label><input type="text" id="bds-${esc(p.id)}" data-bds="${esc(p.id)}" maxlength="500" value="${esc(SWHY[p.id] || '')}" placeholder="For example: we already decided this">${bdFail(p.id, SERR)}`
577
+ + bdActs(bdBtn('Dismiss', 'sdis', p.id, false, ` data-ws="${esc(ws)}"${(SWHY[p.id] || '').trim() ? '' : ' disabled'}`), bdBtn('Cancel', 'sdiscancel', p.id, true)) + '<p class="bd-why">A dismissal counts as a correction. The scan will not raise the same thing again.</p>'
578
+ : bdActs(bdBtn(k[1], 'sapp', p.id, false, ` data-ws="${esc(ws)}"`), bdBtn('Dismiss', 'sdisopen', p.id, true)) + `<p class="bd-why">${esc(sDoes(p))} Dismiss asks for a reason and counts as a correction.</p>` + bdFail(p.id, SERR);
579
+ return `<div class="bd-it${d ? ' decided' : ''}" data-id="${esc(p.id)}"><div class="bd-h">${bdChip(k[0])}${f.board ? bdChip(f.board) : ''}</div><span class="bd-t">${esc(p.title)}</span>${p.why ? `<p class="bd-why">${esc(p.why)}</p>` : ''}${p.finding ? `<p class="bd-q">${esc(p.finding)}</p>` : ''}${act}</div>`;
580
+ }
581
+ function scanPart(s) {
582
+ const lastWord = s.last ? dayWord(s.last.at) + (s.last.ok === false ? ' (did not finish' + (s.last.reason ? ': ' + s.last.reason : '') + ')' : '') : 'No scan has run yet';
583
+ const nextWord = s.switched_off ? 'Scans are switched off on this machine' : s.next ? dayWord(s.next) + (s.schedule ? ' · ' + s.schedule : '') : (s.schedule || 'Not scheduled');
584
+ let ctl;
585
+ if (s.open) ctl = `<div class="bd-it"><span class="bd-t">Scanning now</span><div class="bd-steps">${(s.open.steps || []).map((x) => `<div class="${esc(x.state)}"><i></i>${esc(x.label || x.id)}${x.state === 'work' ? ' …' : ''}</div>`).join('')}</div>${bdActs(bdBtn(s.open.stopping ? 'Stopping…' : 'Stop', 'sstop', s.ws, true, s.open.stopping ? ' disabled' : ''))}<p class="bd-why">Stop ends the scan. Nothing it has not filed is written.</p></div>`;
586
+ else {
587
+ const m = s.manual || {}, no = s.switched_off ? 'Scans are switched off on this machine.' : m.ok === false ? (m.error || 'A manual scan cannot start now.') : '';
588
+ ctl = bdActs(bdBtn('Scan now', 'snow', s.ws, false, no ? ' disabled' : '')) + `<p class="bd-why">${no ? esc(no) + ' ' : ''}Scan now starts an agent that reads the public web for your watch list and this repository, then writes reports with proposals. Nothing acts until you approve it.${m.limit ? ' ' + m.left + ' of ' + m.limit + ' manual scans left today.' : ''}</p>`;
589
+ }
590
+ const top = s.reports.filter((r) => !r.parent && r.written), scan = s.last && s.last.scan, show = top.filter((r) => r.scan === scan || (r.proposals && r.proposals.open > 0) || [...SDEC.values()].some((d) => d.p.report === r.id));
591
+ const reps = show.map((r) => {
592
+ const ps = s.proposals.filter((p) => p.report === r.id), dec = [...SDEC.entries()].filter(([, d]) => d.p.report === r.id && !ps.some((p) => p.id === d.p.id)).map(([, d]) => d.p), all = ps.concat(dec);
593
+ return H2(r.label || r.type + ' report') + `<p class="bd-q">${esc(r.title)}</p><p class="bd-why">From: ${esc(r.origin || 'the repository')} · ${ps.length} of ${(r.proposals && r.proposals.total) || all.length} proposals wait</p><div class="bd-list">${all.map((p) => scanProp(p, s.ws)).join('')}</div>`;
594
+ }).join('');
595
+ return (s.pname ? H2(s.pname) : '') + kv([['Last scan', lastWord], ['Next', nextWord]]) + ctl + (reps || (s.last ? '<p class="note">The last scan wrote no report.</p>' : ''));
596
+ }
597
+ function scanHtml() {
598
+ const a = A.scan; if (!a.ok) return `<p class="nodef err" role="alert">Horizon scan ${esc(said(a))}</p>`;
599
+ return a.scans.map(scanPart).join('') + (a.errs.length ? `<p class="note">Not read: ${esc(a.errs[0])}</p>` : '') + '<p class="note">One scan covers the whole product. The watch list, the scan setting, the report documents and Change on a proposal stay in the console.</p>';
600
+ }
601
+ let SPOLL = null;
602
+ function scanPoll(redraw) {
603
+ clearTimeout(SPOLL);
604
+ if (!A.scan || !A.scan.ok || !A.scan.scans.some((s) => s.open)) return;
605
+ SPOLL = setTimeout(async () => {
606
+ if ($('#oMain').dataset.bd !== 'scan' || !$('#dlg').classList.contains('on')) return;
607
+ const before = JSON.stringify(A.scan); await readAll(['scan']);
608
+ if (JSON.stringify(A.scan) !== before) redraw();
609
+ scanPoll(redraw);
610
+ }, 4000);
611
+ }
612
+ async function scanPress(e, redraw) {
613
+ const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
614
+ const act = b.dataset.bda, id = b.dataset.id, ws = b.dataset.ws || '';
615
+ if (act === 'sdisopen') { SOPEN.add(id); redraw(`[data-bds="${CSS.escape(id)}"]`); return; }
616
+ if (act === 'sdiscancel') { SOPEN.delete(id); delete SERR[id]; redraw(`[data-bda="sdisopen"][data-id="${CSS.escape(id)}"]`); return; }
617
+ const why = (SWHY[id] || '').trim();
618
+ if (act === 'sdis' && !why) return;
619
+ BUSY = id; b.disabled = true;
620
+ let r;
621
+ if (act === 'snow') r = await pmPost('/api/scan/now', { ws: id });
622
+ else if (act === 'sstop') r = await pmPost('/api/scan/stop', { ws: id });
623
+ else r = await pmPost('/api/scan/proposal', { ws, id, action: act === 'sapp' ? 'approve' : act === 'sdis' ? 'dismiss' : 'undo', ...(act === 'sdis' ? { why } : {}) });
624
+ BUSY = '';
625
+ if (!r || r.ok !== true) { SERR[id] = (r && r.error) || 'It did not go through.'; redraw(); toast(SERR[id]); return; }
626
+ delete SERR[id];
627
+ if (act === 'sapp' || act === 'sdis') { const p = A.scan.scans.flatMap((s) => s.proposals).find((x) => x.id === id); if (p) SDEC.set(id, { st: act === 'sapp' ? 'ok' : 'no', p }); SOPEN.delete(id); toast(act === 'sapp' ? 'Approved.' : 'Dismissed. It counts as a correction.'); }
628
+ else if (act === 'sundo') { SDEC.delete(id); toast('The dismissal was taken back.'); }
629
+ else toast(act === 'snow' ? 'Scan started. It runs in the background.' : 'Stopping the scan.');
630
+ await readAll(['scan']); redraw(act === 'snow' ? '[data-bda="sstop"]' : act === 'sstop' ? '[data-bda="snow"]' : `.bd-it[data-id="${CSS.escape(id)}"] .bd-done`); scanPoll(redraw);
631
+ }
632
+ const openScan = () => {
633
+ const w = scanOpen();
634
+ const redraw = bdDlg('scan', 'Horizon scan · real data', 'Horizon scan', 'One scan for the whole product', A.scan && A.scan.ok ? (w ? pl(w, 'proposal waits', 'proposals wait') + ' for you. Nothing acts until you approve it.' : 'No proposal waits for you. Nothing acts until you approve it.') : 'The scan could not be read.', scanHtml, scanPress,
635
+ (e) => { const t = e.target.closest('[data-bds]'); if (!t) return; SWHY[t.dataset.bds] = t.value; const k = $(`[data-bda="sdis"][data-id="${CSS.escape(t.dataset.bds)}"]`, $('#oMain')); if (k) k.disabled = !t.value.trim(); });
636
+ scanPoll(redraw);
637
+ };
638
+
639
+ /* ── data freshness ── */
640
+ const SSTATE = { fresh: 'Recent', stale: 'Old', never: 'Never read', building: 'Reading now…', failed: 'Failed', off: 'Off' };
641
+ const SNOTE = {};
642
+ const limitWord = (ms) => (ms >= 48 * 3600000 ? Math.round(ms / 86400000) + ' days' : Math.round(ms / 3600000) + ' hours');
643
+ function srcHtml() {
644
+ const a = A.src; if (!a.ok) return `<p class="nodef err" role="alert">Data freshness ${esc(said(a))}</p>`;
645
+ const b = behindSrc(), many = refreshTargets(a.sources);
646
+ const row = (s) => {
647
+ const when = s.id === 'repository' && s.state === 'fresh' ? 'watching' : s.as_of ? whenRead(s.as_of) : 'never';
648
+ const sch = s.schedule ? [s.schedule.cadence, s.schedule.day, s.schedule.time].filter(Boolean).join(' ') : s.skill ? 'no schedule' : 'on every change';
649
+ return `<div class="bd-src"><span><b>${esc(s.label)}</b><small><span class="bd-st ${esc(s.state)}">${esc(SSTATE[s.state] || s.state)}</span> · ${esc(when)} · ${esc(sch)}${s.stale_after_ms ? ' · old after ' + esc(limitWord(s.stale_after_ms)) : ''}</small><small>${s.skill ? 'Refresh starts the ' + esc(s.skill) + ' skill in an agent session, with your own connection.' : 'Refresh rebuilds the facts on this machine.'}</small>${SNOTE[s.id] ? `<small role="status">${esc(SNOTE[s.id])}</small>` : ''}</span>${bdBtn('Refresh', 'sfone', s.id, true, (s.state === 'off' || s.state === 'building' ? ' disabled' : '') + ` aria-label="Refresh ${esc(s.label)}"`)}</div>`;
650
+ };
651
+ return `<div class="bd-top"><p>Sources are read on a schedule, not live. ${b.length ? pl(b.length, 'source needs', 'sources need') + ' a new read.' : 'None is old.'}</p>${bdBtn('Refresh all', 'sfall', '', false, many.length ? '' : ' disabled')}</div>${a.sources.map(row).join('')}<p class="note">Refresh all reads every source but the repository. The server calls nothing outside this machine: an outside source is read by a skill, with your own connection.</p>`;
652
+ }
653
+ let FPOLL = null;
654
+ function srcPoll(redraw, n) {
655
+ clearTimeout(FPOLL);
656
+ if (!n || !A.src || !A.src.ok || !A.src.sources.some((s) => s.state === 'building')) return;
657
+ FPOLL = setTimeout(async () => { if ($('#oMain').dataset.bd !== 'src' || !$('#dlg').classList.contains('on')) return; await readAll(['src']); redraw(); srcPoll(redraw, n - 1); }, 3000);
658
+ }
659
+ async function srcPress(e, redraw) {
660
+ const b = e.target.closest('[data-bda]'); if (!b || BUSY) return;
661
+ const act = b.dataset.bda, ids = act === 'sfall' ? refreshTargets(A.src.sources) : [b.dataset.id];
662
+ BUSY = 'src'; b.disabled = true;
663
+ const got = await Promise.all(ids.map(async (id) => [id, await pmPost('/api/sources/refresh', { ws: A.src.ws || wsParam() || '', source: id })]));
664
+ BUSY = '';
665
+ let bad = 0;
666
+ for (const [id, r] of got) { if (r && r.ok) SNOTE[id] = r.started === 'session' ? 'An agent session started to read it.' : 'Rebuilding the facts on this machine.'; else { bad++; SNOTE[id] = 'It did not start: ' + ((r && r.error) || 'the server did not answer') + '.'; } }
667
+ toast(bad ? bad + ' of ' + ids.length + ' did not start.' : act === 'sfall' ? 'Reading every source again.' : 'Reading again.');
668
+ await readAll(['src']); redraw(act === 'sfall' ? '[data-bda="sfall"]' : `[data-bda="sfone"][data-id="${CSS.escape(ids[0])}"]`); srcPoll(redraw, 8);
669
+ }
670
+ const openSrc = () => {
671
+ const b = behindSrc();
672
+ const redraw = bdDlg('src', 'Sources · real data', 'Data freshness', 'When each source was last read', A.src && A.src.ok ? (b.length ? joinN(b.map((s) => s.label)) + (b.length === 1 ? ' needs' : ' need') + ' a new read. Refresh one, or all.' : 'Every source was read recently.') : 'The sources could not be read.', srcHtml, srcPress);
673
+ srcPoll(redraw, 8);
674
+ };
675
+
676
+ function mountAround() {
677
+ const t = $('#todayCard'); if (!t) return;
678
+ const s = document.createElement('section');
679
+ s.className = 'card rise'; s.id = 'aroundCard'; s.style.setProperty('--d', '8'); s.setAttribute('aria-labelledby', 'hAround');
680
+ s.innerHTML = `<div class="ch"><span class="ic">${bdIco(BDI.at)}</span><h2 id="hAround">Around you</h2><small id="aroundCap">Reading</small></div><div id="aroundBody" class="bd-rows"></div><p class="note bd-note">Nothing here posts to Slack, Jira, Confluence or mail. A button that records something says what, before you press it.</p>`;
681
+ t.insertAdjacentElement('afterend', s);
682
+ s.addEventListener('click', (e) => {
683
+ const b = e.target.closest('[data-bd]'); if (!b) return;
684
+ ({ prop: openPropsDlg, men: openMen, pulse: openPulse, scan: openScan, src: openSrc })[b.dataset.bd]();
685
+ });
686
+ drawAround();
687
+ }
688
+ mountAround();
689
+
690
+ /* ── the phone moment card: what the day is doing now, above What you need to do, at 640 px and narrower ───────────────────────────────
691
+ * The moment is chosen by momentOf (c3-phone-model.js) from the brief-page day and a clock. Every line below comes from /api/brief-page or /api/phone-day. */
692
+ const PH = { page: null, day: null, dayAt: 0, dec: new Map(), err: {} };
693
+ const phoneOn = () => matchMedia('(max-width:640px)').matches;
694
+ const pHm = (iso) => { const d = new Date(iso); return STAMP(d.getHours()) + ':' + STAMP(d.getMinutes()); };
695
+ const pWho = (m) => (m.people && m.people.length ? m.people.map(first).join(', ') : '');
696
+ const pOwn = () => ((PH.page && PH.page.ok && PH.page.needs) || []).filter((n) => n && n.id && (n.kind === 'overdue' || n.kind === 'due-today'))
697
+ .map((n) => ({ id: n.id, headline: n.headline, label: n.kind === 'overdue' ? (n.days_late === 1 ? '1 day late' : n.days_late + ' days late') : 'Due today', kind: n.kind, looks: !!(n.evidence && n.evidence.text) }));
698
+ const pBtn = (label, act, id, alt) => `<button type="button" class="cta${alt ? ' alt' : ''}" data-pha="${act}"${id != null ? ` data-id="${esc(id)}"` : ''}>${esc(label)}</button>`;
699
+ const pItem = (n) => {
700
+ const d = PH.dec.has(n.id);
701
+ const act = d ? `<p class="bd-done" role="status">${CHECK}<span>Done.</span></p><div class="phacts">${pBtn('Undo', 'phundo', n.id, true)}</div>` : `<div class="phacts">${pBtn(n.looks ? 'Confirm done' : 'Done', 'phdone', n.id)}</div>`;
702
+ return `<div class="phfit" data-id="${esc(n.id)}"><span class="label">${esc(n.label)}</span><b class="phtt">${esc(n.headline)}</b>${act}${PH.err[n.id] ? `<p class="nodef err" role="alert">${esc(PH.err[n.id])}</p>` : ''}</div>`;
703
+ };
704
+ const pItems = (list) => list.concat([...PH.dec.values()].filter((x) => !list.some((y) => y.id === x.id))).map(pItem).join('');
705
+ const pOpen = (m) => pBtn('Open the meeting', 'phopen', m.id, true);
706
+ const pBig = (t) => `<b class="phbig">${esc(t)}</b>`;
707
+ const pL = (t) => `<p class="phl">${esc(t)}</p>`, pS = (t) => `<p class="phs">${esc(t)}</p>`;
708
+ const pDayErr = () => (PH.day && PH.day.ok === false ? pS('Today could not be read: ' + PH.day.error + '.') : !PH.day ? pS('Reading your day.') : '');
709
+ const pNum = (n, one, many) => (n === 1 ? '1 ' + one : (n || 0) + ' ' + many);
710
+ function phMoment(mo) {
711
+ const m = mo.meeting, own = pOwn(), day = PH.day && PH.day.ok !== false ? PH.day : null, fin = day ? day.finished || [] : [];
712
+ const wait = own.length ? pNum(own.length, 'item of yours waits', 'items of yours wait') + '.' : 'Nothing of yours is due.';
713
+ const finRows = (n) => fin.slice(0, n).map((t) => `<div class="phfit"><span class="label">${t.status === 'review' ? 'Waits for you' : t.status === 'sent' ? 'Sent' : 'Finished'}</span><b class="phtt">${esc(t.title)}</b><p class="phs">${esc(t.summary)}</p></div>`).join('');
714
+ if (mo.kind === 'meeting') return `<span class="label">Under way · ends ${esc(inText(mo.minutes))}</span>${pBig(m.title)}${pWho(m) ? pL(pWho(m)) : ''}<div class="phacts">${pOpen(m)}</div>`;
715
+ if (mo.kind === 'before') {
716
+ const prep = (m.prepared || []).slice(0, 3).map((x) => `<p class="phs">${esc(x.text)}</p>`).join('') || pS('Nothing is prepared for it.');
717
+ const bf = (m.before || []).filter((x) => x && x.id && !x.done).map((x) => ({ id: x.id, headline: x.title, label: 'Before you go', kind: 'before' }));
718
+ return `<span class="label">Starts ${esc(inText(mo.minutes))} · ${pHm(m.start)}</span>${pBig(m.title)}${[pWho(m), m.initiative].filter(Boolean).length ? pL([pWho(m), m.initiative].filter(Boolean).join(' · ')) : ''}${prep}${pItems(bf)}<div class="phacts">${pOpen(m)}</div>`;
719
+ }
720
+ if (mo.kind === 'after') return `<span class="label">Just ended · ${pHm(m.end || m.start)}</span>${pBig(m.title)}${pS('The notes of this meeting, if there are any, are in the meeting.')}<div class="phacts">${pOpen(m)}</div>`;
721
+ if (mo.kind === 'gap') return `<span class="label">Until ${esc(mo.next.title)} at ${pHm(mo.next.start)}</span>${pBig(mo.minutes + ' free minutes')}${mo.fits.length ? pItems(mo.fits.map((n) => own.find((o) => o.id === n.id)).filter(Boolean)) : pL('Nothing of yours is due. A good moment to prepare the next meeting.')}`;
722
+ if (mo.kind === 'morning') {
723
+ const top = own.slice(0, 3);
724
+ return `<span class="label">Your morning</span>${pBig(top.length ? ['', 'One thing', 'Two things', 'Three things'][top.length] + ' this morning' : 'Nothing pressing this morning')}${pItems(top)}${pS(wait)}${mo.next ? `<div class="phfit"><b class="phtt">First up: ${esc(mo.next.title)} at ${pHm(mo.next.start)}</b><p class="phs">${esc(inText((Date.parse(mo.next.start) - Date.now()) / 60000).replace(/^in/, 'In'))}${pWho(mo.next) ? ' · ' + esc(pWho(mo.next)) : ''}</p><div class="phacts">${pOpen(mo.next)}</div></div>` : pS('No meetings today.')}`;
725
+ }
726
+ if (mo.kind === 'work') return `<span class="label">${mo.next ? 'Next: ' + esc(mo.next.title) + ' at ' + pHm(mo.next.start) : 'No more meetings today'}</span>${pBig(fin.length ? 'Finished for you' : 'Nothing new from the agent')}${fin.length ? finRows(2) + pS('Approving a draft waits for your computer.') : pDayErr() || pS('When the agent finishes a draft today, it shows here.')}${mo.fits.length ? pItems(mo.fits.map((n) => own.find((o) => o.id === n.id)).filter(Boolean)) : ''}${mo.next ? `<div class="phacts">${pOpen(mo.next)}</div>` : ''}`;
727
+ if (mo.kind === 'recap') {
728
+ const r = day && day.recap, one = own[0];
729
+ return `<span class="label">Evening recap</span>${pBig('How today went')}${r ? `<div class="phstats"><div><b>${r.meetings || 0}</b><span>meetings</span></div><div><b>${r.decided || 0}</b><span>decided in meetings</span></div><div><b>${r.done || 0}</b><span>done by you</span></div></div>${(r.moved || []).length ? `<div class="phfit"><b class="phtt">What moved</b>${r.moved.map((x) => `<p class="phs">${esc(x.text)}${x.sub ? ' · ' + esc(x.sub) : ''}</p>`).join('')}</div>` : ''}` : pDayErr()}<div class="phfit"><b class="phtt">Still open · ${own.length}</b>${own.slice(0, 3).map((x) => pS(x.headline)).join('')}${pS(own.length ? "They come first on tomorrow's Briefing." : 'Nothing of yours is still open.')}</div>${one ? `<div class="phfit"><span class="label">One thing tonight, if you have a minute</span>${pItems([one])}</div>` : ''}`;
730
+ }
731
+ const r = day && day.recap, tm = day && day.tomorrow;
732
+ return `<span class="label">End of day</span>${pBig(tm ? 'Tomorrow, ' + tm.label : 'Tomorrow, at a glance')}${r ? pL('Today: ' + [pNum(r.meetings, 'meeting', 'meetings'), pNum(r.decided, 'decision', 'decisions'), pNum(r.done, 'item done', 'items done')].join(', ') + '.') : ''}${tm ? `<div class="phfit"><b class="phtt">${tm.meetings.length ? pNum(tm.meetings.length, 'meeting', 'meetings') : 'No meetings'}</b>${tm.meetings.slice(0, 5).map((x) => `<p class="phs">${pHm(x.start)} · ${esc(x.title)}${pWho(x) ? ' · ' + esc(pWho(x)) : ''}</p>`).join('')}</div>` : pDayErr()}${pS(own.length ? pNum(own.length, 'item carries', 'items carry') + " over. They open first on tomorrow's Briefing." : 'Nothing carries over.')}`;
733
+ }
734
+ function drawPhone(focus) {
735
+ const c = $('#phoneCard'); if (!c) return;
736
+ c.hidden = !phoneOn(); if (c.hidden) return;
737
+ if (!PH.page) c.innerHTML = '<span class="label">Now</span><p class="phl">Reading your day.</p>';
738
+ else if (!PH.page.ok) c.innerHTML = `<span class="label">Now</span><p class="nodef err" role="alert">Your day ${esc(said(PH.page))}</p>`;
739
+ else { const mo = momentOf({ today: PH.page.today || [], needs: pOwn(), now: new Date() }); c.dataset.moment = mo.kind; c.innerHTML = phMoment(mo); }
740
+ if (focus) { const f = $(focus, c); if (f) f.focus(); }
741
+ }
742
+ async function readPhone(force) {
743
+ if (!phoneOn()) { drawPhone(); return; }
744
+ PH.page = await briefPage(force);
745
+ const mo = PH.page.ok ? momentOf({ today: PH.page.today || [], needs: pOwn(), now: new Date() }) : null;
746
+ if (mo && ['work', 'recap', 'night'].includes(mo.kind) && (force || !PH.day || Date.now() - PH.dayAt > 300000)) { PH.day = await getj('/api/phone-day'); PH.dayAt = Date.now(); }
747
+ drawPhone();
748
+ }
749
+ async function phonePress(e) {
750
+ const b = e.target.closest('[data-pha]'); if (!b || BUSY) return;
751
+ const act = b.dataset.pha, id = b.dataset.id;
752
+ if (act === 'phopen') {
753
+ const m = ((PH.page && PH.page.today) || []).find((x) => x.id === id); if (!m) return;
754
+ if (!(await week.openToday({ at: Date.parse(m.start), title: m.title }))) toast('The calendar PMOS holds does not list that meeting, so it could not be opened.');
755
+ return;
756
+ }
757
+ const n = pOwn().find((x) => x.id === id) || (PH.dec.get(id)) || (((PH.page && PH.page.today) || []).flatMap((x) => x.before || []).map((x) => ({ id: x.id, headline: x.title, label: 'Before you go', kind: 'before' })).find((x) => x.id === id));
758
+ if (!n) return;
759
+ BUSY = id; b.disabled = true; delete PH.err[id];
760
+ const r = await pmPost(act === 'phdone' ? '/api/pm-items/done' : '/api/pm-items/reopen', { id });
761
+ BUSY = '';
762
+ if (!r || r.ok === false) { PH.err[id] = 'That did not go through' + (r && r.error ? ': ' + r.error : '.'); drawPhone(`.phfit[data-id="${CSS.escape(id)}"] button`); return; }
763
+ if (act === 'phdone') { PH.dec.set(id, n); toast('Done: ' + n.headline); } else { PH.dec.delete(id); toast('Reopened: ' + n.headline); }
764
+ drawPhone(`.phfit[data-id="${CSS.escape(id)}"] button`);
765
+ await readPhone(true); drawPhone(`.phfit[data-id="${CSS.escape(id)}"] button`);
766
+ }
767
+ function mountPhone() {
768
+ const anchor = $('#hMoves') && $('#hMoves').closest('.cols2'); if (!anchor) return;
769
+ const s = document.createElement('section');
770
+ s.className = 'card rise phm'; s.id = 'phoneCard'; s.hidden = true; s.setAttribute('aria-label', 'Now'); s.style.setProperty('--d', '5');
771
+ anchor.insertAdjacentElement('beforebegin', s);
772
+ s.addEventListener('click', phonePress);
773
+ const mq = matchMedia('(max-width:640px)'), again = () => { if (!document.hidden) readPhone(); };
774
+ (mq.addEventListener ? mq.addEventListener('change', again) : mq.addListener(again));
775
+ document.addEventListener('visibilitychange', again);
776
+ setInterval(() => { if (!document.hidden && phoneOn()) { PH.page && PH.page.ok ? drawPhone() : null; readPhone(true); } }, 60000);
777
+ readPhone();
778
+ }
779
+ mountPhone();
780
+
255
781
  /* ── load ───────────────────────────────────────────────────────────────────────────────────────────────── */
256
- let readTimer = null;
782
+ let readTimer = null, AROUND = false;
257
783
  const ago = (ms) => { const m = Math.round(ms / 60000); return m < 1 ? 'just now' : m < 90 ? m + ' min ago' : Math.round(m / 60) + ' h ago'; };
258
784
  async function load() {
259
785
  let r = null, status = 0;
@@ -273,6 +799,7 @@ async function load() {
273
799
  return;
274
800
  }
275
801
  M = r.model; drawHero(); drawRows(); drawChips(); drawTl(); drawDock(); drawPick(); onScroll();
802
+ if (!AROUND) { AROUND = true; readAll(); setInterval(() => { if (!document.hidden && !$('#dlg').classList.contains('on')) readAll(); }, 300000); }
276
803
  const age = Date.now() - r.as_of;
277
804
  if (age > 5 * 60000) $('#snap').textContent += ' · read ' + ago(age) + (r.refreshing ? ', refreshing' : '');
278
805
  if (r.error) $('#snap').textContent += ' · the latest read failed: ' + r.error.slice(0, 120);
@@ -0,0 +1,9 @@
1
+ {
2
+ "_comment": "Initiative premium-briefing-depth: the Around you card on the premium Briefing (agent proposals, mentions, portfolio pulse, horizon scan, data freshness), against the real server on a scratch repository with a seeded driver ledger, scan ledger and brief.",
3
+ "seconds": {
4
+ "premium-briefing-depth-test.js": 90
5
+ },
6
+ "panels": [
7
+ "premium-briefing-depth-test.js"
8
+ ]
9
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "_comment": "Initiative premium-phone-card: the phone moment card on the premium Briefing at 640px and below, against the real server with the clock set per moment; Done and Reopen press the real routes.",
3
+ "seconds": {
4
+ "premium-phone-card-test.js": 90
5
+ },
6
+ "panels": [
7
+ "premium-phone-card-test.js"
8
+ ]
9
+ }