create-pmos 0.614.0 → 0.616.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 (44) hide show
  1. package/package.json +57 -39
  2. package/payload/KIT-VERSION +1 -1
  3. package/payload/planning/evals/eval-calibration.md +1 -1
  4. package/payload/planning/okrs/health-budgets.md +1 -1
  5. package/payload/state/discoveries.md +1 -1
  6. package/workspace/changelog.json +56 -0
  7. package/workspace/guide/backlog.md +70 -0
  8. package/workspace/guide/cli.md +1 -0
  9. package/workspace/guide/index.md +1 -0
  10. package/workspace/guide/layout.md +5 -4
  11. package/workspace/guide/programs.md +1 -1
  12. package/workspace/guide/routine.md +1 -1
  13. package/workspace/lib/backlog.js +323 -0
  14. package/workspace/lib/day-run.js +3 -2
  15. package/workspace/lib/doc-library.js +26 -3
  16. package/workspace/lib/events-place.js +45 -9
  17. package/workspace/lib/jira-status.js +4 -1
  18. package/workspace/lib/mention-cli.js +7 -5
  19. package/workspace/lib/mention-store.js +9 -5
  20. package/workspace/lib/route-modules.js +1 -0
  21. package/workspace/lib/routes-backlog.js +283 -0
  22. package/workspace/lib/routes-boards.js +13 -0
  23. package/workspace/package-lock.json +2 -2
  24. package/workspace/package.json +1 -1
  25. package/workspace/public/pm/bd-backlog.css +158 -0
  26. package/workspace/public/pm/bd-backlog.js +531 -0
  27. package/workspace/public/pm/bk-model.js +169 -0
  28. package/workspace/public/pm/cozy-events-view.js +23 -4
  29. package/workspace/public/pm/cozy-events.js +8 -2
  30. package/workspace/public/pm/cozy-pick.js +6 -3
  31. package/workspace/public/pm/cozy-routine.js +3 -2
  32. package/workspace/public/pm/cozy-today-app.js +23 -5
  33. package/workspace/public/pm/cozy-today-model.js +44 -10
  34. package/workspace/public/pm/cozy-today-page.css +9 -1
  35. package/workspace/public/pm/cozy-today-view.js +14 -9
  36. package/workspace/public/pm/home-app.js +5 -0
  37. package/workspace/public/pm/mention-one-model.js +6 -4
  38. package/workspace/public/pm/premium-board.js +21 -3
  39. package/workspace/public/pm/premium-goals.js +12 -9
  40. package/workspace/public/pm/premium-library.js +15 -3
  41. package/workspace/public/pm/scope-chip.js +5 -2
  42. package/workspace/public/premium-board.html +1 -0
  43. package/workspace/skills/morning-brief.skill +1 -1
  44. package/workspace/test-lists/backlog.json +9 -0
@@ -0,0 +1,531 @@
1
+ /* pm/bd-backlog.js — the Backlog in Work: every open task of the picked products in one list, Jira-style (initiative work-backlog; Exploring 2
2
+ * page "Backlog: every task in one list", boards BkList and BkSelect; brief nav-structure/backlog/build-brief.md).
3
+ *
4
+ * · Work's header gets a switch, Initiatives | Backlog (the count of open tasks). Not a place of its own on the rail. The choice is kept per
5
+ * product pick in this browser (localStorage pmos.backlog.view); ?work=backlog opens it.
6
+ * · Columns: Task (□ a task, ◇ a milestone), Jira ticket, Epic ("No epic" when a ticket has none), Initiative, Who, State. No Stage: a
7
+ * stage is an initiative's, never a task's. A late task says so in State ("To do · 8 days late").
8
+ * · Groups (pm/bk-model.js): Needs your review · PMOS is working · PMOS can take these · With people · Nobody has these · No home ·
9
+ * Done by PMOS today.
10
+ * · Quick filters with counts; the tune button opens Sort and the facets Initiative, Who, Epic, Sprint and Status; "Showing … · N hidden ·
11
+ * Show all" says what is filtered.
12
+ * · Tick rows: the bar gives them to PMOS or a person, moves them to an initiative, sets a date or archives them.
13
+ * · A row's name opens the task; Review opens what PMOS made (the pull request, the document or the message) with Approve and Send back.
14
+ * Every write is a route's own (lib/routes-backlog.js, and the Board's task routes for a person, a date, an initiative and Archive) and comes
15
+ * with Undo where the route has one. The words say PMOS, never the model's name. pm/premium-board.js calls sync() after each read of the board. */
16
+ import * as BM from './bk-model.js';
17
+
18
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
19
+ const SV = (d, n) => `<svg viewBox="0 0 24 24"${n ? ` width="${n}" height="${n}"` : ''} aria-hidden="true"><path d="${d}"/></svg>`;
20
+ const I = {
21
+ chev: 'M9 6l6 6-6 6', down: 'M7 10l5 5 5-5', ok: 'M5 12.5l4.5 4.5L19 7', x: 'M6 6l12 12M18 6L6 18', more: 'M5 12h.01M12 12h.01M19 12h.01',
22
+ undo: 'M9 14L4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3', jira: 'M12 3l9 9-9 9-9-9z', task: 'M6 6h12v12H6z', ms: 'M12 4l8 8-8 8-8-8z', back: 'M15 6l-6 6 6 6',
23
+ ext: 'M14 4h6v6M20 4l-9 9M10 6H5v13h13v-5', ret: 'M20 5v7a4 4 0 0 1-4 4H5M9 12l-4 4 4 4',
24
+ };
25
+ const SPARK = '✦';
26
+ const KEY = 'pmos.backlog.view';
27
+ const PREFS = 'pmos.backlog.prefs';
28
+
29
+ let A = null; // the page's api (sync)
30
+ let SC = null; // while a press in an embedded list runs (bindList): { api, tasks }
31
+ let LASTAPI = null; // the api of the last embedded press: its Undo and Review run after the press, on a page that may have no Backlog
32
+ const AP = () => (SC ? SC.api : A || LASTAPI);
33
+ let DATA = null; // { tasks, modes, readAt, err }
34
+ let loading = false, lastScope = '', loadedAt = 0;
35
+ let CHIPS = new Set(), PICK = {}, SORT = 'due';
36
+ let FOLD = {}; // group key → open (true) | folded (false), as the PM left it
37
+ let MORE = new Set(); // the groups whose "N more" was pressed
38
+ let SEL = new Set(); // ticked rows: ws|board|id
39
+ let host = null, sw = null;
40
+ let iniApplied = false; // ?ini= is read once
41
+ let SAID = null; // the one line after a Yes: { text, undo }
42
+
43
+ const box = () => { try { return typeof localStorage !== 'undefined' ? localStorage : null; } catch { return null; } };
44
+ const get = (k, d) => { try { const s = box(); const v = s ? JSON.parse(s.getItem(k) || 'null') : null; return v == null ? d : v; } catch { return d; } };
45
+ const put = (k, v) => { try { const s = box(); if (s) s.setItem(k, JSON.stringify(v)); } catch { /* a private window keeps it for this page */ } };
46
+ const scopeKey = () => (A ? A.scope().map((s) => s.ws + '|' + (s.board || '')).sort().join(',') : '');
47
+ const uidOf = (t) => t.ws + '|' + t.board + '|' + t.id;
48
+
49
+ /** Is the Backlog the view now? The address first (?work=backlog), then what the PM chose for this pick. */
50
+ export function on() {
51
+ const q = new URLSearchParams(location.search).get('work');
52
+ if (q === 'backlog') return true;
53
+ if (q === 'initiatives') return false;
54
+ return (get(KEY, {}) || {})[scopeKey()] === 'bk';
55
+ }
56
+ function setOn(v) {
57
+ const m = get(KEY, {}) || {}; m[scopeKey()] = v ? 'bk' : 'ini'; put(KEY, m);
58
+ const q = new URLSearchParams(location.search); if (q.has('work')) { q.delete('work'); const s = q.toString(); history.replaceState(history.state, '', location.pathname + (s ? '?' + s : '')); }
59
+ apply();
60
+ }
61
+
62
+ /* ── reading ──────────────────────────────────────────────────────────────────────────────────────────────────── */
63
+ async function readOne(s, tries = 0) {
64
+ let r = null, status = 0;
65
+ try { const res = await fetch('/api/backlog?ws=' + encodeURIComponent(s.ws) + (s.board ? '&board=' + encodeURIComponent(s.board) : ''), { credentials: 'same-origin' }); status = res.status; r = await res.json(); } catch { r = null; }
66
+ if (status === 202 && tries < 8) { await new Promise((f) => setTimeout(f, 1500)); return readOne(s, tries + 1); }
67
+ return r && r.ok ? r : null;
68
+ }
69
+ export async function load() {
70
+ if (SC) { if (SC.api.reload) await SC.api.reload(); return; } // an embedded list reads again through its own page
71
+ if (!A || loading) return;
72
+ loading = true;
73
+ const S = A.scope();
74
+ const got = await Promise.all(S.map((s) => readOne(s)));
75
+ loading = false; loadedAt = Date.now();
76
+ const ok = got.filter(Boolean);
77
+ DATA = { tasks: ok.flatMap((r) => r.tasks || []), modes: ok.map((r) => ({ product: r.product, mode: r.mode, label: r.modeLabel, kinds: r.kinds || null })), inis: ok.flatMap((r) => (r.inis || []).map((x) => ({ ...x, ws: r.ws, board: r.board, product: r.product }))),
78
+ err: ok.length ? (ok.length < S.length ? 'One product could not be read; its tasks are not here.' : '') : 'The tasks could not be read. Try again in a moment.', many: S.length > 1 };
79
+ // ?ini=<initiative id> (the initiative popup's "Open in Backlog"): the Initiative facet starts on that initiative, once
80
+ if (!iniApplied) {
81
+ iniApplied = true;
82
+ const want = new URLSearchParams(location.search).get('ini');
83
+ const hit = want && (DATA.inis || []).find((x) => x.id === want);
84
+ if (hit) PICK = { ...PICK, ini: new Set([hit.title]) };
85
+ }
86
+ // ticks that left the list go with them
87
+ const ids = new Set(DATA.tasks.map(uidOf)); for (const k of [...SEL]) if (!ids.has(k)) SEL.delete(k);
88
+ drawSwitch(); if (on()) draw();
89
+ }
90
+
91
+ /* ── the switch in Work's header ──────────────────────────────────────────────────────────────────────────────── */
92
+ function drawSwitch() {
93
+ if (!sw) return;
94
+ const n = DATA ? DATA.tasks.filter(BM.isOpen).length : null, bk = on();
95
+ sw.innerHTML = `<button type="button" role="tab" aria-selected="${!bk}" class="${bk ? '' : 'on'}" data-bksw="ini">Initiatives</button>`
96
+ + `<button type="button" role="tab" aria-selected="${bk}" class="${bk ? 'on' : ''}" data-bksw="bk">Backlog${n ? `<span class="k">${n}</span>` : ''}</button>`;
97
+ }
98
+ function apply() {
99
+ const bk = on();
100
+ document.body.classList.toggle('bk-on', bk);
101
+ if (host) host.hidden = !bk;
102
+ drawSwitch();
103
+ if (bk) { if (!DATA || scopeKey() !== lastScope) { lastScope = scopeKey(); host.innerHTML = '<p class="bk-wait">Reading the tasks…</p>'; load(); } else draw(); }
104
+ else closeAll();
105
+ }
106
+
107
+ /* ── the list ─────────────────────────────────────────────────────────────────────────────────────────────────── */
108
+ const partB = () => true;
109
+ function draw() {
110
+ if (!host || !DATA) return;
111
+ const T = DATA.tasks, cnt = BM.chipCounts(T, partB());
112
+ const chips = BM.CHIPS.filter(([k]) => k === 'all' || cnt[k]).map(([k, n]) => {
113
+ const onC = k === 'all' ? !CHIPS.size : CHIPS.has(k);
114
+ return `<button type="button" class="bk-chip${onC ? ' on' : ''}" data-bkchip="${k}" aria-pressed="${onC}">${esc(n)}<span class="k">${cnt[k]}</span></button>`;
115
+ }).join('');
116
+ const ml = BM.modeLine(DATA.modes);
117
+ const mode = ml ? `<p class="bk-mode">${esc(ml.lead)}<b>${esc(ml.label)}</b>${esc(ml.tail)}: ${esc(ml.what)} <button type="button" class="bk-lnk" data-bkmode aria-haspopup="dialog">Change</button></p>` : '';
118
+ const said = SAID ? `<p class="bk-said" role="status">${esc(SAID.text)}${SAID.undo ? ' <button type="button" class="bk-lnk" data-bksaid>Undo</button>' : ''}</p>` : '';
119
+ const sh = BM.showingLine(T, { chips: CHIPS, pick: PICK, partB: partB() });
120
+ const showing = sh ? `<p class="bk-show">${esc(sh.text)}${sh.hidden ? ` · ${sh.hidden} hidden` : ''} · <button type="button" class="bk-lnk" data-bkall>Show all</button></p>` : '';
121
+ const G = BM.groupsOf(T, { chips: CHIPS, pick: PICK, sort: SORT, partB: partB() });
122
+ const head = headHtml(COLS);
123
+ const body = G.map((g) => groupHtml(g)).join('') || `<p class="bk-none">${T.length ? 'No task matches these filters.' : 'No open task here. A task added to an initiative, or a Jira ticket of a sprint, shows here.'}</p>`;
124
+ host.innerHTML = `<div class="bk-chips" role="group" aria-label="Show">${chips}</div>${mode}${showing}${said}${DATA.err ? `<p class="bk-err">${esc(DATA.err)}</p>` : ''}`
125
+ + `<div class="bk" role="table" aria-label="Backlog">${head}${body}</div>`;
126
+ drawBar();
127
+ }
128
+ /* ── the columns: Task first and the actions last, always; the ones between are a list, so the initiative popup can leave Initiative out ── */
129
+ export const COLS = ['jira', 'epic', 'ini', 'who', 'state'];
130
+ const COL = { jira: ['Jira ticket', '104px'], epic: ['Epic', 'minmax(80px, 130px)'], ini: ['Initiative', 'minmax(110px, 160px)'], who: ['Who', '76px'], due: ['Due', 'minmax(80px, 150px)'], state: ['State', 'minmax(200px, 290px)'] };
131
+ const colsCss = (cols) => `40px minmax(240px, 1fr) ${cols.map((c) => COL[c][1]).join(' ')} 72px`;
132
+ function headHtml(cols) {
133
+ return `<div class="bk-r bk-h" role="row"><span class="c-ck"></span><span class="c-n">Task</span>${cols.map((c) => `<span class="c-${c}">${COL[c][0]}</span>`).join('')}<span class="c-a"></span></div>`;
134
+ }
135
+ function groupHtml(g, cols = COLS) {
136
+ const open = FOLD[g.k] != null ? FOLD[g.k] : g.open;
137
+ const rows = open ? (MORE.has(g.k) ? g.rows : g.rows.slice(0, BM.SHOW)) : [];
138
+ // Yes acts on the rows in view, never blind (design check 1 a): "Yes to these 5" while the group is cut to 5, "Yes to all 31" once open
139
+ const can = yesRows(g, rows), whole = rows.length === g.rows.length;
140
+ const yes = can.length ? `<button type="button" class="bk-yes" data-bkyes="${g.k}">${SPARK} ${whole ? (can.length === 1 ? 'Yes to this one' : 'Yes to all ' + can.length) : 'Yes to these ' + can.length}</button>` : '';
141
+ const more = open && g.rows.length > rows.length ? `<button type="button" class="bk-r bk-more" data-bkmore="${g.k}">${SV(I.chev)}${g.rows.length - rows.length} more</button>` : '';
142
+ return `<div class="bk-r bk-g${open ? ' open' : ''}" role="row"><button type="button" class="bk-gt" data-bkfold="${g.k}" aria-expanded="${open}">${SV(open ? I.down : I.chev)}<b>${esc(g.n)}</b><span class="k">${g.rows.length}</span>${g.sub ? `<small>· ${esc(g.sub)}</small>` : ''}</button>${yes}</div>`
143
+ + rows.map((t) => rowHtml(t, g.k, cols)).join('') + more;
144
+ }
145
+ /** The rows of group g that a Yes acts on: the eligible rows in view. */
146
+ function yesRows(g, rows) {
147
+ if (g.k === 'take') return rows.filter((t) => t.take && !t.declined);
148
+ if (g.k === 'nohome') return rows.filter((t) => t.propose);
149
+ return [];
150
+ }
151
+ const MON3 = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
152
+ const dueText = (d) => { const x = new Date(String(d).slice(0, 10) + 'T00:00:00Z'); return isNaN(x) ? String(d) : x.getUTCDate() + ' ' + MON3[x.getUTCMonth()]; };
153
+ function whoHtml(t) {
154
+ if (t.agent && t.agent.state !== 'failed') return `<span class="bk-pm">${SPARK} PMOS</span>`;
155
+ return t.who ? esc(t.who) : '<span class="q">None</span>';
156
+ }
157
+ function rowHtml(t, gk, cols = COLS) {
158
+ const u = uidOf(t), ck = SEL.has(u), s = BM.stateOf(t, gk, { noLate: cols.includes('due') });
159
+ const icon = t.milestone ? `<i class="bk-ic ms" title="Milestone">${SV(I.ms)}</i>` : `<i class="bk-ic" title="Task">${SV(I.task)}</i>`;
160
+ const jira = t.key ? `<span class="bk-jk" title="Jira ticket ${esc(t.key)}">${SV(I.jira)}${esc(t.key)}</span>` : '';
161
+ const epic = t.src === 'jira' ? (t.epic ? `<span title="${esc(t.epic.name ? t.epic.name + ' (' + t.epic.key + ')' : t.epic.key)}">${esc(t.epic.name || t.epic.key)}</span>` : '<span class="q">No epic</span>') : '';
162
+ const ini = t.ini ? `<span title="${esc(t.iniTitle)}">${esc(t.iniTitle)}</span>`
163
+ : t.propose ? `<span class="bk-pm" title="${esc('PMOS proposes it: ' + t.propose.why)}">${SPARK} ${esc(t.propose.title)}</span>` : ''; // No home says it once, in its head
164
+ let act = '';
165
+ if (gk === 'review') act = `<button type="button" class="bk-rvb" data-bkrev="${esc(u)}">Review</button>`;
166
+ else if (gk === 'working') act = `<button type="button" class="bk-ib" data-bkmenu="${esc(u)}" aria-label="More for ${esc(t.title)}" title="More">${SV(I.more)}</button>`;
167
+ else if (gk === 'take' || (gk === 'nohome' && t.propose)) act = `<span class="bk-two"><button type="button" class="bk-ib" data-bkok="${esc(u)}" aria-label="${gk === 'take' ? 'Give to PMOS' : 'Put it in ' + esc(t.propose.title)}" title="${gk === 'take' ? 'Give to PMOS' : 'Put it there'}">${SV(I.ok)}</button><button type="button" class="bk-ib" data-bkno="${esc(u)}" aria-label="${gk === 'take' ? 'Not for PMOS' : 'Not there'}" title="${gk === 'take' ? 'Not for PMOS' : 'Not there'}">${SV(I.x)}</button></span>`;
168
+ else if (gk === 'done') act = `<button type="button" class="bk-ib" data-bkundo="${esc(u)}" aria-label="Undo: open ${esc(t.title)} again" title="Undo">${SV(I.undo)}</button>`;
169
+ const cell = {
170
+ due: `<span class="c-due${t.late ? ' lt' : ''}">${t.due ? esc(dueText(t.due) + (t.late ? ' · ' + t.late + (t.late === 1 ? ' day late' : ' days late') : '')) : '<span class="q">No date</span>'}</span>`,
171
+ jira: `<span class="c-jira">${jira}</span>`, epic: `<span class="c-epic">${epic}</span>`, ini: `<span class="c-ini">${ini}</span>`, who: `<span class="c-who">${whoHtml(t)}</span>`,
172
+ state: `<span class="c-state bk-s${s.tone ? ' ' + s.tone : ''}${gk === 'take' ? ' tk' : ''}" title="${esc(s.text + (s.note ? ' · ' + s.note : ''))}"><i class="bk-dot ${s.dot}"></i>${s.tone === 'late' && gk === 'take' ? `<em class="lt">${esc(s.text)}</em>` : esc(s.text)}${s.note ? `<em> · ${esc(s.note)}</em>` : ''}</span>`,
173
+ };
174
+ return `<div class="bk-r bk-i${ck ? ' sel' : ''}" role="row" data-bk="${esc(u)}">`
175
+ + `<span class="c-ck"><input type="checkbox" class="bk-ck" data-bkck="${esc(u)}" aria-label="Tick ${esc(t.title)}"${ck ? ' checked' : ''}></span>`
176
+ + `<span class="c-n bk-n">${icon}<button type="button" class="bk-t" data-bkopen="${esc(u)}" title="${esc(t.title)}">${esc(t.title)}</button></span>`
177
+ + cols.map((c) => cell[c]).join('')
178
+ + `<span class="c-a bk-a">${act}</span></div>`;
179
+ }
180
+
181
+ /* ── the bar under ticked rows (board BkSelect) ───────────────────────────────────────────────────────────────── */
182
+ let bar = null;
183
+ function drawBar() {
184
+ const n = SEL.size;
185
+ if (!n && host) host.classList.remove('picking');
186
+ if (!n || !on()) { if (bar) { bar.remove(); bar = null; } return; }
187
+ if (!bar) { bar = document.createElement('div'); bar.className = 'bk-bar'; bar.setAttribute('role', 'toolbar'); bar.setAttribute('aria-label', 'Ticked tasks'); document.body.appendChild(bar); bar.addEventListener('click', barPress); }
188
+ bar.innerHTML = `<span class="c">${n} selected</span><button type="button" class="pm" data-bkb="give">${SPARK} Give to PMOS</button><button type="button" data-bkb="person">Give to a person</button>`
189
+ + `<button type="button" data-bkb="ini">Move to initiative</button><button type="button" data-bkb="date">Set date</button><button type="button" data-bkb="archive">Archive</button>`
190
+ + `<button type="button" class="x" data-bkb="clear" aria-label="Clear the ticks" title="Clear">${SV(I.x)}</button>`;
191
+ }
192
+ const picked = () => DATA.tasks.filter((t) => SEL.has(uidOf(t)));
193
+ async function barPress(e) {
194
+ const b = e.target.closest('[data-bkb]'); if (!b) return;
195
+ const k = b.dataset.bkb, T = picked();
196
+ if (k === 'clear') { SEL.clear(); draw(); return; }
197
+ if (k === 'give') { await giveTo(T); return; }
198
+ if (k === 'person') { pickPop(b, 'Give to a person', people(), async (who) => { await editMany(T, { owner: who }, 'Given to ' + who); }, { free: 'A name' }); return; }
199
+ if (k === 'ini') { pickPop(b, 'Move to initiative', inisFor(T).map((x) => [x.id, x.title]), async (id) => { await moveMany(T, id); }); return; }
200
+ if (k === 'date') { datePop(b, async (d) => { await editMany(T, { due: d }, 'Due ' + d); }); return; }
201
+ if (k === 'archive') { await stateMany(T, 'Archived'); }
202
+ }
203
+ const inisFor = (T) => { const ws = new Set(T.map((t) => t.ws + '|' + t.board)); return (DATA.inis || []).filter((x) => ws.has(x.ws + '|' + x.board)); };
204
+
205
+ /* ── writes ───────────────────────────────────────────────────────────────────────────────────────────────────── */
206
+ const post = (p, b) => AP().post(p, b).catch(() => null);
207
+ const people = () => { const s = new Set(); for (const t of (SC ? SC.tasks() : DATA ? DATA.tasks : [])) if (t.who && t.whoKind === 'person') s.add(t.who); return [...s].sort().map((x) => [x, x]); };
208
+ const byBoard = (T) => { const m = new Map(); for (const t of T) { const k = t.ws + '|' + t.board; if (!m.has(k)) m.set(k, []); m.get(k).push(t); } return m; };
209
+ /** One line after a Yes (design check 1 a), in the list, with Undo; a later press replaces it. */
210
+ function sayLine(text, undo) { if (SC) { AP().say(text, undo); return; } SAID = { text, undo }; draw(); }
211
+ async function giveTo(T, line) {
212
+ const L = T.filter((t) => !(t.agent && t.agent.state !== 'failed'));
213
+ if (!L.length) { AP().say('PMOS already has these.'); return; }
214
+ let given = [], refused = [];
215
+ for (const [, ts] of byBoard(L)) {
216
+ const r = await post('/api/backlog/give', { ws: ts[0].ws, board: ts[0].board, tasks: ts.map((t) => t.id) });
217
+ if (r && r.given) given = given.concat(r.given.map((id) => ts.find((t) => t.id === id)).filter(Boolean));
218
+ if (r && r.refused) refused = refused.concat(r.refused);
219
+ else if (!r) refused.push({ error: 'The give did not land.' });
220
+ }
221
+ SEL.clear();
222
+ const undo = given.length ? async () => { for (const t of given) await post('/api/backlog/stop', { ws: t.ws, board: t.board, task: t.id }); AP().say('Taken back.'); load(); } : null;
223
+ const words = given.length ? `Given to PMOS: ${given.length === 1 ? given[0].title : given.length + ' tasks'}.${refused.length ? ' ' + refused[0].error + '.' : ''}` : (refused[0] && refused[0].error) || 'Nothing was given.';
224
+ if (line) sayLine(words, undo); else AP().say(words, undo);
225
+ load();
226
+ }
227
+ async function editMany(T, patch, words) {
228
+ const P = T.filter((t) => t.src === 'pmos' || 'due' in patch), J = T.length - P.length;
229
+ const back = [];
230
+ for (const t of P) {
231
+ const r = await post('/api/boards/tasks/edit', { ws: t.ws, board: t.board, task: t.id, ...patch });
232
+ if (r && r.ok !== false) back.push({ t, from: r.from || {} }); else { AP().say((r && r.error) || 'Nothing was changed.'); break; }
233
+ }
234
+ SEL.clear();
235
+ if (back.length) AP().say(`${words}: ${back.length === 1 ? back[0].t.title : back.length + ' tasks'}.${J ? ' Jira keeps who has its tickets.' : ''}`, async () => { for (const x of back) { const b = {}; for (const f of Object.keys(patch)) b[f] = x.from[f] != null ? x.from[f] : ''; await post('/api/boards/tasks/edit', { ws: x.t.ws, board: x.t.board, task: x.t.id, ...b }); } AP().say('Put back.'); load(); AP().reload(); });
236
+ else if (J) AP().say('Jira keeps who has its tickets: give them in Jira.');
237
+ load(); AP().reload();
238
+ }
239
+ async function moveMany(T, ini) {
240
+ const done = [];
241
+ for (const t of T) {
242
+ const r = t.src === 'jira' ? await post('/api/backlog/place', { ws: t.ws, board: t.board, key: t.id, to: ini }) : await post('/api/boards/tasks/edit', { ws: t.ws, board: t.board, task: t.id, initiative: ini });
243
+ if (r && r.ok !== false) done.push({ t, from: t.src === 'jira' ? (r.from || '') : (r.from && r.from.initiative) || t.ini || '' }); else { AP().say((r && r.error) || 'Nothing was moved.'); break; }
244
+ }
245
+ SEL.clear();
246
+ const name = ((DATA.inis || []).find((x) => x.id === ini) || {}).title || ini;
247
+ if (done.length) AP().say(`Moved to ${name}: ${done.length === 1 ? done[0].t.title : done.length + ' tasks'}.`, async () => { for (const x of done) { if (x.t.src === 'jira') await post('/api/backlog/place', { ws: x.t.ws, board: x.t.board, key: x.t.id, to: x.from }); else if (x.from) await post('/api/boards/tasks/edit', { ws: x.t.ws, board: x.t.board, task: x.t.id, initiative: x.from }); } AP().say('Put back.'); load(); AP().reload(); });
248
+ load(); AP().reload();
249
+ }
250
+ async function stateMany(T, state) {
251
+ const P = T.filter((t) => t.src === 'pmos'), back = [];
252
+ for (const t of P) { const r = await post('/api/boards/tasks/state', { ws: t.ws, board: t.board, task: t.id, state }); if (r && r.ok !== false) back.push(t); else { AP().say((r && r.error) || 'Nothing was changed.'); break; } }
253
+ SEL.clear();
254
+ const J = T.length - P.length;
255
+ if (back.length) AP().say(`${state}: ${back.length === 1 ? back[0].title : back.length + ' tasks'}.${J ? ' Jira tickets close in Jira.' : ''}`, async () => { for (const t of back) await post('/api/boards/tasks/state', { ws: t.ws, board: t.board, task: t.id, state: t.state }); AP().say('Put back.'); load(); AP().reload(); });
256
+ else if (J) AP().say('Jira tickets close in Jira.');
257
+ load(); AP().reload();
258
+ }
259
+
260
+ /* ── small popovers: a pick list, a date ──────────────────────────────────────────────────────────────────────── */
261
+ let pop = null;
262
+ function closePop() { if (pop) { pop.remove(); pop = null; } }
263
+ function place(el, at) { const b = at.getBoundingClientRect(); document.body.appendChild(el); el.style.left = Math.max(8, Math.min(b.left, innerWidth - el.offsetWidth - 8)) + 'px'; el.style.top = Math.max(8, (b.top > innerHeight / 2 ? b.top - el.offsetHeight - 8 : b.bottom + 8)) + 'px'; }
264
+ function pickPop(at, title, items, pick, o = {}) {
265
+ closePop();
266
+ pop = document.createElement('div'); pop.className = 'bk-pop'; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', title);
267
+ pop.innerHTML = `<p class="h">${esc(title)}</p>` + (o.free ? `<input class="bk-in" type="text" placeholder="${esc(o.free)}" aria-label="${esc(o.free)}">` : '')
268
+ + `<div class="l">${items.map(([v, n]) => `<button type="button" data-v="${esc(v)}">${esc(n)}</button>`).join('') || '<p class="q">Nothing to pick.</p>'}</div>`;
269
+ place(pop, at);
270
+ const inp = pop.querySelector('.bk-in'); (inp || pop.querySelector('button') || pop).focus();
271
+ pop.addEventListener('click', (e) => { const x = e.target.closest('[data-v]'); if (x) { closePop(); pick(x.dataset.v); } });
272
+ if (inp) inp.addEventListener('keydown', (e) => { if (e.key === 'Enter' && inp.value.trim()) { const v = inp.value.trim(); closePop(); pick(v); } });
273
+ pop.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closePop(); at.focus(); } });
274
+ }
275
+ function datePop(at, pick) {
276
+ closePop();
277
+ pop = document.createElement('div'); pop.className = 'bk-pop'; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', 'Set date');
278
+ pop.innerHTML = `<p class="h">Due</p><input class="bk-in" type="date" aria-label="Due day"><div class="r"><button type="button" class="bk-go" data-ok>Set</button></div>`;
279
+ place(pop, at);
280
+ const inp = pop.querySelector('input'); inp.focus();
281
+ pop.addEventListener('click', (e) => { if (e.target.closest('[data-ok]') && inp.value) { closePop(); pick(inp.value); } });
282
+ pop.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closePop(); at.focus(); } });
283
+ }
284
+ /** ⋯ on a row PMOS works on (design check 1 g): Stop, and Give to a person (PMOS stops, then the person has it). */
285
+ function rowMenu(at, t) {
286
+ pickPop(at, 'PMOS is working on it', [['stop', 'Stop'], ['person', 'Give to a person']], async (k) => {
287
+ if (k === 'person') { pickPop(at, 'Give to a person', people(), async (who) => { const r = await post('/api/backlog/stop', { ws: t.ws, board: t.board, task: t.id }); if (!r || !r.ok) { AP().say((r && r.error) || 'Nothing was changed.'); return; } await editMany([t], { owner: who }, 'Given to ' + who); }, { free: 'A name' }); return; }
288
+ const r = await post('/api/backlog/stop', { ws: t.ws, board: t.board, task: t.id });
289
+ AP().say(r && r.ok ? 'Stopped: ' + t.title + '.' : (r && r.error) || 'Nothing was changed.'); load();
290
+ });
291
+ }
292
+
293
+ /* ── the tune panel: Sort and the facets ──────────────────────────────────────────────────────────────────────── */
294
+ function tune(at) {
295
+ closePop();
296
+ const F = BM.facetsOf(DATA.tasks.filter(BM.isOpen));
297
+ pop = document.createElement('div'); pop.className = 'bk-pop bk-tune'; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', 'Sort and filter');
298
+ const draw1 = () => {
299
+ pop.innerHTML = `<p class="h">Sort</p><div class="bk-fg">${BM.SORTS.map(([k, n]) => `<button type="button" class="bk-chip${SORT === k ? ' on' : ''}" data-sort="${k}" aria-pressed="${SORT === k}">${esc(n)}</button>`).join('')}</div>`
300
+ + BM.FACETS.map(([f, n]) => (F[f].length > 1 ? `<p class="h">${esc(n)}</p><div class="bk-fg">${F[f].slice(0, 12).map(([v, c]) => { const o = PICK[f] && PICK[f].has(v); return `<button type="button" class="bk-chip${o ? ' on' : ''}" data-f="${f}" data-v="${esc(v)}" aria-pressed="${!!o}">${esc(v)}<span class="k">${c}</span></button>`; }).join('')}</div>` : '')).join('')
301
+ + `<div class="r"><button type="button" class="bk-lnk" data-reset>Reset</button></div>`;
302
+ };
303
+ draw1(); place(pop, at); (pop.querySelector('button') || pop).focus();
304
+ pop.addEventListener('click', (e) => {
305
+ const s = e.target.closest('[data-sort]'), f = e.target.closest('[data-f]');
306
+ if (s) SORT = s.dataset.sort;
307
+ else if (f) { const k = f.dataset.f; PICK[k] = PICK[k] || new Set(); if (PICK[k].has(f.dataset.v)) PICK[k].delete(f.dataset.v); else PICK[k].add(f.dataset.v); }
308
+ else if (e.target.closest('[data-reset]')) { SORT = 'due'; PICK = {}; }
309
+ else return;
310
+ savePrefs(); draw(); draw1();
311
+ });
312
+ pop.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closePop(); at.focus(); } });
313
+ }
314
+ function savePrefs() { put(PREFS, { sort: SORT, fold: FOLD }); }
315
+
316
+ /* ── Review: what PMOS made, with Approve and Send back (one review object for every kind of work) ─────────────── */
317
+ let rv = null;
318
+ function closeAll() { closePop(); if (rv) { rv.remove(); rv = null; } if (bar) { bar.remove(); bar = null; } }
319
+ /* who a message goes to and where, from the draft's first words ("To Daryl in #paywall") or the task's own words */
320
+ function whereOf(t, d) {
321
+ const m = /^\s*(?:reply\s+)?to\s+(.+?)(?:\s+in\s+(\S.*?))?\s*[.:]?\s*$/i.exec(String(d.summary || '').split('\n')[0]);
322
+ if (m) return { who: m[1].replace(/\s+in$/, ''), where: m[2] || '' };
323
+ return { who: (t.agent && t.agent.to) || (t.take && t.take.to) || '', where: '' };
324
+ }
325
+ /* a pull request's files and checks, read from the agent's body (diff headers, "Files:" lines, a "Checks:" line) */
326
+ function prParts(body) {
327
+ const B = String(body || ''), files = new Set();
328
+ for (const m of B.matchAll(/^diff --git a\/(\S+)/gm)) files.add(m[1]);
329
+ for (const m of B.matchAll(/^\s*(?:[-*]|M|A|D)\s+([\w./-]+\.[\w]+)\s*$/gm)) files.add(m[1]);
330
+ const ck = /^\s*checks?\s*:\s*(.+)$/im.exec(B);
331
+ return { files: [...files].slice(0, 30), checks: ck ? ck[1].trim() : '' };
332
+ }
333
+ function review(t) {
334
+ closePop(); if (rv) rv.remove();
335
+ const a = t.agent || {}, d = a.draft || {}, s = BM.stateOf(t), kind = a.review || 'doc';
336
+ rv = document.createElement('div'); rv.className = 'bk-rv'; rv.setAttribute('role', 'dialog'); rv.setAttribute('aria-modal', 'true'); rv.setAttribute('aria-label', 'Review ' + t.title);
337
+ let left = `<p class="k">${esc(s.text)}${t.key ? ' · ' + esc(t.key) : ''}</p><h3>${esc(t.title)}</h3>`, yes = 'Approve';
338
+ if (kind === 'message') {
339
+ const w = whereOf(t, d);
340
+ left += w.who ? `<p class="to">To <b>${esc(w.who)}</b>${w.where ? ' in ' + esc(w.where) : ''}</p>` : '';
341
+ left += `<textarea class="bd" rows="10" aria-label="The message, as it will go">${esc(d.body || '')}</textarea>`;
342
+ yes = w.who ? 'Send to ' + w.who : 'Send it';
343
+ } else if (kind === 'pr') {
344
+ const P = prParts(d.body);
345
+ left += (d.summary ? `<p class="sm">${esc(d.summary.replace(/^\s*guarded\s*:[^\n]*\n?/i, ''))}</p>` : '')
346
+ + (P.files.length ? `<p class="h k">Files changed (${P.files.length})</p><ul class="fl">${P.files.map((f) => `<li>${esc(f)}</li>`).join('')}</ul>` : '')
347
+ + (P.checks ? `<p class="ck">Checks: <b>${esc(P.checks)}</b></p>` : '')
348
+ + (d.link ? `<p><a class="bk-lnk" href="${esc(d.link)}" target="_blank" rel="noopener">${SV(I.ext, 14)} Open the pull request</a></p>` : '');
349
+ yes = 'Approve the pull request';
350
+ } else {
351
+ left += (d.summary ? `<p class="sm">${esc(d.summary)}</p>` : '') + `<div class="bd">${esc(d.body || 'PMOS has not written anything to show here.')}</div>`;
352
+ yes = a.to ? 'Approve it for ' + a.to : 'Approve';
353
+ }
354
+ rv.innerHTML = `<div class="bk-rvc"><div class="bk-rvl">${left}</div>`
355
+ + `<div class="bk-rvr"><p class="why">It waits for you: ${esc(a.why || 'it cannot pass alone')}.</p>`
356
+ + `<div class="bk-rvb2"><button type="button" class="bk-ib big ok" data-rv="approve" aria-label="${esc(yes)}" title="${esc(yes)}">${SV(I.ok)}</button><button type="button" class="bk-ib big" data-rv="back" aria-label="Send back to PMOS" title="Send back to PMOS">${SV(I.ret)}</button></div>`
357
+ + `<input class="bk-note1" type="text" placeholder="What to change" aria-label="What to change" hidden><button type="button" class="bk-go" data-rv="send" hidden>Send back</button>`
358
+ + `<button type="button" class="bk-ib x" data-rv="close" aria-label="Close" title="Close">${SV(I.x)}</button></div></div>`;
359
+ document.body.appendChild(rv);
360
+ rv.querySelector('[data-rv="approve"]').focus();
361
+ const go = async (k) => {
362
+ const note = rv.querySelector('.bk-note1').value.trim();
363
+ if (k === 'send' && !note) { rv.querySelector('.bk-note1').focus(); return; }
364
+ const ed = rv.querySelector('textarea.bd');
365
+ const body = { ws: t.ws, board: t.board, task: t.id, action: k === 'approve' ? 'approve' : 'revise', ...(k === 'send' ? { note } : {}), ...(k === 'approve' && ed ? { body: ed.value } : {}) };
366
+ const r = await post('/api/backlog/decide', body);
367
+ if (!r || r.ok === false) { AP().say((r && r.error) || 'Nothing was changed.'); return; }
368
+ closeRv();
369
+ AP().say(k === 'approve' ? (r.sending ? 'PMOS sends it now.' : 'Approved: ' + t.title + '.') : 'Sent back to PMOS: ' + note);
370
+ load(); AP().reload();
371
+ };
372
+ rv.addEventListener('click', async (e) => {
373
+ if (e.target === rv) { closeRv(); return; }
374
+ const b = e.target.closest('[data-rv]'); if (!b) return;
375
+ const k = b.dataset.rv;
376
+ if (k === 'close') { closeRv(); return; }
377
+ if (k === 'back') { const n = rv.querySelector('.bk-note1'), sb = rv.querySelector('[data-rv="send"]'); n.hidden = false; sb.hidden = false; n.focus(); return; }
378
+ await go(k);
379
+ });
380
+ rv.querySelector('.bk-note1').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); go('send'); } });
381
+ rv.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.stopPropagation(); closeRv(); } });
382
+ }
383
+ function closeRv() { if (rv) { rv.remove(); rv = null; } }
384
+
385
+ /* ── presses ──────────────────────────────────────────────────────────────────────────────────────────────────── */
386
+ const taskOf = (u) => (SC ? SC.tasks() : DATA ? DATA.tasks : []).find((t) => uidOf(t) === u) || null;
387
+ async function press(e, emb) {
388
+ const t0 = e.target;
389
+ const chip = t0.closest('[data-bkchip]');
390
+ if (chip) { const k = chip.dataset.bkchip; if (k === 'all') CHIPS.clear(); else if (CHIPS.has(k)) CHIPS.delete(k); else CHIPS.add(k); draw(); const n = host.querySelector(`[data-bkchip="${k}"]`); if (n) n.focus(); return; }
391
+ if (t0.closest('[data-bkall]')) { CHIPS.clear(); PICK = {}; draw(); return; }
392
+ if (t0.closest('[data-bkmode]')) { kindsPop(t0.closest('[data-bkmode]')); return; }
393
+ if (t0.closest('[data-bksaid]')) { const u = SAID && SAID.undo; SAID = null; draw(); if (u) await u(); return; }
394
+ const f = t0.closest('[data-bkfold]');
395
+ if (f) { const k = f.dataset.bkfold; FOLD[k] = f.getAttribute('aria-expanded') !== 'true'; savePrefs(); draw(); const n = host.querySelector(`[data-bkfold="${k}"]`); if (n) n.focus(); return; }
396
+ const m = t0.closest('[data-bkmore]'); if (m) { MORE.add(m.dataset.bkmore); draw(); return; }
397
+ const ck = t0.closest('[data-bkck]'); if (ck) { if (ck.checked) SEL.add(ck.dataset.bkck); else SEL.delete(ck.dataset.bkck); const r = ck.closest('.bk-i'); if (r) r.classList.toggle('sel', ck.checked); drawBar(); return; }
398
+ const yes = t0.closest('[data-bkyes]');
399
+ if (yes) {
400
+ const G = (emb ? BM.groupsOf(SC.tasks(), { partB: partB() }) : BM.groupsOf(DATA.tasks, { chips: CHIPS, pick: PICK, sort: SORT, partB: partB() })).find((g) => g.k === yes.dataset.bkyes);
401
+ if (!G) return;
402
+ const L = yesRows(G, (emb ? emb.more : MORE).has(G.k) ? G.rows : G.rows.slice(0, BM.SHOW));
403
+ if (G.k === 'take') await giveTo(L, true);
404
+ else await placeAll(L, true);
405
+ return;
406
+ }
407
+ const ok = t0.closest('[data-bkok]');
408
+ if (ok) { const t = taskOf(ok.dataset.bkok); if (!t) return; if (t.ini) await giveTo([t]); else await placeAll([t]); return; }
409
+ const no = t0.closest('[data-bkno]');
410
+ if (no) {
411
+ const t = taskOf(no.dataset.bkno); if (!t) return;
412
+ const r = await post('/api/backlog/decline', { ws: t.ws, board: t.board, task: t.id });
413
+ if (!r || r.ok === false) { AP().say((r && r.error) || 'Nothing was changed.'); return; }
414
+ AP().say((t.ini ? 'Not for PMOS: ' : 'Not placed: ') + t.title + '.', async () => { await post('/api/backlog/decline', { ws: t.ws, board: t.board, task: t.id, undo: true }); load(); });
415
+ load(); return;
416
+ }
417
+ const un = t0.closest('[data-bkundo]');
418
+ if (un) {
419
+ const t = taskOf(un.dataset.bkundo); if (!t) return;
420
+ const r = await post('/api/backlog/undo', { ws: t.ws, board: t.board, task: t.id });
421
+ AP().say(r && r.ok ? 'Open again: ' + t.title + '.' : (r && r.error) || 'The undo did not land.'); load(); AP().reload(); return;
422
+ }
423
+ const rvb = t0.closest('[data-bkrev]'); if (rvb) { const t = taskOf(rvb.dataset.bkrev); if (t) review(t); return; }
424
+ const mn = t0.closest('[data-bkmenu]'); if (mn) { const t = taskOf(mn.dataset.bkmenu); if (t) rowMenu(mn, t); return; }
425
+ const op = t0.closest('[data-bkopen]'); if (op) { const t = taskOf(op.dataset.bkopen); if (t) AP().openTask(t, op); }
426
+ }
427
+ async function placeAll(T, line) {
428
+ const done = [];
429
+ for (const t of T) {
430
+ if (!t.propose) continue;
431
+ const r = await post('/api/backlog/place', { ws: t.ws, board: t.board, key: t.id, to: t.propose.ini });
432
+ if (r && r.ok) done.push({ t, from: r.from || '' }); else { AP().say((r && r.error) || 'Nothing was placed.'); break; }
433
+ }
434
+ const back = async () => { for (const x of done) await post('/api/backlog/place', { ws: x.t.ws, board: x.t.board, key: x.t.id, to: x.from }); AP().say('Put back.'); load(); AP().reload(); };
435
+ const words = `Placed ${done.length === 1 ? done[0].t.title + ' in ' + done[0].t.propose.title : done.length + ' tickets in their initiatives'}.`;
436
+ if (done.length) { if (line) sayLine(words, back); else AP().say(words, back); }
437
+ load(); AP().reload();
438
+ }
439
+ /** "Change" on the mode line (design check 1, point 1): the initiatives with their kind of work, each changeable in place. It is the same
440
+ * field the initiative's popup changes (POST /api/initiatives/kind, pm/work-kind.js); each change comes with Undo. */
441
+ const KIND_LABEL = { product: 'Product management', project: 'Project management', sdlc: 'Full SDLC' };
442
+ function kindsPop(at) {
443
+ closePop();
444
+ pop = document.createElement('div'); pop.className = 'bk-pop bk-kdp'; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', 'Kind of work');
445
+ const L = (DATA.inis || []).slice().sort((a, b) => String(a.title).localeCompare(String(b.title)));
446
+ pop.innerHTML = `<p class="h">Kind of work, per initiative</p><div class="bk-kd">${L.map((x, i) => `<span title="${esc(x.title)}">${esc(x.title)}${DATA.many ? ` <small class="q">${esc(x.product)}</small>` : ''}</span>`
447
+ + `<select data-kd="${i}" aria-label="Kind of work for ${esc(x.title)}">${Object.entries(KIND_LABEL).map(([k, n]) => `<option value="${k}"${(x.kind || 'product') === k ? ' selected' : ''}>${esc(n)}</option>`).join('')}</select>`).join('') || '<p class="q">No open initiative here.</p>'}</div>`
448
+ + '<p class="bk-help">Each task follows its own initiative\'s kind: it decides what PMOS can take.</p>';
449
+ place(pop, at);
450
+ (pop.querySelector('select') || pop).focus();
451
+ pop.addEventListener('change', async (e) => {
452
+ const el = e.target.closest('[data-kd]'); if (!el) return;
453
+ const x = L[+el.dataset.kd], from = x.kind || 'product', to = el.value;
454
+ const r = await post('/api/initiatives/kind', { ws: x.ws, id: x.id, kind: to });
455
+ if (!r || !r.ok) { el.value = from; AP().say((r && r.error) || 'The kind of work was not changed.'); return; }
456
+ x.kind = to;
457
+ AP().say(`${x.title}: ${KIND_LABEL[to]}.`, async () => { await post('/api/initiatives/kind', { ws: x.ws, id: x.id, kind: r.from || from }); load(); AP().reload(); });
458
+ load(); AP().reload();
459
+ });
460
+ pop.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closePop(); at.focus(); } });
461
+ }
462
+
463
+ /* ── one list, two places (design check 2): the initiative popup draws an initiative's tasks with this same code ───────────────────────────
464
+ * listHtml(tasks, o) → the HTML of the grouped list: the same groups, rows, states and actions as the Backlog. o: { ini: an initiative id
465
+ * (only its tasks), cols: a subset of COLS in order (the popup leaves out 'ini'), fold: { group: open? }, more: Set of groups shown whole,
466
+ * partB }. bindList(el, api, tasks) wires the presses inside el (open, Give to PMOS ✓ ✕, Review, ⋯ Stop / Give to a person, Undo, fold,
467
+ * N more, Yes) through api: { post(path, body) → json, say(msg, undo?), openTask(task, from), reload() } and tasks() → the current task
468
+ * list (the rows of GET /api/backlog). After a press it calls api.reload(); the page reads again and draws listHtml anew. No tick boxes
469
+ * and no bar in an embedded list: ticking is the Backlog's. */
470
+ export function listHtml(tasks, o = {}) {
471
+ const cols = (Array.isArray(o.cols) ? o.cols : COLS).filter((c) => COL[c]);
472
+ const G = BM.groupsOf(tasks || [], { ini: o.ini, sort: o.sort || 'due', partB: o.partB !== false });
473
+ const keep = FOLD, more = MORE;
474
+ FOLD = o.fold || {}; MORE = o.more || new Set();
475
+ try {
476
+ const body = G.map((g) => groupHtml(g, cols)).join('');
477
+ return body ? `<div class="bk bk-emb" role="table" aria-label="Tasks" style="--bk-cols: ${colsCss(cols)}">${headHtml(cols)}${body}</div>` : '';
478
+ } finally { FOLD = keep; MORE = more; }
479
+ }
480
+ export function bindList(el, api, tasks) {
481
+ const fold = {}, more = new Set();
482
+ el.addEventListener('click', async (e) => {
483
+ const f = e.target.closest('[data-bkfold]'), m = e.target.closest('[data-bkmore]');
484
+ if (f || m) { if (f) fold[f.dataset.bkfold] = f.getAttribute('aria-expanded') !== 'true'; else more.add(m.dataset.bkmore); el.dispatchEvent(new CustomEvent('bk:redraw', { detail: { fold, more } })); return; }
485
+ if (e.target.closest('[data-bkck],[data-bkchip],[data-bkmode],[data-bkall],[data-bksaid]')) return;
486
+ SC = { api, tasks }; LASTAPI = api;
487
+ try { await press(e, { fold, more }); } finally { SC = null; }
488
+ });
489
+ return { fold, more };
490
+ }
491
+
492
+ /* ── mount ────────────────────────────────────────────────────────────────────────────────────────────────────── */
493
+ /**
494
+ * Called by pm/premium-board.js after each read of the board. api: { scope() → [{ ws, board, name }], post(path, body), say(msg, undo?),
495
+ * openTask(task, from), reload(), readonly, desk }. The first call places the switch and the list; later calls read the tasks again.
496
+ */
497
+ export function sync(api) {
498
+ A = api;
499
+ if (A.readonly) return;
500
+ if (!host) {
501
+ const p = get(PREFS, {}) || {}; SORT = BM.SORTS.some(([k]) => k === p.sort) ? p.sort : 'due'; FOLD = p.fold && typeof p.fold === 'object' ? p.fold : {};
502
+ const crumb = document.getElementById('crumbHost'), ib = document.getElementById('ibBody');
503
+ if (!crumb || !ib) return;
504
+ sw = document.createElement('span'); sw.className = 'bk-sw'; sw.setAttribute('role', 'tablist'); sw.setAttribute('aria-label', 'Work');
505
+ // on a desk the switch sits in the toolbar after the product picker; on a phone the toolbar is full, so it takes its own line above the list
506
+ const PH = matchMedia('(max-width: 760px)');
507
+ const place = () => { if (PH.matches) ib.insertAdjacentElement('beforebegin', sw); else crumb.insertAdjacentElement('afterend', sw); sw.classList.toggle('bk-sw-row', PH.matches); };
508
+ place(); PH.addEventListener('change', place);
509
+ sw.addEventListener('click', (e) => { const b = e.target.closest('[data-bksw]'); if (b) setOn(b.dataset.bksw === 'bk'); });
510
+ host = document.createElement('div'); host.id = 'bkBody'; host.className = 'bk-host'; host.hidden = true;
511
+ ib.insertAdjacentElement('afterend', host);
512
+ host.addEventListener('click', (e) => { press(e); });
513
+ host.addEventListener('change', (e) => { if (e.target.closest('[data-bkck]')) press(e); });
514
+ // a phone shows no tick boxes until a long press on a row (design check 1 h): the press ticks that row and shows the boxes
515
+ let lp = null;
516
+ const lpEnd = () => { if (lp) { clearTimeout(lp); lp = null; } };
517
+ host.addEventListener('touchstart', (e) => {
518
+ const r = e.target.closest('.bk-i'); if (!r || host.classList.contains('picking')) return;
519
+ lp = setTimeout(() => { lp = null; host.classList.add('picking'); SEL.add(r.dataset.bk); r.classList.add('sel'); const c = r.querySelector('.bk-ck'); if (c) c.checked = true; drawBar(); }, 500);
520
+ }, { passive: true });
521
+ for (const ev of ['touchend', 'touchmove', 'touchcancel']) host.addEventListener(ev, lpEnd, { passive: true });
522
+ host.addEventListener('contextmenu', (e) => { if (host.classList.contains('picking') && e.target.closest('.bk-i')) e.preventDefault(); });
523
+ // the tune button is the Backlog's own while it shows (Sort and the facets)
524
+ const fb = document.getElementById('bdFilter');
525
+ if (fb) fb.addEventListener('click', (e) => { if (!on() || !DATA) return; e.stopImmediatePropagation(); e.preventDefault(); if (pop && pop.classList.contains('bk-tune')) closePop(); else tune(fb); }, true);
526
+ document.addEventListener('click', (e) => { if (pop && !pop.contains(e.target) && !e.target.closest('[data-bkb],#bdFilter,[data-bkmenu],[data-bkmode]')) closePop(); });
527
+ }
528
+ apply();
529
+ if (on() && DATA && Date.now() - loadedAt > 3000) load();
530
+ else if (!on() && (!DATA || Date.now() - loadedAt > 60000)) load(); // the switch's count
531
+ }