Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

refactor(view): split the page script under the 1500-line cap [C7,D1]

Corey Olson3377cd78b8d1
diff --git a/src/cockpit.js b/src/cockpit.js
index 7a6b8a6f..59f9ef30 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -34,6 +34,10 @@ import { roadmapBlock } from './view/roadmap-block.js';
import { openPageDialog } from './view/page-dialog.js';
import { closePageDialog } from './view/page-dialog.js';
import { applyStateDelta } from './api-http.js';
+import { pageScriptPart1 } from './view/page-script-1.js';
+import { pageScriptPart2 } from './view/page-script-2.js';
+import { pageScriptPart3 } from './view/page-script-3.js';
+import { pageScriptPart4 } from './view/page-script-4.js';
/** The CLI's default phrases, ordered by depth for the existing prose inventory guard. */
export const PULLBOARD_COMMANDS = Object.freeze(commandPhrases().sort((left, right) => right.split(' ').length - left.split(' ').length));
@@ -93,6 +97,7 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
const releaseInfo = hostedReleaseInfo(hostedReleaseVersion, hostedReleaseVersions, releaseHosted);
const css = stylesheet ?? (snapshot ? 'view.css' : transportModule ? '/view.css' : '/view.css?k=' + encodeURIComponent(key));
const cssAttribute = css.replace(/[&<>"']/g, (character) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]);
+ const pageScope = { STAR_KEY, applyStateDelta, closePageDialog, connection, drawHosted, hostedBrowser, hostedOptions, hostedReleaseDistance, hostedReleaseNote, hostedState, lifecycle, moduleOption, openPageDialog, pageStartup, paths, personNeeds, readOnly, releaseHosted, releaseInfo, requestMode, roadmapBlock, roadmapHeaders, roadmapSummary, sharingPresentation, snapshot, staleChip, tabValue, transportModule };
return `<!doctype html>
<html lang="en">
<head>
@@ -224,1079 +229,8 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
</div>
<div class="console" id="console" title="Click to close" hidden></div>
<script>
-const snapshot = ${JSON.stringify(snapshot)};
-let readOnly = ${JSON.stringify(readOnly)};
-let requests = ${JSON.stringify(requestMode)};
-const pageReadOnly = ${JSON.stringify(readOnly)};
-const pageRequests = ${JSON.stringify(requestMode)};
-const relayRequestsEnabled = requests;
-const configuredTransportModule = ${moduleOption};
-let transportModule = configuredTransportModule;
-const connection = ${connection};
-let transport = null;
-let transportLoadError = null;
-// Hosted pages can read two independent authorities at once. Local boards use the view's API; relay boards
-// retain the relay client's device-only decryption and event stream. The board id, never a mutable global mode,
-// selects the authority for each request.
-const boardSources = new Map();
-const localBoardIds = new Set();
-let localReadBase = connection.base;
-let localReadHeaders = { ...connection.headers };
-// The hosted page (N26, #513): at https://app.pullboard.dev, on the machine that runs pullboard view, the page reads
-// that view straight instead of the relay. The view hands it the session's secret by a round trip that ends back here
-// with the secret in the address's fragment, which no request carries; the page takes it out of the address before
-// anything else reads the address, and keeps it for this tab only. Every request then sends it in x-pullboard-key.
-const hosted = ${hostedOptions};
-const LOCAL_VIEW = 'http://127.0.0.1:4890';
-const LOCAL_TAB = 'pullboard.local.session';
-const LOCAL_TRIPS = 'pullboard.local.trips';
-let localSession = null;
-let localProblem = null;
-let localConfirmed = false;
-const tabValue = (${tabValue.toString()});
-/** Whether a value is a local session this page may use: version 1, a loopback origin with its port, and a secret. */
-function validLocalSession(value) {
- if (!value || value.version !== 1 || typeof value.key !== 'string' || !/^[\\x21-\\x7e]{1,256}$/.test(value.key) || typeof value.origin !== 'string') return false;
- try {
- const address = new URL(value.origin);
- return address.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(address.hostname) && address.port !== '' && address.origin === value.origin;
- } catch { return false; }
-}
-const pageStartup = (${pageStartup.toString()});
-// A relay pairing link carries its own fragment; that load stays the relay's, as before.
-const relayPairing = hosted.local && ['board', 'key', 'device'].some((name) => new URLSearchParams(location.hash.slice(1)).has(name));
-if (hosted.local && !relayPairing) {
- const fragment = new URLSearchParams(location.hash.slice(1));
- const returned = fragment.get('pullboard-local');
- if (returned !== null) {
- fragment.delete('pullboard-local');
- const rest = fragment.toString();
- let removed = true;
- try { history.replaceState(history.state, '', location.pathname + location.search + (rest ? '#' + rest : '')); }
- catch { removed = false; }
- let returnedSession = null;
- try { returnedSession = JSON.parse(returned); } catch { /* refused below */ }
- if (!removed) localProblem = 'This browser kept the connection secret in the address, so this page will not use it. Close this tab, then open your board below.';
- else if (validLocalSession(returnedSession)) localSession = { version: 1, origin: returnedSession.origin, key: returnedSession.key };
- else localProblem = 'Pullboard on this computer sent back a connection this page cannot read.';
- } else {
- try { const kept = JSON.parse(tabValue(LOCAL_TAB) ?? 'null'); if (validLocalSession(kept)) localSession = kept; } catch { /* nothing kept for this tab */ }
- }
- tabValue(LOCAL_TAB, localSession ? JSON.stringify(localSession) : null);
-}
-const snapshotReplay = { final: null, events: [], index: 0, playing: false, timer: null };
-const keep = (name, value) => { name = snapshot ? 'snapshot.' + name : name; try { if (value === undefined) return localStorage.getItem(name); localStorage.setItem(name, value); } catch { return null; } return value; };
-// Whether the host serves this page at /roadmap as well as at /, so the Roadmap's address is a path;
-// anywhere else it is a #roadmap fragment on the page's own address (N38).
-const routed = ${JSON.stringify(Boolean(paths) && !snapshot)};
-/** The tab the address names: the Roadmap at its own address, or null at the board's. */
-function addressTab() {
- if (typeof location === 'undefined') return null;
- if (snapshot) {
- const tab = (location.hash || '').slice(1).split('/')[0] || '';
- return ['items', 'shouts', 'spec', 'doctrine', 'activity', 'roadmap'].includes(tab) ? tab : null;
- }
- if (location.hash === '#items/pipeline') return 'items';
- if (/^#items\\/\\d+$/.test(location.hash)) return 'items';
- return (routed ? location.pathname === '/roadmap' : location.hash === '#roadmap') ? 'roadmap' : null;
-}
-/** Build an address for an item in the current app or an exported snapshot, preserving repo scope. */
-function itemAddress(id, root = view.root) {
- if (snapshot) return location.pathname + location.search + '#items/' + encodeURIComponent(String(id));
- const repo = data?.projects.find((entry) => entry.root === root);
- const group = data?.groups.find((entry) => entry.key === root);
- const name = repo?.name || group?.name;
- const prefix = (data?.projects.filter((entry) => entry.ok).length || 0) > 1 && name ? '/' + encodeURIComponent(name) : '';
- const path = prefix + '/items/' + encodeURIComponent(String(id));
- return routed ? path + location.search : location.pathname + location.search + '#' + path.slice(1);
-}
-/** The tab the board's own address shows: the one last picked there, or Items. */
-function homeTab() {
- const kept = keep('pb.tab');
- return kept && kept !== 'roadmap' ? kept : 'items';
-}
-const view = { roadmapOpen: new Map(), root: keep('pb.project'), tab: addressTab() || homeTab(), itemsView: typeof location !== 'undefined' && location.hash === '#items/pipeline' ? 'pipeline' : 'list', filterOpen: false, seen: {}, code: {}, item: null, adding: false, declining: null, state: 'active', rows: { spec: 'decide', doctrine: 'all' }, row: { spec: null, doctrine: null }, agent: null, allAgents: false, agentsHidden: keep('pb.agents') === 'hidden', statsOpen: false, open: {}, addressDetail: null, shout: null, scrollPlace: false };
-let switchGeneration = 0;
-// Each board read in the order it started, and the newest one drawn: an answer older than that one is stale.
-let refreshStarted = 0;
-let refreshDrawn = { generation: 0, full: true };
-if (snapshot) view.state = 'all';
-let data = null;
-let seen = '';
-let addressReady = false;
-let heldClickPointer = null;
-let deferredClickRender = false; const pageDialogs = new Set(); // open page dialogs; the page holds its redraws while one is open
-// Detail replies stay with an unchanged summary, while search results are keyed by board and words.
-const itemDetails = new Map();
-const itemSearches = new Map();
-let detailRead = null;
-const addressedShouts = new Map();
-const $ = (id) => document.getElementById(id);
-// The update note from src/view/hosted-release.js (#632): only a confirmed read of this machine's view says how far behind it is.
-// Only the hosted page builds it; every other page draws nothing and never touches the DOM for it.
-const renderHostedReleaseNote = ${releaseHosted ? `(${hostedReleaseNote.toString()})(${releaseInfo}, { $, keep, distance: (${hostedReleaseDistance.toString()}),
- // The selected board's own source decides (#632 review): a confirmed local board keeps its note on a mixed list that
- // also reads relay boards, and a selected relay board never shows one; with no board selected, only an all-local page.
- readable: () => {
- if (!hosted.local || !localConfirmed || !localSession || connection.base !== localSession.origin) return false;
- const board = data?.projects?.find((entry) => entry.root === view.root && entry.ok);
- return board ? boardSources.get(board.id)?.kind === 'local' : !transportModule && !transport;
- },
- project: (project = data?.project) => project?.releaseNotes ? project : data?.projects?.find((entry) => entry.ok && entry.releaseNotes) })` : '() => {}'};
-
-const hostedState = (${hostedState.toString()});
-const hostedBrowser = (${hostedBrowser.toString()});
-const drawHosted = (${drawHosted.toString()});
-/**
- * Show the open-board screen the page is in (src/view/hosted.js), or none with null. A phone is the one the relay's
- * page names before first paint (#757), and it hears nothing about this computer.
- */
-function localNote(state, facts = {}) {
- drawHosted(document, hostedState(state, { browser: hostedBrowser(navigator), phone: document.documentElement.dataset.relayDevice === 'phone', ...facts }), { view: localSession?.origin || LOCAL_VIEW, signIn: hosted.signIn, session: hosted.relaySession });
-}
-
-let starLinked = { at: 0, linked: false, reading: false };
-/**
- * Show the hosted page's star line (src/view/star.js) to a signed-in person whose account lists a linked board, until
- * dismissed here; pass a board list through. Why the account's list: it is the linked-board metadata the relay serves
- * this page, whichever source then draws a board, so a linked board this machine reads locally still counts, and no
- * relay client loads to decide it. It is read until it lists one, at most every few seconds, and
- * declares the relay's engine as every relay request does.
- */
-function starLine(list) {
- const line = $('star-line');
- if (!line) return list;
- const show = () => { line.hidden = !(hosted.relaySession && starLinked.linked && keep(${JSON.stringify(STAR_KEY)}) !== 'dismissed'); };
- const learn = (reply) => {
- const linked = Boolean(reply?.boards?.some((board) => typeof board?.id === 'string'));
- starLinked = { at: Date.now(), linked, reading: false };
- line.dataset.linked = linked ? 'yes' : 'no';
- show();
- };
- if (hosted.relaySession && !starLinked.linked && !starLinked.reading) {
- // The page's own read of the account, when it made one since the line last looked, answers the line, refused
- // or not: the line reads the account itself only when the page made no such read, so a listing never brings a
- // second one (#817).
- if (linkedSeen && linkedSeen.at > starLinked.at) learn(linkedSeen.reply);
- else if (Date.now() - starLinked.at > 2500) {
- starLinked = { at: Date.now(), linked: false, reading: true };
- linkedList().then(learn, () => learn(null));
- }
- }
- show();
- return list;
-}
-$('star-dismiss')?.addEventListener('click', () => { keep(${JSON.stringify(STAR_KEY)}, 'dismissed'); starLine(null); });
-// No first look of its own (#817): every signed-in page lists its boards, and api() hands that list here, so the
-// account is read only after a listing succeeds, never beside it. A session that its first listing revokes therefore
-// sees exactly one listing, and the line, hidden in its markup, stays hidden until a listing shows it.
-
-/** Hide the relay's own banner, which speaks for the relay, on a page the relay does not serve this time. */
-function hideRelayNotice() {
- const banner = document.getElementById('relay-notice');
- if (banner) banner.hidden = true;
-}
-
-/** Send this tab on the round trip to the local view, which sends it straight back here; two tries in a row at most. */
-function localTrip(base) {
- const trips = Number(tabValue(LOCAL_TRIPS) || 0);
- if (trips >= 2) {
- tabValue(LOCAL_TRIPS, null);
- localNote('problem', { detail: 'Pullboard on this computer did not give this page a session it accepts.' });
- return false;
- }
- tabValue(LOCAL_TRIPS, String(trips + 1));
- location.assign(base + '/local/connect');
- return true;
-}
-
-/** The local view refused this tab's secret, as after a restart with a new one: go round again for it, unasked. */
-function localExpired() {
- const base = localSession.origin;
- localSession = null;
- localConfirmed = false;
- tabValue(LOCAL_TAB, null);
- localTrip(base);
-}
-
-// The screens that wait on this computer: the page looks again by itself while one shows, with no Try again (#764).
-const LOCAL_STATES = ['looking', 'asking', 'blocked', 'not-running', 'mismatch'];
-let localChecking = false;
-let localReached = false;
-
-/**
- * Reach this machine's view: read the view's public protocol, which holds no secret and no board, and take the session
- * the round trip brought back. While the browser asks the person, which it does before the request goes anywhere, the
- * page draws the prompt and says it waits. It is 'local' when the page now reads the local view, 'away' when the
- * browser is on the round trip, 'unreachable' when the page cannot read it, with the screen that says why, and 'busy'
- * while another look is still on its way. A look again by itself (again) redraws only a screen that waits on this
- * computer, so a later screen, such as signing in, stays.
- */
-async function connectLocal(again = false) {
- // A phone never runs Pullboard: it is unreachable at once, before a permission query or a fetch can wait (#900).
- if (pageStartup(document.documentElement).phone) return 'unreachable';
- if (localChecking) return 'busy';
- localChecking = true;
- try { return await lookLocal(again); }
- finally { localChecking = false; }
-}
-
-/** One look for this machine's view, for connectLocal, which keeps two from running at once. */
-async function lookLocal(again) {
- const base = localSession?.origin || LOCAL_VIEW;
- /** Draw this screen, unless the page has moved past the ones that wait on this computer. */
- const show = (state) => {
- const shown = $('local-note').dataset.state || '';
- if (shown !== state && (!again || LOCAL_STATES.includes(shown))) localNote(state);
- };
- let permission = null;
- for (const name of ['loopback-network', 'local-network-access']) {
- try { permission = (await navigator.permissions.query({ name })).state; break; } catch { /* this browser has no such permission */ }
- }
- if (permission === 'denied') {
- show('blocked');
- return 'unreachable';
- }
- // A browser that says it will ask gets Click Allow on screen before the request that raises its prompt; one that
- // says nothing gets it only once the request is slow to come back, as it is while a prompt waits.
- let slow = null;
- if (permission === 'prompt' && !again) {
- show('asking');
- await new Promise((painted) => requestAnimationFrame(() => requestAnimationFrame(painted)));
- } else if (permission !== 'granted' && !again) slow = setTimeout(() => show('asking'), 800);
- let reply;
- try {
- for (let attempt = 1; !reply; attempt += 1) {
- try { reply = await fetch(base + '/local/protocol', { signal: AbortSignal.timeout(3000), credentials: 'omit', redirect: 'error' }); }
- catch (error) {
- // A read that ran out of time may have met a slow first answer or a browser prompt still open, so it asks once
- // more (#786). After that, one that ran out of time while the browser may still be asking is the prompt waiting
- // for the person, and one refused at once means nothing runs here (#764). One discovery request at a time is all
- // this page makes of this device (P5), so a view too old to answer it reads as none.
- if (attempt < 2 && error?.name === 'TimeoutError') continue;
- show(error?.name === 'TimeoutError' && permission !== 'granted' ? 'asking' : 'not-running');
- return 'unreachable';
- }
- }
- } finally { clearTimeout(slow); }
- let protocol = null;
- try { protocol = await reply.json(); } catch { /* not this protocol */ }
- if (!reply.ok || protocol?.version !== 1 || protocol?.apiVersion !== 1 || protocol?.hostedOrigin !== location.origin) {
- show('mismatch');
- return 'unreachable';
- }
- if (!localSession) return localTrip(base) ? 'away' : 'unreachable';
- connection.base = localSession.origin;
- connection.headers = { 'x-pullboard-key': localSession.key };
- localReadBase = connection.base;
- localReadHeaders = { ...connection.headers };
- readOnly = false;
- requests = false;
- localReached = true;
- document.body.classList.remove('read-only', 'requests');
- hideRelayNotice();
- // Finding your boards stays until the list arrives, so the page never shows an empty board on its way to one.
- if (LOCAL_STATES.includes($('local-note').dataset.state || '')) localNote('looking');
- return 'local';
-}
-
-/** Mark primary pointer targets whose click would be lost if a refresh replaces them. */
-function holdClickPointer(event) {
- if (!event.isPrimary || event.button !== 0 || !(event.target instanceof Element && event.target.closest('#pipeline .pipeline-item, #spec-detail [data-row-decision="decline"], #spec-decline-submit, #roadmap-panel [data-roadmap-jump]'))) return;
- heldClickPointer = event.pointerId;
-}
-
-/** Flush a deferred refresh only after the browser has had the chance to dispatch the resulting click. */
-function releaseClickPointer(event) {
- if (event.pointerId !== heldClickPointer) return;
- heldClickPointer = null;
- if (deferredClickRender) requestAnimationFrame(() => {
- if (heldClickPointer === null && deferredClickRender) {
- deferredClickRender = false;
- render();
- }
- });
-}
-
-document.addEventListener('pointerdown', holdClickPointer, true);
-document.addEventListener('pointerup', releaseClickPointer, true);
-document.addEventListener('pointercancel', releaseClickPointer, true);
-/**
- * Draw the page in the theme the person picked, light or dark; with none picked it follows the system, live. The button
- * only ever offers the other of the two: it shows the scheme on screen, and a press picks the opposite. Following the
- * system again waits for a settings page. The tokens hold both values, so only the scheme they answer to changes.
- */
-function theme(pick) {
- if (pick === 'light' || pick === 'dark') document.documentElement.dataset.theme = pick;
- else delete document.documentElement.dataset.theme;
- const now = document.documentElement.dataset.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
- document.documentElement.dataset.scheme = now;
- // The open-board screens carry the same toggle in their own header (#764), as the sidebar is hidden there.
- for (const button of [$('theme'), $('ob-theme')]) {
- button.title = now === 'dark' ? 'Dark theme: switch to light' : 'Light theme: switch to dark';
- button.setAttribute('aria-label', button.title);
- }
-}
-theme(keep('pb.theme'));
-matchMedia('(prefers-color-scheme: dark)').addEventListener?.('change', () => theme(keep('pb.theme')));
-/** Collapse the sidebar into the tab bar on a wide screen, or bring it back, as the person last chose. */
-function collapseSide(collapsed) {
- if (collapsed) document.documentElement.dataset.side = 'collapsed';
- else delete document.documentElement.dataset.side;
- $('side-toggle').setAttribute('aria-pressed', String(collapsed));
- $('side-toggle').title = collapsed ? 'Show the project list' : 'Collapse the project list';
- $('side-toggle').setAttribute('aria-label', $('side-toggle').title);
-}
-collapseSide(keep('pb.side') === 'collapsed');
-const esc = (text) => String(text ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
-// Inline code: a short chip stays whole on its line; one wider than a phone line's worth may wrap. Width
-// is in columns, as a terminal counts them: CJK, full-width and emoji characters take two.
-const wideChar = (c) => { const p = c.codePointAt(0); return (p >= 0x1100 && p <= 0x115f) || (p >= 0x2e80 && p <= 0xa4cf) || (p >= 0xac00 && p <= 0xd7a3) || (p >= 0xf900 && p <= 0xfaff) || (p >= 0xfe30 && p <= 0xfe4f) || (p >= 0xff00 && p <= 0xff60) || (p >= 0xffe0 && p <= 0xffe6) || (p >= 0x1f300 && p <= 0x1faff) || (p >= 0x20000 && p <= 0x3fffd); };
-const columns = (text) => [...String(text)].reduce((n, c) => n + (wideChar(c) ? 2 : 1), 0);
-const codeChip = (text, kind = '') => kind === 'sha' && String(text).length > 10
- ? '<code class="inline sha" title="' + esc(text) + '">' + esc(String(text).slice(0, 10)) + '</code>'
- : '<code class="inline' + (kind ? ' ' + kind : '') + (columns(text) > 24 ? ' long" title="' + esc(text) : '') + '">' + esc(text) + '</code>';
-// An age said in words, as a shout's card shows it: now, 2m ago, 1h ago.
-const agoLong = (iso) => { const short = ago(iso); return short === 'now' ? 'now' : short + ' ago'; };
-const ago = (iso) => { const m = Math.round((Date.now() - Date.parse(iso)) / 60000); return m < 1 ? 'now' : m < 60 ? m + 'm' : m < 2880 ? Math.round(m / 60) + 'h' : Math.round(m / 1440) + 'd'; };
-// An age as the page shows it: the moment it counts from stays on it, so tickAges can move it on.
-const age = (iso) => '<time data-ago="' + esc(iso) + '">' + ago(iso) + '</time>';
-const clock = (iso) => new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
-const when = (iso) => (new Date(iso).toDateString() === new Date().toDateString() ? '' : new Date(iso).toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ') + clock(iso);
-// A day as a feed names it: Today, Yesterday, or its weekday and date.
-const dayName = (iso) => {
- const then = new Date(iso).toDateString(), today = new Date();
- if (then === today.toDateString()) return 'Today';
- today.setDate(today.getDate() - 1);
- return then === today.toDateString() ? 'Yesterday' : new Date(iso).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
-};
-// When the page last named days, so tickDays can rename them in place once the clock passes midnight (#644).
-let daysNamedAt = new Date();
-// A feed's rows, newest first, with the day named above each run of rows from the same day.
-const byDay = (rows, at, row) => { daysNamedAt = new Date(); return rows.map((x, i) => (i && new Date(at(x)).toDateString() === new Date(at(rows[i - 1])).toDateString() ? '' : '<h4 class="day">' + dayName(at(x)) + '</h4>') + row(x)).join(''); };
-// Where the shouts cross into an earlier day, a rule names it in the middle; today needs no label at the top.
-const dayRules = (rows, at, row) => { daysNamedAt = new Date(); return rows.map((x, i) => {
- const day = new Date(at(x)).toDateString(), before = i ? new Date(at(rows[i - 1])).toDateString() : new Date().toDateString();
- return (day === before ? '' : '<div class="day-rule" role="separator"><span>' + dayName(at(x)) + '</span></div>') + row(x);
-}).join(''); };
-const firstLine = (text) => String(text ?? '').split('\\n').map((line) => line.trim()).find(Boolean) || '';
-/** Omit a duplicated leading verdict code from rendered copy while preserving the recorded note. */
-function visibleVerdictNote(reason, note) {
- const text = String(note ?? '');
- const code = String(reason ?? '');
- const remainder = text.slice(code.length);
- return code && text.startsWith(code) && (!remainder || /^\\s/u.test(remainder)) ? remainder.trimStart() : text;
-}
-// The latest verdict is a reject and no accept followed: open again, being reworked, resubmitted, or
-// withdrawn after it.
-const rejected = (i) => i.status !== 'verified' && !!i.verdict && i.verdict.decision === 'REJECT';
-/** Resolve visible agent text from this board's API without changing action identities. */
-function agentName(id, project = data?.project) {
- const agent = project?.agents?.find((entry) => entry.agent_id === id);
- return agent?.displayName || (agent ? id + ' (' + (agent.model || agent.agent_model || 'unknown') + ')' : id);
-}
-/** Keep a shout address whole while its model can shorten, retaining the API name for assistive readers. */
-function shoutAgentName(id) {
- const name = agentName(id);
- if (name === id) return esc(id);
- const prefix = name.endsWith('-' + id);
- const model = prefix ? name.slice(0, -id.length) : name.slice(id.length);
- const address = '<span class="agent-id">' + esc(id) + '</span>';
- const label = '<span class="agent-model">' + esc(model) + '</span>';
- return '<span class="agent-label' + (prefix ? ' prefix' : '') + '" title="' + esc(name) + '" role="group" aria-label="' + esc(name) + '">' + (prefix ? label + address : address + label) + '</span>';
-}
-/** Render a review note with escaped text and references bound to the selected board. */
-const verdictHtml = (v, titles) => '<div class="verdict ' + (v.decision === 'ACCEPT' ? 'yes' : 'no') + '"><b>' + esc(v.decision) + ' ' + esc(v.reason) + '</b><span class="by">' + esc(agentName(v.by)) + ' · ' + when(v.at) + ' · at ' + esc(String(v.commit || '').slice(0, 12)) + '</span><div class="note">' + inline(visibleVerdictNote(v.reason, v.note), titles) + '</div></div>';
-const roadmapSummary = (${roadmapSummary.toString()}), roadmapHeaders = (${roadmapHeaders.toString()});
-const stateOf = (i) => i.status === 'claimed' ? 'building' : i.status === 'submitted' ? 'verify' : i.status === 'verified' ? 'verified' : i.status === 'withdrawn' ? 'withdrawn' : i.verdict && i.verdict.decision === 'REJECT' ? 'back' : 'open';
-const STATES = { building: ['building', 'busy'], verify: ['to verify', 'warn'], back: ['sent back', 'no'], verified: ['verified', 'ok'], open: ['unclaimed', 'free'], withdrawn: ['withdrawn', ''] };
-const chip = (s) => '<span class="chip ' + STATES[s][1] + '">' + STATES[s][0] + '</span>';
-// A verified item's stale mark from src/view/stale.js (#726): Core publishes verdictState and the page only draws it.
-const staleChip = (${staleChip.toString()});
-// A roadmap item's blocker dot and unfolded reason from src/view/roadmap-block.js (#605), read from the summaries held.
-const roadmapBlock = (${roadmapBlock.toString()});
-const openPageDialog = (${openPageDialog.toString()}), closePageDialog = (${closePageDialog.toString()});
-/** Parse the bounded reference syntax before requesting additional committed line windows. */
-function codeReferenceParts(ref) {
- const match = /^(.+):(\\d+)(?:-(\\d+))?@([0-9a-f]{7,40})$/.exec(String(ref));
- if (!match) return null;
- const from = Number(match[2]);
- const to = Number(match[3] ?? match[2]);
- return Number.isSafeInteger(from) && Number.isSafeInteger(to) && from > 0 && to >= from
- ? { path: match[1], from, to, commit: match[4] } : null;
-}
-/**
- * Escape and color a source line using a small language-neutral set of common code tokens. A block comment or a
- * template string still open at the line's end is left in state.open, and the next line given the same state goes on
- * inside it, so a comment or a string spanning lines is colored on every one of them.
- */
-function highlightCodeLine(line, path, state = {}) {
- const source = String(line);
- const extension = String(path).split('.').at(-1).toLowerCase();
- let output = '', i = 0;
- if (state.open) {
- let end = -1;
- if (state.open === 'comment') { const at = source.indexOf('*/'); end = at < 0 ? -1 : at + 2; }
- else for (let k = 0; k < source.length; k++) { if (source.charCodeAt(k) === 92) { k++; continue; } if (source.charCodeAt(k) === 96) { end = k + 1; break; } }
- const kind = state.open === 'comment' ? 'tok-comment' : 'tok-string';
- if (end < 0) return '<span class="' + kind + '">' + esc(source) + '</span>';
- output = '<span class="' + kind + '">' + esc(source.slice(0, end)) + '</span>';
- i = end;
- state.open = null;
- } else {
- // A preview may start inside a block comment, so a line that reads as one is all comment, and so is a whole-line
- // hash comment where the language has them: their apostrophes are words, not strings.
- const lead = source.trimStart();
- if (/^(?:\\*\\/|\\*(?:\\s|$))/.test(lead) || (['py', 'sh', 'yml', 'yaml', 'rb', 'toml'].includes(extension) && lead.startsWith('#'))) return '<span class="tok-comment">' + esc(source) + '</span>';
- }
- const keywords = new Set(['const', 'let', 'var', 'function', 'return', 'if', 'else', 'new', 'class', 'export', 'import', 'from', 'async', 'await', 'throw', 'try', 'catch', 'true', 'false', 'null', 'undefined']);
- while (i < source.length) {
- if (source.startsWith('//', i) || (extension === 'py' && source[i] === '#')) {
- output += '<span class="tok-comment">' + esc(source.slice(i)) + '</span>';
- break;
- }
- if (source.startsWith('/*', i)) {
- const at = source.indexOf('*/', i + 2), end = at < 0 ? source.length : at + 2;
- output += '<span class="tok-comment">' + esc(source.slice(i, end)) + '</span>';
- if (at < 0) state.open = 'comment';
- i = end;
- continue;
- }
- const char = source[i];
- if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
- let end = i + 1, closed = false;
- while (end < source.length) {
- if (source.charCodeAt(end) === 92) { end += 2; continue; }
- if (source[end++] === char) { closed = true; break; }
- }
- if (!closed && char.charCodeAt(0) === 96) state.open = 'template';
- output += '<span class="tok-string">' + esc(source.slice(i, end)) + '</span>';
- i = end;
- continue;
- }
- const wordStart = (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z') || char === '_' || char === '$';
- if (wordStart) {
- let end = i + 1;
- while (end < source.length && ((source[end] >= 'A' && source[end] <= 'Z') || (source[end] >= 'a' && source[end] <= 'z') || (source[end] >= '0' && source[end] <= '9') || source[end] === '_' || source[end] === '$')) end++;
- const word = source.slice(i, end);
- output += keywords.has(word) ? '<span class="tok-keyword">' + esc(word) + '</span>' : esc(word);
- i = end;
- continue;
- }
- if (char >= '0' && char <= '9') {
- let end = i + 1;
- while (end < source.length && ((source[end] >= '0' && source[end] <= '9') || source[end] === '.')) end++;
- output += '<span class="tok-number">' + esc(source.slice(i, end)) + '</span>';
- i = end;
- continue;
- }
- output += esc(char);
- i++;
- }
- return output;
-}
-// A shout or thread fact's path:lines@commit reference: keep only the reference in this button until
-// the person opens it. The text before a shout ref is retained so ambiguous paths can be refused.
-const codeRef = (ref, before, block = false) => {
- const c = view.code[view.root + '\\n' + before + '\\n' + ref];
- const open = Boolean(c && c.open);
- const shownLines = c?.all ? c.allLines : c?.lines, carry = {};
- const shown = !open ? '' : c.error ? '<span class="code no" role="status">' + esc(c.error) + '</span>' : !shownLines ? '<span class="code more">loading…</span>'
- : '<div class="code-wrap"><pre class="code">' + shownLines.map((line, n) => '<span><i>' + (c.from + n) + '</i>' + highlightCodeLine(line, c.path, carry) + '</span>').join('') + '</pre>'
- + (c.more && !c.all ? '<button class="code-control" data-code-all="' + esc(ref) + '"' + (before ? ' data-before="' + esc(before) + '"' : '') + ' type="button"' + (c.allLoading ? ' disabled' : '') + '>' + (c.allLoading ? 'loading all lines…' : 'show all lines') + '</button>' : '')
- + (c.all ? '<button class="code-control" data-code-less="' + esc(ref) + '"' + (before ? ' data-before="' + esc(before) + '"' : '') + ' type="button">show less</button>' : '')
- + '</div>';
- // Its label is one piece: the path, cut short first where the line is narrow, then the lines and the commit's first
- // ten characters; the whole reference is on hover.
- const colon = ref.indexOf(':'), at = ref.lastIndexOf('@');
- const label = '<span class="ref-path">' + esc(ref.slice(0, colon)) + '</span><span class="ref-at">' + esc(ref.slice(colon, at)) + '<span class="ref-sha">' + esc(ref.slice(at, at + 11)) + '</span></span>';
- const button = (asBlock) => '<button class="ref' + (asBlock ? ' block' : '') + '" data-code="' + esc(ref) + '"' + (before ? ' data-before="' + esc(before) + '"' : '') + ' title="' + esc(ref) + '" aria-label="Open code reference ' + esc(ref) + '" type="button" aria-expanded="' + open + '">' + label + '</button>';
- // A reference on a line of its own is a block, collapsed until asked: a caret, the path and lines, the short commit.
- // One inside a sentence keeps its label, so the prose reads on, and opens that same block below it.
- return block ? '<div class="code-ref' + (open ? ' open' : '') + '">' + button(true) + shown + '</div>'
- : button(false) + (open ? '<div class="code-ref open">' + button(true) + shown + '</div>' : '');
-};
-/** Format the API's structured fact binding as the live reference the code preview accepts. */
-function factCodeRef(ref) {
- if (!ref || typeof ref !== 'object') return String(ref ?? '');
- const lines = ref.start === ref.end ? String(ref.start) : ref.start + '-' + ref.end;
- return ref.path + ':' + lines + '@' + ref.commit;
-}
-const tone = (s) => s === 'approved' ? 'ok' : s === 'pending' ? 'no' : s === 'draft' ? 'warn' : '';
-/** Name a rule's actual packaged version or its repository source, including explicit overrides. */
-const ruleSource = (row) => row.standardVersion != null ? 'Pullboard v' + row.standardVersion + (row.overrides ? row.status === 'wont' ? ', declined here' : ', overridden here' : '') : 'this repo';
-/** Keep the full source label available when a narrow row clips it. */
-const ruleSourceTitle = (row) => ruleSource(row);
-/** Render the two-line record shared by Items, Spec and Doctrine, with one grid and type hierarchy. */
-function recordRow({ tag = 'li', classes = '', attributes, title, state, primary, secondary, rightTop = '', rightBottom = '' }) {
- return '<' + tag + ' class="' + (tag === 'div' ? 'srow ' : '') + 'row s-' + state + (classes ? ' ' + classes.trim() : '') + '" ' + attributes + ' title="' + esc(title) + '"><span class="dot ' + state + '"></span><div><div class="t srow-text">' + primary + '</div>' + (rightTop ? '<span class="row-age">' + rightTop + '</span>' : '') + '<div class="meta">' + secondary + '</div></div>' + rightBottom + '</' + tag + '>';
-}
-const count = (n, one, many = one) => n + ' ' + (n === 1 ? one : many);
-// What needs the person in a project, as its Needs-you list counts it: only the person's calls (B26),
-// the decisions passed up to them, spec rows waiting for them, and held lanes, which only the main
-// checkout, the person's seat, can set. Work waiting for a verdict or sent back belongs to the agents,
-// and the line under the project says so without counting it.
-const needCount = (x) => x.ok && !x.loading ? x.decisions + x.pending + x.drafts + x.holds : 0;
-const doing = (x) => [x.decisions && count(x.decisions, 'decision', 'decisions'), x.pending && count(x.pending, 'question', 'questions'), x.drafts && count(x.drafts, 'draft row', 'draft rows'), x.holds && count(x.holds, 'lane held', 'lanes held'), x.sentBack && count(x.sentBack, 'sent back'), x.awaiting && count(x.awaiting, 'to verify'), x.building && count(x.building, 'building')].filter(Boolean).join(' · ') || (x.open ? count(x.open, 'item open', 'items open') : 'nothing open');
-// Embed the standalone shared builder for every page; the binding also lets the page fixture substitute its output.
-let personNeeds = (${personNeeds.toString()});
-/** The person's calls in one repo, reused by a combined project view. */
-function projectNeeds(p) {
- return personNeeds(p);
-}
-// The item lifecycle as pullboard declares it in src/machine.js, embedded when the page is served.
-const FLOW = ${JSON.stringify(lifecycle()).replaceAll('<', '\\u003c')};
-
-/**
- * An item's history replayed through the lifecycle: each event with the state it found the item in
- * and the move it made, if it made one. The board logs a move under its verb, and a claim on a
- * claimed item as renew, but never the clock's lapse: an event that cannot start where the replay
- * stands, or an item that reads otherwise than where its history leaves it, means the clock moved
- * first, and the replay puts that lapse in, with no time of its own.
- */
-function replay(item) {
- const clock = FLOW.moves.filter((m) => m.by.includes('clock'));
- const steps = [];
- let at = FLOW.initial;
- const step = (move, e) => {
- steps.push({ from: at, move, at: e ? e.at : null, by: e ? e.by : 'the clock', kind: e ? e.kind : move.verb });
- if (move) at = move.to;
- };
- for (const e of item.history) {
- const verb = e.kind === 'renew' ? 'claim' : e.kind;
- // A renew is the claim that stays claimed; a claim logged as such is the one that arrives.
- const fits = (s) => FLOW.moves.find((m) => m.verb === verb && m.from.includes(s) && (verb !== 'claim' || (e.kind === 'renew') === (m.to === s)));
- const lapse = fits(at) ? null : clock.find((m) => m.from.includes(at) && fits(m.to));
- if (lapse) step(lapse, null);
- step(fits(at) || null, e);
- }
- const lapse = at === item.status ? null : clock.find((m) => m.from.includes(at) && m.to === item.status);
- if (lapse) step(lapse, null);
- return steps;
-}
-
-/** A recorded merge, rather than an accept, is the end of the shipping pipeline. */
-function pipelineStage(item) {
- if (item.stage !== undefined) return item.stage;
- if (item.merged) return 'merged';
- return item.status === 'verified' ? 'accepted' : item.status;
-}
-
-/** The last arrival in this stage; edits, review reservations and renewals do not restart its age. */
-function pipelineSince(item) {
- if (item.since !== undefined) return item.since;
- if (item.merged) return item.history.findLast((event) => event.kind === 'merged')?.at || item.updatedAt;
- const arrival = replay(item).findLast((step) => step.move && step.from !== step.move.to);
- // Lapses are inferred, but the native claim receipt records the deadline that caused them.
- if (arrival?.move?.verb === 'lapse') {
- const claim = item.thread?.findLast((entry) => entry.type === 'move' && ['claim', 'renew'].includes(entry.kind));
- if (claim?.detail?.leaseUntil) return claim.detail.leaseUntil;
- }
- return arrival ? arrival.at || item.updatedAt : item.history.find((event) => event.kind === 'add')?.at || item.updatedAt;
-}
-
-/** Add the list and pipeline fields omitted from full snapshots, while leaving API summaries intact. */
-function listFields(item, fresh = false) {
- if (!fresh && item.stage !== undefined) return item;
- const claim = item.status === 'claimed' && item.owner ? { by: item.owner, until: null }
- : item.status === 'submitted' && item.reviewer ? { by: item.reviewer, until: item.reviewUntil ?? null } : null;
- return { ...item, stage: pipelineStage(item), since: pipelineSince(item), claim,
- counts: { verdicts: item.verdicts.length, facts: (item.thread || []).filter((entry) => entry.type === 'fact').length } };
-}
-
-/** Resolve a builder from the full item's owner or the live claim in an API summary. */
-const holderOf = (item) => item.status === 'claimed' ? item.claim?.by ?? item.owner ?? null : null;
-/** Resolve a reviewer from the full item or the live claim in an API summary. */
-const reviewerOf = (item) => item.status === 'submitted' ? item.claim?.by ?? item.reviewer ?? null : null;
-
-/** Render the same board's items in lifecycle order, retaining every item as a detail link. */
-function pipelineCard(items) {
- const stages = [['open', 'Not started'], ['claimed', 'Building'], ['submitted', 'Waiting for review'], ['accepted', 'Accepted, waiting to merge'], ['merged', 'Merged']];
- return stages.map(([stage, label]) => {
- const rows = items.map((item) => listFields(item)).filter((item) => item.stage === stage).sort((a, b) => a.since.localeCompare(b.since) || a.id - b.id);
- const oldest = rows[0];
- return '<li class="card-panel pipeline-stage" data-pipeline-stage="' + stage + '"><header><h2>' + label + '</h2><b data-stage-count="' + stage + '">' + rows.length + '</b></header>'
- + (oldest ? '<p class="pipeline-oldest">Oldest <a class="ref" href="' + esc(itemAddress(oldest.id)) + '" data-go="item:' + oldest.id + '">#' + oldest.id + '</a> · ' + age(oldest.since) + ' in this stage</p>' : '<p class="pipeline-oldest">No items</p>')
- + '<ul>' + rows.map((item) => '<li><button class="pipeline-item' + (view.item === item.id ? ' on' : '') + '" type="button" data-item="' + item.id + '"><span>#' + item.id + '</span><span>' + esc(item.title) + '</span></button></li>').join('') + '</ul></li>';
- }).join('');
-}
-
-/** How often each move was made on this board, keyed from>to:verb, from every item's replay. */
-function moveCounts(items) {
- const counts = new Map();
- for (const item of items) {
- for (const s of replay(item)) {
- if (s.move) counts.set(s.from + '>' + s.move.to + ':' + s.move.verb, (counts.get(s.from + '>' + s.move.to + ':' + s.move.verb) || 0) + 1);
- }
- }
- return counts;
-}
-
-// A finished stay as the timeline says it: 45m, 3h 20m, 2d 4h.
-const span = (ms) => {
- const m = Math.max(0, Math.round(ms / 60000));
- return m < 1 ? 'under a minute' : m < 60 ? m + 'm' : m < 1440 ? Math.floor(m / 60) + 'h' + (m % 60 ? ' ' + (m % 60) + 'm' : '') : Math.floor(m / 1440) + 'd' + (Math.floor((m % 1440) / 60) ? ' ' + Math.floor((m % 1440) / 60) + 'h' : '');
-};
-
-/**
- * An item's history drawn as a timeline. Each move is a dot in the colour of the state it led to, a
- * reject in the colour of work sent back, and the item's creation (logged as add) one in the start
- * state's colour; an event that moves nothing is a hollow dot. Between the dots runs a line in the
- * colour of the state the item stayed in, and under each dot that began a stay, how long it lasted,
- * or how long so far while the item can still leave. A lapse has a row but no time, so a stay that
- * ends or begins at one says its length was not logged rather than guess it.
- */
-function timeline(item) {
- const entries = Array.isArray(item.thread) && item.thread.length
- ? item.thread
- : item.history.filter((entry) => entry.kind !== 'fact').map((entry, eventId) => ({ type: 'move', eventId: eventId + 1, ...entry }));
- const steps = replay({ ...item, history: entries.filter((entry) => entry.type === 'move').map(({ kind, by, at }) => ({ kind, by, at })) });
- const facts = entries.filter((entry) => entry.type === 'fact');
- const replacements = new Map(facts.filter((fact) => fact.supersedes).map((fact) => [fact.supersedes, fact]));
- const rows = [];
- let stepIndex = 0;
- /** Render a lifecycle step, keeping inferred clock lapses between recorded moves. */
- const moveRow = (s, event, index) => {
- const enters = s.move ? s.move.to : s.kind === 'add' ? FLOW.initial : null;
- const state = enters || s.from;
- const final = FLOW.states.some((f) => f.id === state && f.final);
- const next = steps.slice(index + 1).find((n) => n.move);
- const named = s.kind === 'reject' ? 'sent back' : state;
- const stay = !enters || (final && !next) ? ''
- : !s.at ? esc(named + (next ? ' after the ' : ' so far since the ') + s.kind + ', length not logged')
- : !next ? esc(named) + ' for ' + age(s.at) + ' so far'
- : !next.at ? esc(named + ' until the ' + next.kind + ', length not logged')
- : esc(named + ' for ' + span(Date.parse(next.at) - Date.parse(s.at)));
- rows.push('<li class="tl-' + esc(state) + (s.kind === 'reject' ? ' tl-back' : '') + (enters ? '' : ' tl-quiet') + '"' + (event ? ' data-event-id="' + event.eventId + '"' : '') + '><time>' + (s.at ? when(s.at) : '') + '</time><span><b>' + esc(s.kind) + '</b> ' + esc(agentName(s.by)) + '</span>' + (stay ? '<small>' + stay + '</small>' : '') + '</li>');
- };
- /** Render one API fact with its identity, replacement and committed code binding. */
- const factRow = (fact) => {
- const replacement = replacements.get(fact.id);
- const judgement = ['decision', 'rejection', 'supersession', 'root-cause'].includes(fact.kind);
- rows.push('<li id="fact-' + esc(fact.id) + '" class="tl-fact' + (judgement ? ' tl-judgement' : '') + (replacement ? ' tl-superseded' : '') + '" data-event-id="' + fact.eventId + '"><time>' + when(fact.at) + '</time><span class="tl-fact-head"><span class="chip">' + esc(fact.kind) + '</span> <b>' + esc(agentName(fact.by)) + '</b></span><span class="tl-body">' + esc(fact.text) + '</span><small>' + age(fact.at) + (replacement ? ' · <a class="thread-replacement" href="#fact-' + esc(replacement.id) + '">replaced by ' + esc(replacement.kind) + '</a>' : '') + '</small>' + (fact.ref ? '<div class="tl-code">' + codeRef(factCodeRef(fact.ref), '') + '</div>' : '') + '</li>');
- };
- for (const entry of entries) {
- if (entry.type === 'fact') { factRow(entry); continue; }
- while (stepIndex < steps.length && !(steps[stepIndex].kind === entry.kind && steps[stepIndex].by === entry.by && steps[stepIndex].at === entry.at)) {
- moveRow(steps[stepIndex], null, stepIndex);
- stepIndex += 1;
- }
- if (stepIndex < steps.length) {
- moveRow(steps[stepIndex], entry, stepIndex);
- stepIndex += 1;
- }
- }
- while (stepIndex < steps.length) {
- moveRow(steps[stepIndex], null, stepIndex);
- stepIndex += 1;
- }
- return '<ol class="tl">' + rows.join('') + '</ol>';
-}
-
-/**
- * The lifecycle drawn as SVG with this board's counts, the way the README's figure draws it. The
- * longest way from the start to a final state runs along a row, the first-declared final winning a
- * tie, its states joined by straight arrows. A pair of states a move leads back along takes a dashed
- * square route above the row, the further back the higher. The moves that keep a state are written
- * in its box after a ↻. A state off the row sits below the last state on the row that leads to it,
- * and routes into it from the row join into one, labelled once. Moves out of those states take
- * separate routes below the boxes, with their words above each route. Final states have a double border. Boxes
- * count the items there now; labels count the moves made along each route, or name its moves when
- * none was. Words are wrapped and placed by a generous estimate of their width, so none overlaps.
- */
-function flowSvg(p) {
- // Summary states include board-wide tallies, so the lifecycle drawing needs no per-item histories.
- const counts = p.moveCounts ? new Map(Object.entries(p.moveCounts)) : moveCounts(p.items);
- const finals = FLOW.states.filter((s) => s.final).map((s) => s.id);
- const leads = (s) => FLOW.moves.filter((m) => m.from.includes(s) && m.to !== s).map((m) => m.to);
- let row = [];
- const walk = (trail) => {
- const at = trail[trail.length - 1];
- if (finals.includes(at)) {
- if (trail.length > row.length || (trail.length === row.length && finals.indexOf(at) < finals.indexOf(row[row.length - 1]))) row = trail;
- return;
- }
- for (const next of new Set(leads(at))) if (!trail.includes(next)) walk([...trail, next]);
- };
- walk([FLOW.initial]);
- const W = 880, L = 20, BW = 160, step = (W - 2 * L - BW) / Math.max(row.length - 1, 1);
- const f = (v) => String(Math.round(v * 10) / 10);
- const col = (s) => row.indexOf(s);
- const pairs = [];
- for (const m of FLOW.moves) for (const from of m.from) {
- let pair = pairs.find((e) => e.from === from && e.to === m.to);
- if (!pair) pairs.push((pair = { from, to: m.to, moves: [] }));
- pair.moves.push(m);
- }
- const made = (pair, m) => counts.get(pair.from + '>' + pair.to + ':' + m.verb) || 0;
- const says = (pair) => pair.moves.map((m) => m.verb + ', ' + pair.from + ' to ' + pair.to + ', by the ' + m.by.join(' or ') + ': ' + m.how + '. Made ' + count(made(pair, m), 'time', 'times') + (m.checks.length ? '.\\nChecks, in order:\\n' + m.checks.map((c) => ' ' + c).join('\\n') : '.')).join('\\n\\n');
- // What some pairs' moves come to: each verb with how often it was made, or every verb when none was.
- const told = (list) => {
- const sums = new Map();
- for (const pair of list) for (const m of pair.moves) sums.set(m.verb, (sums.get(m.verb) || 0) + made(pair, m));
- const done = [...sums].filter(([, n]) => n);
- return { words: done.length ? done.map(([verb, n]) => verb + ' ' + n) : [...sums.keys()], idle: !done.length };
- };
- // A generous width for words at a size, and words joined by dots into the fewest even lines that
- // fit a room, as the README's figure splits them.
- const wide = (words, size) => words.length * size * 0.56;
- const wrap = (words, room, size) => {
- for (let n = 1; ; n += 1) {
- const per = Math.ceil(words.length / n), lines = [];
- for (let i = 0; i < words.length; i += per) lines.push(words.slice(i, i + per).join(' · '));
- if (per === 1 || lines.every((line) => wide(line, size) <= room)) return lines;
- }
- };
- const text = (x, y, words, cls, anchor = 'middle') => '<text class="' + cls + '" x="' + f(x) + '" y="' + f(y) + '" text-anchor="' + anchor + '">' + esc(words) + '</text>';
- const lines = (x, y, said, cls, anchor) => said.map((line, i) => text(x, y - 15 * (said.length - 1 - i), line, cls, anchor)).join('');
- const path = (points) => 'M' + points.map(([x, y]) => f(x) + ' ' + f(y)).join('L');
-
- // Inside each box: its name and count, then the moves that keep it, then any items sent back.
- const back = p.items.filter((i) => stateOf(i) === 'back').length;
- const inside = new Map(FLOW.states.map((s) => {
- const keeps = pairs.find((pair) => pair.from === s.id && pair.to === s.id);
- const said = keeps ? told([keeps]) : null;
- const kept = said ? wrap(said.words, BW - 28 - wide('↻ ', 11), 11).map((line, i) => (i ? ' ' : '↻ ') + line) : [];
- return [s.id, { keeps, said, kept, back: s.id === FLOW.initial && back ? back + ' sent back' : '' }];
- }));
- const BH = 44 + 15 * Math.max(1, ...[...inside.values()].map((box) => box.kept.length + (box.back ? 1 : 0)));
-
- // Routes back along the row, each at a level by how far back it goes; their words above them.
- const ups = pairs.filter((pair) => pair.from !== pair.to && col(pair.from) >= 0 && col(pair.to) >= 0 && col(pair.to) !== col(pair.from) + 1)
- .map((pair) => ({ pair, span: Math.abs(col(pair.from) - col(pair.to)) })).sort((a, b) => a.span - b.span);
- const spans = [...new Set(ups.map((up) => up.span))];
- for (const up of ups) {
- up.level = spans.indexOf(up.span);
- const a = L + BW / 2 + col(up.pair.from) * step, b = L + BW / 2 + col(up.pair.to) * step;
- const before = (key, value) => ups.filter((other) => other !== up && other.pair[key] === value && other.span < up.span).length;
- up.start = a + (a > b ? 16 : -16) + (a > b ? 26 : -26) * before('from', up.pair.from);
- up.end = b + (a > b ? BW / 2 - 40 : 40 - BW / 2) + (a > b ? -30 : 30) * before('to', up.pair.to);
- up.said = told([up.pair]);
- up.lines = wrap(up.said.words, Math.abs(up.start - up.end) - 20, 12);
- }
- // Higher routes cross this level vertically; put its words in the widest gap between them.
- for (const up of ups) {
- const left = Math.min(up.start, up.end), right = Math.max(up.start, up.end);
- const cuts = [left, ...ups.filter((other) => other.span > up.span).flatMap((other) => [other.start, other.end]).filter((x) => x > left && x < right), right].sort((a, b) => a - b);
- const rooms = cuts.slice(1).map((end, index) => ({ left: cuts[index], right: end })).sort((a, b) => (b.right - b.left) - (a.right - a.left));
- const room = rooms[0];
- up.labelX = (room.left + room.right) / 2;
- up.lines = wrap(up.said.words, room.right - room.left - 20, 12);
- }
- // Each level stands clear of the words of the level below it.
- const rise = [];
- for (const level of spans.keys()) {
- const below = ups.filter((up) => up.level === level - 1);
- rise[level] = level ? rise[level - 1] + 18 + 15 * Math.max(...below.map((up) => up.lines.length)) : 30;
- }
- const highest = ups.length ? Math.max(...ups.map((up) => rise[up.level] + 21 + 15 * (up.lines.length - 1))) : 0;
- const top = 12 + highest, Y = top + BH / 2, bottom = top + BH;
- const pos = new Map(row.map((s, i) => [s, { x: L + BW / 2 + i * step, y: Y }]));
-
- // A state off the row sits below the last state on it that leads there.
- const below = FLOW.states.filter((s) => !pos.has(s.id));
- for (const s of below) {
- const from = row.filter((r) => leads(r).includes(s.id));
- pos.set(s.id, { x: from.length ? pos.get(from[from.length - 1]).x : W / 2, y: bottom + 80 + BH / 2 });
- }
- const outgoing = pairs.filter((pair) => pair.from !== pair.to && below.some((state) => state.id === pair.from));
- const H = (below.length ? bottom + 80 + BH : bottom) + 14 + (outgoing.length ? 44 + 40 * (outgoing.length - 1) : 0);
-
- const group = (pairList, route, label) => pairList.map((pair, n) => '<g><title>' + esc(says(pair)) + '</title><path class="edge' + (route.back ? ' back' : '') + '" d="' + route.d + '" marker-end="url(#pb-head' + (route.back ? '-back' : '') + ')"/>' + (n === 0 ? label : '') + '</g>').join('');
- const tone = (said, extra = '') => 'tag' + (said.idle ? ' idle' : '') + extra;
- const routes = [];
- // Straight along the row.
- for (const pair of pairs.filter((pair) => col(pair.from) >= 0 && col(pair.to) === col(pair.from) + 1)) {
- const a = pos.get(pair.from), b = pos.get(pair.to), said = told([pair]);
- const words = said.words.join(' · ');
- // A long label sits above the boxes when the gap cannot hold it with clearance.
- const labelY = wide(words, 12) + 8 > b.x - a.x - BW ? top - 8 : Y - 8;
- routes.push(group([pair], { d: path([[a.x + BW / 2, Y], [b.x - BW / 2 - 1, Y]]) }, text((a.x + b.x) / 2, labelY, words, tone(said))));
- }
- // Square, above the row.
- for (const up of ups) {
- const isBack = col(up.pair.to) < col(up.pair.from), y = top - rise[up.level];
- routes.push(group([up.pair], { back: isBack, d: path([[up.start, top], [up.start, y], [up.end, y], [up.end, top - 1]]) }, lines(up.labelX, y - 7, up.lines, tone(up.said, isBack ? ' back' : ''))));
- }
- // Down from the row, joining into one route per state below, labelled once on the way in.
- for (const s of below) {
- const t = pos.get(s.id), into = pairs.filter((pair) => pair.to === s.id && col(pair.from) >= 0);
- const said = told(into), tTop = t.y - BH / 2;
- const xs = into.map((pair) => pos.get(pair.from).x).sort((a, b) => a - b);
- const left = xs.filter((x) => x < t.x - 0.5), right = xs.filter((x) => x > t.x + 0.5);
- const label = left.length
- ? lines((left[0] + (left[1] ?? t.x - BW / 2)) / 2, t.y - 8, wrap(said.words, (left[1] ?? t.x - BW / 2) - left[0] - 20, 12), tone(said))
- : right.length
- ? lines((right[right.length - 1] + (right[right.length - 2] ?? t.x + BW / 2)) / 2, t.y - 8, wrap(said.words, right[right.length - 1] - (right[right.length - 2] ?? t.x + BW / 2) - 20, 12), tone(said))
- : lines(t.x + 10, (bottom + tTop) / 2 + 4, said.words, tone(said), 'start');
- // The label goes with the route that reaches furthest, drawn first; the others join it.
- const order = [...into].sort((p1, p2) => Math.abs(pos.get(p2.from).x - t.x) - Math.abs(pos.get(p1.from).x - t.x));
- order.forEach((pair, n) => {
- const a = pos.get(pair.from);
- const d = Math.abs(a.x - t.x) < 0.5 ? path([[a.x, bottom], [t.x, tTop - 1]]) : path([[a.x, bottom], [a.x, t.y], [a.x < t.x ? t.x - BW / 2 - 1 : t.x + BW / 2 + 1, t.y]]);
- routes.push(group([pair], { d }, n === 0 ? label : ''));
- });
- }
- // A below-row state can move back into the row or on to another below-row state.
- outgoing.forEach((pair, index) => {
- const from = pos.get(pair.from), to = pos.get(pair.to);
- const lane = bottom + 80 + BH + 26 + index * 40;
- const side = to.x < from.x ? to.x + BW / 2 + 1 : to.x - BW / 2 - 1;
- const said = told([pair]);
- const room = Math.max(40, Math.abs(side - from.x) - 24);
- const label = lines((from.x + side) / 2, lane - 8, wrap(said.words, room, 12), tone(said));
- routes.push(group([pair], { d: path([[from.x, from.y + BH / 2], [from.x, lane], [side, lane], [side, to.y]]) }, label));
- });
-
- const boxes = FLOW.states.map((s) => {
- const { x, y } = pos.get(s.id), box = inside.get(s.id), left = x - BW / 2, boxTop = y - BH / 2;
- const tip = s.id + ': ' + s.means + (s.entry.length ? '.\\nEvery way in checks:\\n' + s.entry.map((r) => ' ' + r).join('\\n') : '.');
- const keeps = box.kept.length ? '<g><title>' + esc(says(box.keeps)) + '</title>' + box.kept.map((line, i) => text(left + 14, boxTop + 47 + 15 * i, line, 'keep' + (box.said.idle ? ' idle' : ''), 'start')).join('') + '</g>' : '';
- return '<g class="s-' + esc(s.id) + '"><title>' + esc(tip) + '</title><rect class="box" x="' + f(left) + '" y="' + f(boxTop) + '" width="' + BW + '" height="' + BH + '" rx="10"/>'
- + (s.final ? '<rect class="box inner" x="' + f(left + 4) + '" y="' + f(boxTop + 4) + '" width="' + (BW - 8) + '" height="' + (BH - 8) + '" rx="7"/>' : '')
- + text(left + 14, boxTop + 25, s.id, 'name', 'start') + text(x + BW / 2 - 14, boxTop + 29, String(p.items.filter((i) => i.status === s.id).length), 'n', 'end')
- + keeps + (box.back ? text(left + 14, boxTop + 47 + 15 * box.kept.length, box.back, 'sub', 'start') : '') + '</g>';
- });
- const head = (id, cls) => '<marker id="' + id + '" class="' + cls + '" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z"/></marker>';
- return '<svg viewBox="0 0 ' + W + ' ' + f(H) + '" role="img" aria-label="The item lifecycle, with counts from this board"><defs>' + head('pb-head', '') + head('pb-head-back', 'back') + '</defs>' + routes.join('') + boxes.join('') + '</svg>';
-}
-
-/** Read or move through API v1, retaining the rule and repair guidance in a refusal. */
-async function api(path, body) {
- path = snapshot ? path.split('?')[0].slice(1) + '.json' : path;
- if (snapshot) {
- if (body !== undefined && body !== null) throw new Error('This is a read-only snapshot.');
- return jsonRequest(path, undefined, '', {});
- }
- if (path === '/api/v1/boards') return starLine(await listedBoards());
- const boardId = /^\\/api\\/v1\\/boards\\/([0-9a-f]{32})(?:\\/|$)/u.exec(path)?.[1];
- const source = boardId ? boardSources.get(boardId) : null;
- if (boardId && !source) throw new Error(transport
- ? 'Pair this browser to read that board, or refresh the board list if the board is local.'
- : 'This board is not available in the current view. Refresh the board list and retry.');
- if (boardId && source?.kind === 'relay') {
- if (body !== undefined && body !== null) throw new Error('This is a read-only view of relay boards.');
- if (!transport) throw transportLoadError || new Error('The relay transport is still loading.');
- const reply = await transport.request(path, body);
- if (path.includes('/state') && reply.state) return { ...reply, state: { ...reply.state, root: source.board.root } };
- return reply;
- }
- if (body && (hosted.local ? readOnly && source?.kind !== 'local' : pageReadOnly)) throw new Error('This is a read-only view.');
- const base = source?.kind === 'local' ? localReadBase : connection.base;
- const headers = source?.kind === 'local' ? localReadHeaders : connection.headers;
- return jsonRequest(path, body, base, headers);
-}
-
-/** Use one JSON request primitive, capturing its local route and session before awaiting a reply. */
-async function jsonRequest(path, body, base, headers, cache, format = 'json') {
- const session = localSession;
- path = base + path;
- const res = await fetch(path, { method: body ? 'POST' : 'GET', headers: { ...headers, ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined, cache });
- const json = format === 'html' && res.ok ? await res.text() : await res.json();
- if (session && session === localSession && base === session.origin) {
- if (res.status === 401 || res.status === 403) localExpired();
- else if (res.ok && !localConfirmed) { localConfirmed = true; tabValue(LOCAL_TRIPS, null); }
- }
- if (!res.ok) {
- const refusal = json.error;
- const message = refusal && typeof refusal === 'object' ? '[' + refusal.code + '] ' + refusal.message : refusal || res.status;
- const error = new Error(message);
- if (refusal && typeof refusal === 'object') error.code = refusal.code;
- throw error;
- }
- return json;
-}
-
-/** Read only this machine's authenticated view, including when its page is hosted elsewhere. */
-function sharingApi(body) {
- return jsonRequest('/api/v1/view-link', body, hosted.local ? localReadBase : connection.base,
- hosted.local ? localReadHeaders : connection.headers);
-}
-
-let sharingReady = null;
-let sharingTask = Promise.resolve();
-let sharing = { state: 'idle', intentId: null, popup: null, timer: null, closing: false, boards: [] };
-
-${sharingPresentation()}/** Stop the one operation and await core cleanup; a linking batch is never described as rolled back. */
-async function closeSharing() {
- clearTimeout(sharing.timer);
- sharing.closing = true;
- if (!sharing.intentId) return;
- try {
- const status = await sharingApi({ action: 'cancel', intentId: sharing.intentId });
- sharingProgress(status);
- sharing.popup?.close(); sharing.popup = null;
- $('share-start').disabled = false;
- sharingReady = sharingInvitation();
- } catch (error) {
- $('share-status').textContent = error.message;
- if (error.code === 'VIEW_SIGN_IN_LINKING') {
- sharing.closing = false;
- sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);
- } else { sharing.popup?.close(); sharing.popup = null; $('share-start').disabled = false; }
- }
-}
-
-/** Poll public progress only while the person has an active sign-in or pairing step. */
-async function pollSharing() {
- if (sharing.closing) return;
- if (sharing.state === 'waiting' && sharing.popup?.closed) { sharingTask = closeSharing(); return sharingTask; }
- try {
- const status = await sharingApi({ action: 'status', intentId: sharing.intentId });
- sharingProgress(status);
- if (['waiting', 'linking', 'pairing'].includes(status.state)) sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);
- else { $('share-start').disabled = false; sharingReady = sharingInvitation(); }
- } catch (error) {
- $('share-status').textContent = error.message;
- $('share-start').disabled = false;
- }
-}
-
-/** Begin one existing all-board sign-in; open its browser window in the native click before awaiting the server. */
-async function beginSharing(popup) {
- sharing = { state: 'waiting', intentId: null, popup, timer: null, closing: false, boards: [] };
- $('share-panel').hidden = false;
- $('share-start').disabled = true;
- $('share-status').textContent = 'Starting GitHub sign-in…';
- try {
- const instructions = await sharingApi({ action: 'start' });
- sharing.intentId = instructions.intentId;
- if (sharing.closing || popup?.closed) return await closeSharing();
- $('share-status').textContent = 'Enter ' + instructions.userCode + ' in the GitHub window. Closing this sign-in before linking leaves every board local.';
- popup.location.replace(instructions.verificationURL);
- sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);
- } catch (error) {
- popup?.close();
- $('share-status').textContent = error.message;
- $('share-start').disabled = false;
- }
-}
-
-/** Open only core's transient device navigation in a separately authenticated HTML response, never a JSON URL. */
-async function pairSharing(popup) {
- const base = hosted.local ? localReadBase : connection.base;
- const headers = hosted.local ? localReadHeaders : connection.headers;
- try {
- const html = await jsonRequest('/api/v1/view-link', { action: 'pairing', intentId: sharing.intentId }, base, headers, undefined, 'html');
- const destination = new DOMParser().parseFromString(html, 'text/html').querySelector('a')?.getAttribute('href');
- if (!destination) throw new Error('Phone pairing is no longer waiting. Read the sign-in status and start again if needed.');
- popup.location.replace(destination);
- } catch (error) { popup?.close(); $('share-status').textContent = error.message; }
-}
-
-$('share-start')?.addEventListener('click', () => {
- const popup = window.open('about:blank', '_blank');
- if (!popup) { $('share-panel').hidden = false; $('share-status').textContent = 'Allow this view to open the GitHub sign-in window, then try again.'; return; }
- popup.opener = null;
- sharingTask = beginSharing(popup);
-});
-$('share-close')?.addEventListener('click', () => { sharingTask = closeSharing(); });
-$('share-pair')?.addEventListener('click', () => {
- const popup = window.open('about:blank', '_blank');
- if (!popup) { $('share-status').textContent = 'Allow this view to open the device-pairing window, then try again.'; return; }
- popup.opener = null;
- sharingTask = pairSharing(popup);
-});
-
-let relayEngine = null;
-/** The account's linked boards: a same-origin read that declares the relay's engine, as every relay request does. */
-// The account's last read and when it ended, answered or refused, for the star line, which reuses it rather than
-// asking again (#817): a refusal is an answer too, "not linked", and is not asked again straight away.
-let linkedSeen = null;
-async function linkedList() {
- relayEngine ??= await import('/relay/engine.js').then((engine) => String(engine.ENGINE_VERSION), () => '');
- try {
- const reply = await jsonRequest('/api/v1/boards', undefined, '', relayEngine ? { 'x-pullboard-engine': relayEngine } : {}, 'no-store');
- linkedSeen = { at: Date.now(), reply };
- return reply;
- } catch (error) {
- linkedSeen = { at: Date.now(), reply: null };
- throw error;
- }
-}
-
-/**
- * Whether the signed-in person's linked boards name one this machine's list lacks: only then does the page need the
- * decrypting relay client. The metadata is a same-origin cookie-authenticated read, with none of this machine's local
- * credential.
- */
-async function linkedBoardMissing(localIds) {
- const linked = await linkedList();
- return Boolean(linked.boards?.some(board => typeof board.id === 'string' && /^[0-9a-f]{32}$/.test(board.id) && typeof board.repository === 'string' && !localIds.has(board.id)));
-}
-
-/** Read this machine's API list and the signed-in relay list, preferring a local registration with the same id. */
-async function listedBoards() {
- let local = { boards: [], warnings: [] };
- let relay = { boards: [], warnings: [] };
- const hasLocal = hosted.local ? Boolean(localReadBase) && Boolean(localSession) : transportModule === null;
- if (hasLocal) {
- try {
- local = await jsonRequest('/api/v1/boards', undefined, localReadBase, localReadHeaders, 'no-store');
- } catch (error) {
- // A local read that fails once, as while the view restarts, is no reason to load the relay client for a
- // person whose linked boards are all on this machine or who has none (#748).
- if (!transport && hosted.relaySession && configuredTransportModule) {
- try { if (await linkedBoardMissing(new Set())) await loadTransport(); } catch { /* Keep the local refusal when neither source can be read. */ }
- }
- if (!transport) throw error;
- localNote('local-failed', { detail: String(error.message || error) });
- }
- }
- if (hosted.local && hasLocal && hosted.relaySession && configuredTransportModule && !transport) {
- try {
- if (await linkedBoardMissing(new Set((local.boards || []).map(board => board.id)))) await loadTransport();
- } catch (error) { localNote('linked-failed', { detail: String(error.message || error) }); }
- }
- if (!hasLocal && transportModule && !transport) throw transportLoadError || new Error('The browser transport is still loading.');
- if (transport) {
- try { relay = await transport.request('/api/v1/boards'); }
- catch (error) {
- if (!hosted.local || !hasLocal) throw error;
- localNote('linked-failed', { detail: String(error.message || error) });
- }
- }
- boardSources.clear();
- localBoardIds.clear();
- const boards = [];
- for (const board of local.boards || []) {
- if (typeof board.id !== 'string') continue;
- const row = { ...board, source: 'local' };
- boardSources.set(row.id, { kind: 'local', board: row });
- localBoardIds.add(row.id);
- boards.push(row);
- }
- for (const board of relay.boards || []) {
- if (typeof board.id !== 'string' || boardSources.has(board.id)) continue;
- // A linked board reads by its own name, as it does locally, with its owner as a quiet prefix.
- const [owner, name] = String(board.name || '').includes('/') ? board.name.split('/') : ['', board.name];
- const row = { ...board, root: board.id, source: 'relay', name, owner };
- boardSources.set(row.id, { kind: 'relay', board: row });
- boards.push(row);
- }
- if (hosted.local) await hostedListed(boards);
- return { version: 1, boards, warnings: [...(local.warnings || []), ...(relay.warnings || [])] };
-}
-
-/** After a hosted board list: a list clears a state it stood in for, and a signed-in empty one says why it is empty. */
-async function hostedListed(boards) {
- let shown = $('local-note').dataset.state || '';
- // A list that arrives after a failed read, once this computer's view answered, means the page recovered: the problem
- // it showed is over, and this list decides what shows now.
- if (shown === 'problem' && localReached) { localNote(null); shown = ''; }
- if (boards.length) { if (['looking', 'not-running', 'no-linked', 'unpaired', 'signed-out'].includes(shown)) localNote(null); return; }
- // Nobody signed in and no board on this computer yet: the page says how to make one, as the local view does.
- if (!hosted.relaySession) { if (shown === 'looking') localNote(null); return; }
- // An empty local view can still leave linked boards on another computer waiting for this browser to pair.
- if (!['', 'looking', 'not-running', 'no-linked', 'unpaired'].includes(shown)) return;
- let linked;
- try { linked = await linkedList(); } catch { return; /* the relay's banner says why */ }
- const names = (linked.boards || []).filter((board) => typeof board.repository === 'string').map((board) => board.repository);
- localNote(names.length ? 'unpaired' : 'no-linked', { linked: names });
-}
-
-/** Set presentation controls for the selected board; API routing still checks the target board independently. */
-function syncBoardMode(root) {
+${pageScriptPart1(pageScope)}const itemSearches = new Map();
+${pageScriptPart2(pageScope)}function syncBoardMode(root) {
if (snapshot) return;
const board = data?.projects.find((entry) => entry.root === root && entry.ok);
const source = board && boardSources.get(board.id);
@@ -1307,388 +241,7 @@ function syncBoardMode(root) {
document.body.classList.toggle('requests', requests);
}
-/** Whether a selected project is backed by the read-only relay transport. */
-function relayProject(root = view.root) {
- const board = data?.projects.find((entry) => entry.root === root && entry.ok);
- return boardSources.get(board?.id)?.kind === 'relay';
-}
-
-/** Send only literal person intent; the transport seals it and generic API writes stay refused. */
-async function sendPersonRequest(root, move) {
- if (!requests || snapshot || !readOnly) throw new Error('This view cannot send person requests.');
- if (!relayProject(root)) throw new Error('Person requests through the relay require a linked relay board.');
- if (!['add', 'shout', 'answer', 'hold', 'spec-approve', 'spec-decline'].includes(move.verb)) throw new Error('Choose a person action from the view controls.');
- if (!transport) throw transportLoadError || new Error('The browser transport is still loading.');
- return transport.request(boardPath(root) + '/moves', move);
-}
-
-/** Name a person request using its public literal intent, without exposing its sealed document. */
-function requestLabel(request) {
- const move = request.move;
- const args = move?.args || {};
- if (move?.verb === 'add') return 'New item: ' + (args.title || 'Untitled');
- if (move?.verb === 'shout') return 'Shout to ' + (args.to || 'coordinator') + ': ' + (args.text || '');
- if (move?.verb === 'answer') return 'Answer #' + move.item + ': ' + (args.text || '');
- if (move?.verb === 'hold') return (args.off ? 'Release ' : 'Hold ') + (args.lane || '') + ' lane' + (!args.off && args.reason ? ': ' + args.reason : '');
- if (move?.verb === 'spec-approve') return 'Approve row ' + (args.ids || '');
- if (move?.verb === 'spec-decline') return 'Decline row ' + (args.ids || '');
- return 'Person request';
-}
-
-/** Retain the native request status and the CLI's complete refusal guidance beside an action. */
-function requestNotice(request) {
- const label = { waiting: 'Waiting', done: 'Done', refused: 'Refused' }[request.status] || 'Unknown status';
- const error = request.status === 'refused' && request.error;
- return label + ' · ' + requestLabel(request) + (error ? '\\n' + (error.code ? '[' + error.code + '] ' : '') + (error.message || '') + (error.next ? '\\n' + error.next : '') : '');
-}
-
-/** Show the public request receipts on every board tab and update the latest action's status. */
-function renderPersonRequests(project) {
- const entries = project?.personRequests || [];
- const panel = $('person-requests');
- panel.hidden = !entries.length;
- panel.innerHTML = entries.length ? '<h2>Your requests</h2><ul class="request-list">' + [...entries].sort((a, b) => b.sequence - a.sequence).map((request) => {
- const status = { waiting: 'Waiting', done: 'Done', refused: 'Refused' }[request.status] || 'Unknown status';
- const error = request.status === 'refused' && request.error;
- const reason = error ? '<p class="request-error">' + (error.code ? '<b>' + esc(error.code) + '</b> ' : '') + esc(error.message || '') + '</p>' + (error.next ? '<p class="request-next">' + esc(error.next) + '</p>' : '') : '';
- return '<li data-person-request="' + esc(request.id) + '"><span class="request-label">' + esc(requestLabel(request)) + '</span><span class="chip request-status ' + (request.status === 'done' ? 'ok' : request.status === 'refused' ? 'no' : 'warn') + '">' + status + '</span>' + reason + '</li>';
- }).join('') + '</ul>' : '';
- const active = view.request;
- const current = active && active.root === view.root && active.run === view.acting && entries.find((request) => request.id === active.id);
- if (current && !$('console').hidden) {
- $('console').className = 'console' + (current.status === 'done' ? ' ok' : current.status === 'refused' ? ' no' : '');
- $('console').textContent = requestNotice(current);
- }
- const feedback = view.specFeedback;
- const rowRequest = feedback?.root === view.root && feedback.requestId && entries.find((request) => request.id === feedback.requestId);
- if (rowRequest) {
- feedback.status = rowRequest.status;
- feedback.tone = rowRequest.status === 'done' ? 'ok' : rowRequest.status === 'refused' ? 'no' : '';
- feedback.text = requestNotice(rowRequest);
- }
-}
-
-/** A board's sidebar counts, derived from the same API state the page displays. */
-function boardSummary(board, state) {
- const needs = personNeeds(state);
- /** Count the calls, with draft rows retaining their individual count in the sidebar. */
- const calls = (kind) => needs.filter((row) => row.kind === kind).reduce((total, row) => total + (row.count ?? 1), 0);
- /** Count one item state for the sidebar. */
- const count = (test) => state.items.filter(test).length;
- return {
- ...board, ok: true,
- releaseNotes: state.releaseNotes,
- building: count((item) => item.status === 'claimed'),
- awaiting: count((item) => item.status === 'submitted'),
- sentBack: count((item) => item.status === 'open' && item.verdict && item.verdict.decision === 'REJECT'),
- open: count((item) => item.status === 'open'),
- verified: count((item) => item.status === 'verified'),
- pending: calls('pending'),
- drafts: calls('draft') + calls('rigor-draft'),
- holds: calls('hold'),
- laneHolds: state.holds,
- decisions: calls('decision'),
- // What each item's state reads from, so another repo's roadmap can show it as this board's
- // Items tab does, sent back included, and open it here.
- items: state.items.map((item) => listFields(item)),
- agents: state.agents, events: state.events, milestones: state.milestones,
- };
-}
-
-/** Format an API-measured duration in readable units without deriving times from events [N26]. */
-function flowMinutes(value) {
- if (value === null || value === undefined) return 'unmeasured';
- const minutes = Math.round(value);
- if (minutes < 60) return minutes + ' min';
- const hours = Math.floor(minutes / 60);
- if (hours < 24) return hours + ' h ' + minutes % 60 + ' min';
- return Math.floor(hours / 24) + ' d ' + hours % 24 + ' h';
-}
-
-/** A queue's oldest item and how long it has waited, as the flow card reads it. */
-function oldestLine(oldest) {
- return 'Oldest: ' + (oldest ? '#' + oldest.id + ' · ' + flowMinutes(oldest.ageMinutes) : 'none');
-}
-
-/** Render the four stages, live queues and single recommendation supplied by stats [N26]. */
-function proofFlowCard(flow) {
- if (!flow) return '';
- const stages = [['build', 'Build'], ['reviewWait', 'Review wait'], ['review', 'Review'], ['mergeWait', 'Merge wait']];
- const queues = [['open', 'Open'], ['claimed', 'Building'], ['submitted', 'In review'], ['accepted', 'Awaiting merge']];
- const averages = stages.map(([key, label]) => {
- const average = flow.stages[key].averageMinutes;
- return '<div><span>' + label + ' average</span><b data-stage="' + key + '" data-value="' + esc(average ?? '') + '">' + esc(flowMinutes(average)) + '</b></div>';
- }).join('');
- const waiting = queues.map(([key, label]) => {
- const queue = flow.queues[key];
- const oldest = queue.oldest;
- return '<div><span>' + label + ' queue</span><b data-queue="' + key + '" data-value="' + esc(queue.size) + '">' + esc(queue.size) + '</b>'
- + '<small data-oldest="' + key + '" data-value="' + esc(oldest?.ageMinutes ?? '') + '">' + esc(oldestLine(oldest)) + '</small></div>';
- }).join('');
- const bottleneck = flow.bottleneck;
- return '<div class="proof-stats-flow"><div class="proof-stats-grid">' + averages + waiting + '</div>'
- + '<p class="proof-stats-bottleneck"><b>Bottleneck: </b><span data-flow="bottleneck">' + esc(bottleneck.message) + '</span>'
- + (bottleneck.recommendation ? ' · <span data-flow="recommendation">' + esc(bottleneck.recommendation) + '</span>' : '') + '</p></div>';
-}
-
-/** Render the event-log totals already supplied by the shared stats API [V2,N26]. */
-function proofStatsCard(stats, expanded = false) {
- if (!stats) return '<span class="muted">Stats unavailable</span>';
- const percentage = (Number(stats.rejectionShare) * 100).toFixed(1) + '%';
- const bottleneck = stats.flow?.bottleneck;
- const stage = { build: 'Build', reviewWait: 'Review wait', review: 'Review', mergeWait: 'Merge wait' }[bottleneck?.stage];
- const summary = stats.merged + ' merged · ' + percentage + ' sent back'
- + (bottleneck ? ' · Bottleneck: ' + (stage || bottleneck.message) + (bottleneck.recommendation ? ', ' + bottleneck.recommendation : '') : '');
- /** Format an API timestamp for the card without recalculating event statistics.
- * @param {string|number|null} value
- * @returns {string}
- */
- const dateText = (value) => value ? new Date(value).toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' }) : 'none';
- const firstAt = stats.firstEventAt ?? '';
- const lastAt = stats.lastEventAt ?? '';
- return '<button class="proof-stats-summary" id="proof-stats-summary" data-stats-toggle type="button" aria-expanded="' + expanded + '" aria-controls="proof-stats-full">'
- + '<span class="proof-stats-summary-text">' + esc(summary) + '</span><span class="proof-stats-caret" aria-hidden="true">' + (expanded ? '−' : '+') + '</span></button>'
- + '<div class="proof-stats-full" id="proof-stats-full"' + (expanded ? '' : ' hidden') + '>'
- + '<div class="proof-stats-head"><b>Proof stats</b><span>from recorded moves</span></div>'
- + '<div class="proof-stats-grid">'
- + '<div><span>Submissions</span><b data-stat="submissions" data-value="' + esc(stats.submissions) + '">' + esc(stats.submissions) + '</b></div>'
- + '<div><span>Rejections</span><b data-stat="rejections" data-value="' + esc(stats.rejections) + '">' + esc(stats.rejections) + '</b></div>'
- + '<div><span>Sent back</span><b data-stat="rejectionShare" data-value="' + esc(percentage) + '">' + esc(percentage) + '</b></div>'
- + '<div><span>Merged</span><b data-stat="merged" data-value="' + esc(stats.merged) + '">' + esc(stats.merged) + '</b></div>'
- + '<div><span>Without accept</span><b data-stat="mergedWithoutAccept" data-value="' + esc(stats.mergedWithoutAccept) + '">' + esc(stats.mergedWithoutAccept) + '</b></div>'
- + '<div><span>Agents</span><b data-stat="agentCount" data-value="' + esc(stats.agentCount) + '">' + esc(stats.agentCount) + '</b></div>'
- + '<div><span>First · latest</span><small><time data-stat="firstEventAt" data-value="' + esc(firstAt) + '" datetime="' + esc(firstAt) + '">' + esc(dateText(firstAt)) + '</time> · <time data-stat="lastEventAt" data-value="' + esc(lastAt) + '" datetime="' + esc(lastAt) + '">' + esc(dateText(lastAt)) + '</time></small></div>'
- + '</div>' + proofFlowCard(stats.flow) + '</div>';
-}
-
-/** Resolve a displayed repo to the persistent board identity supplied by API v1. */
-function boardPath(root) {
- const board = data && data.projects.find((entry) => entry.root === root && entry.ok);
- if (!board) throw new Error('This board is unavailable; choose a readable project and retry.');
- return '/api/v1/boards/' + encodeURIComponent(board.id);
-}
-
-/**
- * What the page last drew for a listed board, to stand in for it in a catch-up that does not read it: its sidebar
- * row, and its state when the page shows it. Nothing when the page has no such row, or shows the board without one.
- */
-function lastRead(board, root) {
- const row = data?.projects.find((entry) => entry.root === board.root && entry.id === board.id && entry.ok);
- if (!row || row.loading) return null;
- const state = data.root === board.root ? data.project : data.group?.repos.find((repo) => repo.root === board.root)?.board ?? null;
- if (!state && (board.root === root || root === 'group:' + board.project)) return null;
- return { row: { ...row, ...board, ok: true }, state };
-}
-
-/** Group the listed repositories without waiting for their individual board states. */
-function projectGroups(projects) {
- const grouped = new Map();
- for (const project of projects) {
- if (!project.project) continue;
- if (!grouped.has(project.project)) grouped.set(project.project, []);
- grouped.get(project.project).push(project);
- }
- // One repository shows once, without a heading that repeats its name.
- return [...grouped].filter(([, repos]) => repos.length > 1).map(([name, repos]) => ({ name, key: 'group:' + name, repos }));
-}
-
-/**
- * Compose the multi-repo page from the public board list and each board's public state. A catch-up names the boards
- * whose events arrived in fresh and reads only those; every other board keeps what the page last drew (#545).
- */
-async function boardState(root, mark, fresh = null) {
- const listed = await api('/api/v1/boards');
- if (!data) {
- // Names are already known: a slow board must not leave the project picker blank.
- const projects = listed.boards.map((board) => ({ ...board, ok: true, loading: true }));
- projects.push(...(listed.warnings || []).map((warning) => ({ ...warning, ok: false, error: warning.error.error.message })));
- data = { root: null, project: null, group: null, projects, groups: projectGroups(projects) };
- renderSide();
- $('project-loading').hidden = projects.length === 0;
- }
- const states = new Map();
- const cursor = mark !== null && mark !== undefined && /^\\d+$/.test(String(mark)) && Number.isSafeInteger(Number(mark)) ? Number(mark) : null;
- const projects = await Promise.all(listed.boards.map(async (board) => {
- const kept = fresh && !fresh.has(board.root) ? lastRead(board, root) : null;
- if (kept) {
- if (kept.state) states.set(board.root, kept.state);
- return kept.row;
- }
- try {
- const state = await boardRead(board, board.root === root ? cursor : null);
- states.set(board.root, state);
- return boardSummary(board, state);
- } catch (error) {
- return { ...board, ok: false, error: String(error.message || error) };
- }
- }));
- projects.push(...(listed.warnings || []).map((warning) => ({ ...warning, ok: false, error: warning.error.error.message })));
- const groups = projectGroups(projects);
- const group = groups.find((entry) => entry.key === root);
- return {
- projects, groups, project: states.get(root) || null,
- group: group ? { name: group.name, repos: group.repos.filter((repo) => repo.ok).map((repo) => ({ root: repo.root, name: repo.name, board: states.get(repo.root) })) } : null,
- };
-}
-
-// What each local board last sent this page, {state, sequence, version}: the base its next read asks to extend.
-const sentStates = new Map();
-// #552's delta applier, embedded as the server's own source, so the page applies a delta and recomputes nothing.
-const applyStateDelta = (${applyStateDelta.toString()});
-
-/**
- * Read one board's summary state. A local board the page read before asks only what changed since the state it holds
- * (#552) and applies that delta as sent; it loads a fresh snapshot only when the answer resets, as when the server no
- * longer keeps that base or the format changed (#555). Relay boards and snapshots have no deltas.
- */
-async function boardRead(board, seen) {
- const path = '/api/v1/boards/' + encodeURIComponent(board.id) + '/state', mark = seen === null ? '' : 'seen=' + encodeURIComponent(seen);
- const local = !snapshot && localBoardIds.has(board.id), held = local ? sentStates.get(board.id) : null;
- if (held && Number.isSafeInteger(held.sequence)) {
- const reply = await api(path + '?since=' + held.sequence + (mark && '&' + mark) + (held.version === undefined ? '' : '&eventLogVersion=' + encodeURIComponent(held.version)));
- if (reply.delta) {
- const state = applyStateDelta(held.state, reply.delta);
- sentStates.set(board.id, { state, sequence: reply.sequence, version: reply.eventLogVersion });
- return state;
- }
- }
- const reply = await api(path + (mark && '?' + mark));
- if (local) sentStates.set(board.id, { state: reply.state, sequence: reply.state.sequence, version: reply.eventLogVersion });
- return reply.state;
-}
-
-/** Whether a board state already carries every item's detail, as exports and event replays do. */
-const fullItems = (project) => project.items.every((item) => Array.isArray(item.history));
-
-/** Text available locally for an item before the API searches criteria omitted from summaries. */
-const searchedText = (item) => ('#' + item.id + ' ' + item.title + ' ' + item.lane + ' ' + item.specs.join(' ') + ' ' + (item.criterion || '')).toLowerCase();
-
-/** Whether the board has a gap in its retained events or an item event newer than a detail read. */
-function movedSince(project, id, cursor) {
- const events = project.events || [];
- if (!events.length || events[0].event_id <= cursor) return false;
- if (events.at(-1).event_id > cursor + 1) return true;
- return events.some((event) => event.event_id > cursor && event.item_id === id);
-}
-
-/** Load one opened item's omitted fields, retaining them only while its summary and event cursor stay current. */
-function detailOf(project, item, ask, root = view.root) {
- if (Array.isArray(item.history)) return { item };
- const drawnRoot = view.root, key = root + '\\n' + item.id, summary = JSON.stringify(item);
- const kept = itemDetails.get(key);
- /** Keep the prior detail visible during a refresh, or return the short initial loading state. */
- const waiting = (entry) => (entry?.shown ? { item: { ...item, ...entry.shown } } : { loading: true });
- if (kept?.loading) return waiting(kept);
- if (kept && kept.summary === summary && !movedSince(project, item.id, kept.cursor) && !(ask && kept.error && Date.now() - kept.failedAt >= 2_500)) {
- return kept.error ? { error: kept.error } : { item: { ...item, ...kept.detail } };
- }
- if (!ask) return waiting(kept && { shown: kept.detail });
- const entry = { loading: true, summary, cursor: project.events?.[0]?.event_id ?? 0, detail: null, error: null, shown: kept?.detail ?? null };
- itemDetails.set(key, entry);
- detailRead = api(boardPath(root) + '/items/' + encodeURIComponent(String(item.id))).then((reply) => { entry.detail = reply.item; },
- // A failed read is not the answer: while this item stays open it reads again in 3 s, so a dropped request recovers (#908).
- (error) => { entry.error = String(error.message || error); entry.failedAt = Date.now(); setTimeout(() => { if (view.root === drawnRoot && view.item === item.id) render(); }, 3_000); }).finally(() => {
- entry.loading = false;
- if (view.root === drawnRoot && ((root === view.root && view.item === item.id) || view.tab === 'roadmap')) render();
- });
- return waiting(entry);
-}
-
-/** Search full snapshots locally and summary states through the API, once per query and board. */
-function searchIds(project, words) {
- const query = words.trim().toLowerCase();
- const local = new Set(project.items.filter((item) => searchedText(item).includes(query)).map((item) => item.id));
- if (!query || fullItems(project) || data.root !== view.root) return local;
- const root = view.root, key = root + '\\n' + query;
- const kept = itemSearches.get(key);
- if (kept) return kept.ids || local;
- const entry = { ids: null };
- itemSearches.set(key, entry);
- api(boardPath(root) + '/items?q=' + encodeURIComponent(query)).then((reply) => {
- entry.ids = new Set(reply.ids);
- if (view.root !== root || $('q').value.trim().toLowerCase() !== query) return;
- render();
- if (!$('find-results').hidden) showFound();
- }, () => {
- if (itemSearches.get(key) === entry) itemSearches.delete(key);
- });
- return local;
-}
-
-// Keep credential metadata apart from board snapshots and scoped to the selected project (H2,H9).
-const credentials = new Map();
-
-/** Draw only allowlisted credential metadata; bearer values never enter page state or markup. */
-function renderCredentials() {
- const region = $('credentials');
- region.hidden = snapshot || readOnly;
- if (region.hidden) { region.innerHTML = ''; return; }
- const state = credentials.get(view.root);
- /** Render an inventory timestamp without shortening its date or timezone. */
- const stamp = (value) => value === null ? 'Unknown' : new Date(value).toISOString();
- region.innerHTML = '<button class="link" data-credentials type="button" aria-expanded="' + Boolean(state) + '"' + (state?.busy ? ' disabled' : '') + '>Agent credentials</button>'
- + (state ? '<p role="status">' + esc(state.message || '') + '</p>'
- + state.tokens.map((row) => '<article class="credential" data-token-id="' + esc(row.id) + '"><b>' + esc(agentName(row.agent)) + '</b><code>' + esc(row.id) + '</code>'
- + '<dl><dt>Created</dt><dd>' + esc(stamp(row.created)) + '</dd><dt>Expires</dt><dd>' + esc(stamp(row.expires)) + '</dd></dl>'
- + (row.revoked ? '<span class="chip">Revoked</span>' : '<button class="ghost" type="button" data-revoke-token="' + esc(row.id) + '"' + (state.busy ? ' disabled' : '') + '>Revoke</button>') + '</article>').join('') : '');
-}
-
-/** Load this board's public metadata on demand, without granting any person authority. */
-async function loadCredentials(root = view.root) {
- if (snapshot || relayProject(root) || (!hosted.local && pageReadOnly)) return;
- const state = credentials.get(root) || { tokens: [], message: '', busy: false };
- credentials.set(root, state);
- state.message = 'Loading agent credentials…';
- if (root === view.root) renderCredentials();
- try {
- const reply = await api(boardPath(root) + '/tokens');
- state.tokens = reply.tokens.map(({ id, agent, created, expires, revoked }) => ({ id, agent, created, expires, revoked }));
- state.message = state.tokens.length ? '' : 'No agent credentials.';
- } catch (error) { state.message = String(error.message || error); }
- if (root === view.root) renderCredentials();
-}
-
-/** Revoke a listed id through the existing one-tap phone grant, then reread its public metadata. */
-async function revokeCredential(id) {
- if (snapshot || relayProject(view.root) || (!hosted.local && pageReadOnly)) return;
- const root = view.root, state = credentials.get(root);
- if (!state || state.busy || !state.tokens.some((row) => row.id === id && !row.revoked)) return;
- state.busy = true;
- state.message = 'Approve revocation on your phone…';
- renderCredentials();
- try {
- const result = await api(boardPath(root) + '/tokens', { id });
- if (result.id !== id || result.revoked !== true) throw new Error('Revocation was not acknowledged; refresh the credential list.');
- state.tokens = state.tokens.map((row) => row.id === id ? { ...row, revoked: true } : row);
- await loadCredentials(root);
- state.message = 'Credential revoked.';
- } catch (error) { state.message = String(error.message || error); }
- state.busy = false;
- if (root === view.root) renderCredentials();
-}
-
-/**
- * A board read as text with its clock readings blanked: the flow's observation time (asOf) and each queue's oldest age
- * (ageMinutes) are stamped afresh on every read, so two reads that differ only there show the same board (#644).
- * Matching whole JSON keys is safe: a quote inside any string value is escaped, so no title can look like one.
- */
-function boardText(state) {
- return JSON.stringify(state).replace(/"(asOf|ageMinutes)":(?:"[^"]*"|[-+.0-9eE]+|null)/g, '"$1":null');
-}
-
-/** Show each queue's oldest age from the board on hand in place: the one thing on the page that moves with the clock alone. */
-function showFlowAges() {
- const flow = data?.project?.proofStats?.flow;
- if (!flow) return;
- for (const node of document.querySelectorAll('#proof-stats [data-oldest]')) {
- const oldest = flow.queues[node.dataset.oldest]?.oldest;
- node.dataset.value = oldest?.ageMinutes ?? '';
- node.textContent = oldestLine(oldest);
- }
-}
-
-/** Refresh from API v1, every board or only those in fresh, and discard a response for a project the person left. */
-async function refresh(fresh = null) {
+${pageScriptPart3(pageScope)}async function refresh(fresh = null) {
const generation = ++refreshStarted;
const root = view.root;
const mark = root ? view.seen['pb.seen.' + root] ?? keep('pb.seen.' + root) : null;
@@ -2883,1118 +1436,7 @@ function render() {
* it, so it stays closed across reloads, and across restarts of the view, which serves from the
* same address again, until they open it. While hidden it is not drawn.
*/
-function showFlow(shown) {
- keep('pb.flow', shown ? 'shown' : 'hidden');
- $('flow-panel').hidden = !shown;
- $('flow-show').hidden = shown;
- if (shown && data && data.project) $('flow').innerHTML = flowSvg(data.project);
-}
-
-function showTab() {
- document.querySelectorAll('[data-pane]').forEach((pane) => { pane.hidden = pane.dataset.pane !== view.tab; });
- document.querySelectorAll('.tab').forEach((button) => button.classList.toggle('on', button.dataset.tab === view.tab));
- countUnseen();
- if (view.tab === 'shouts') foldShouts();
-}
-
-/** Read the selected repo, tab and detail from a path or the hosted page's fragment. */
-function placeAtAddress(page = data) {
- const tabs = ['items', 'shouts', 'spec', 'doctrine', 'activity', 'roadmap'];
- const hash = location.hash || '';
- let path = routed ? location.pathname || '/' : hash.slice(1);
- if (hash === '#items/pipeline' || hash === '#roadmap') path = hash.slice(1);
- if (hash.startsWith('#shout-')) path = 'shouts/' + hash.slice(7);
- let parts;
- try { parts = path.split('/').filter(Boolean).map(decodeURIComponent); }
- catch { parts = []; }
- const repo = page?.projects.find((entry) => entry.ok && entry.name === parts[0]);
- const group = page?.groups.find((entry) => entry.name === parts[0]);
- const named = (repo || group) && tabs.includes(parts[1]);
- const root = named ? repo?.root || group.key : null;
- if (named) parts.shift();
- const tab = tabs.includes(parts[0]) ? parts.shift() : (!path && transportModule && globalThis.history?.state?.tab) || homeTab();
- return { root, tab, detail: parts[0] ?? null };
-}
-
-/** Name each repo even beneath a group; one repo needs no prefix. */
-function tabHref(tab) {
- if (snapshot) {
- const detail = tab === 'items' && view.itemsView === 'pipeline' ? 'pipeline' : view.addressDetail;
- if (tab === 'items' && detail === null && !location.hash) return location.pathname + location.search;
- return location.pathname + location.search + '#' + tab + (detail === null ? '' : '/' + encodeURIComponent(String(detail)));
- }
- const repo = data?.projects.find((entry) => entry.root === view.root);
- const group = data?.groups.find((entry) => entry.key === view.root);
- const name = repo?.name || group?.name;
- const prefix = (data?.projects.filter((entry) => entry.ok).length || 0) > 1 && name ? '/' + encodeURIComponent(name) : '';
- const detail = tab === 'items' && view.itemsView === 'pipeline' && (view.addressDetail === null || view.addressDetail === 'pipeline') ? 'pipeline' : view.addressDetail;
- const path = prefix + '/' + tab + (detail === null ? '' : '/' + encodeURIComponent(String(detail)));
- return routed ? path + location.search : location.pathname + location.search + '#' + path.slice(1);
-}
-
-/** Push one entry per changed place, and retain native fact anchors when restoring an entry. */
-function address(push = true) {
- if (typeof history === 'undefined' || typeof location === 'undefined' || !addressReady) return;
- const state = { tab: view.tab, root: view.root, item: view.item, itemsView: view.itemsView, detail: view.addressDetail };
- let href = tabHref(view.tab);
- if (!push && routed && location.hash && !['#roadmap', '#items/pipeline'].includes(location.hash)) href += location.hash;
- try {
- if (push && href !== location.pathname + location.search + (location.hash || '')) history.pushState(state, '', href);
- else if (transportModule && !location.hash && view.tab === 'items' && view.addressDetail === null) history.replaceState(state, '');
- else history.replaceState(state, '', href);
- } catch { /* A host that refuses history changes still shows the selected place. */ }
-}
-
-/** Apply a parsed selection without recording another history entry. */
-function applyPlace(place, kept = null) {
- if (place.root) view.root = place.root;
- view.tab = place.tab;
- view.addressDetail = place.detail;
- view.item = place.tab === 'items' && place.detail !== null && place.detail !== 'pipeline' ? Number(place.detail) : null;
- view.itemsView = place.tab === 'items' && place.detail === 'pipeline' ? 'pipeline' : 'list';
- if (place.tab === 'items' && kept?.root === view.root && kept.tab === place.tab && kept.detail === place.detail && kept.itemsView === 'pipeline') view.itemsView = 'pipeline';
- view.shout = place.tab === 'shouts' && place.detail !== null ? Number(place.detail) : null;
- view.agent = null;
- view.unread = null;
- view.roadmapOnly = null;
- if (place.tab === 'spec' || place.tab === 'doctrine') {
- view.row[place.tab] = place.detail;
- if (place.detail !== null) view.rows[place.tab] = 'all';
- }
- view.scrollPlace = place.detail !== null;
- keep('pb.project', view.root);
- if (place.tab !== 'roadmap') keep('pb.tab', place.tab);
-}
-
-/** Restore the address on Back and Forward, with a scoped refresh when the repo changes. */
-function fromAddress(event) {
- if (!data) return;
- // Back and Forward close Approve all's confirmation and the decline dialog without recording, wherever they lead.
- leaveDialogs();
- // The configured relay transport owns pairing fragments and removes their secrets itself.
- if (transportModule) {
- const pairing = new URLSearchParams((location.hash || '').slice(1));
- if (['board', 'key', 'device'].some((name) => pairing.has(name))) return;
- }
- if (snapshot) {
- const kept = event?.state || {};
- const place = location.hash ? placeAtAddress() : { root: null, tab: kept.tab || homeTab(), detail: kept.detail ?? null };
- applyPlace(place, kept);
- if (kept.root && kept.root !== view.root) return switchTo(kept.root, view.item, false);
- } else {
- const place = placeAtAddress();
- // A native timeline anchor keeps its existing DOM target and the browser's own scroll.
- if ((location.hash || '').startsWith('#fact-') && place.tab === 'items' && (!place.root || place.root === view.root) && (place.detail === null || Number(place.detail) === view.item)) { address(false); return; }
- const previous = view.root;
- applyPlace(place, event?.state);
- if (previous !== view.root) return switchTo(view.root, view.item, false);
- }
- address(false);
- render();
- void loadAddressedShout();
-}
-
-/** Pick a tab or an explicit detail and record the complete place once. */
-function openTab(tab, detail = null) {
- view.tab = tab;
- view.addressDetail = detail;
- view.shout = tab === 'shouts' && detail !== null ? Number(detail) : null;
- view.scrollPlace = detail !== null;
- if (tab !== 'roadmap') keep('pb.tab', tab);
- address();
-}
-
-/** Fetch one old shout through the same public read API used by local and relay views. */
-async function loadAddressedShout() {
- if (!data?.project || view.tab !== 'shouts' || view.shout === null || data.root !== view.root) return;
- const root = view.root, id = view.shout, key = JSON.stringify([root, id]);
- if (data.project.shouts.some((entry) => entry.shout_id === id) || addressedShouts.has(key)) return;
- const entry = { shout: null, error: null };
- addressedShouts.set(key, entry);
- try {
- const reply = await api(boardPath(root) + '/shouts/' + encodeURIComponent(String(id)));
- entry.shout = reply.shout;
- } catch (error) {
- const message = String(error.message || error);
- entry.error = relayProject(root) && !message.includes('NO_SHOUT')
- ? 'This shout is older than the relay holds. Open its address in the local project view.'
- : 'No shout #' + id + ' exists here. ' + message;
- }
- if (view.root === root && view.shout === id && view.tab === 'shouts') render();
-}
-
-/** Scroll a newly addressed detail once, after its real content has arrived. */
-function revealPlace() {
- if (!view.scrollPlace) return;
- const fact = view.tab === 'items' && (location.hash || '').startsWith('#fact-') ? $(location.hash.slice(1)) : null;
- const element = fact || (view.tab === 'shouts' ? $('shout-' + view.shout)
- : view.tab === 'items' ? $('detail')
- : ['spec', 'doctrine'].includes(view.tab) ? $(view.tab + '-detail') : null);
- if (!element || (view.tab === 'shouts' && !element.querySelector('h2'))) return;
- element.scrollIntoView({ block: 'center', behavior: 'instant' });
- view.scrollPlace = false;
-}
-
-/**
- * Count on the Shouts tab the shouts that came after the newest one the person has seen in this
- * project. Seeing means having the Shouts tab open with the board drawn; a project shown for the
- * first time has seen everything so far. The mark is kept in this browser, so a reload counts
- * nothing old. The board counts the shouts since the mark the last refresh sent, so a burst larger
- * than the forty loaded still counts in full; until a moved mark reaches the board, the loaded
- * shouts count, which is exact then since the mark only ever moves to the newest.
- */
-function countUnseen() {
- const p = data && data.project;
- // While a switch loads, the board on hand is the last project's: it marks nothing for this one.
- if (!p || data.root !== view.root) return;
- const key = 'pb.seen.' + view.root;
- const kept = view.seen[key] ?? keep(key);
- const newest = p.shouts.length ? p.shouts[0].shout_id : 0;
- const seen = view.tab === 'shouts' || kept === null || kept === undefined ? newest : Number(kept);
- if (String(seen) !== String(kept)) { view.seen[key] = seen; keep(key, String(seen)); }
- const unread = (p.unseen && p.unseen.since === seen ? p.unseen.count : p.shouts.filter((x) => x.shout_id > seen).length) || 0;
- const slot = $('status-unread');
- if (slot) { slot.innerHTML = '<b>' + unread + '</b> unread'; slot.hidden = !unread; }
-}
-
-/** A quiet line that opens what it counts: what it says, everything it holds on hover, and show or hide. */
-function foldLine(name, text, names) {
- return '<button class="fold-line" data-fold="' + name + '" type="button" aria-expanded="' + Boolean(view.open[name]) + '" title="' + esc(names) + '"><span>' + esc(text) + '</span><span class="fold-more">' + (view.open[name] ? 'hide' : 'show') + '</span></button>';
-}
-
-/**
- * Address the composer: the coordinator unless someone else is named, who then shows as a chip the person can clear.
- */
-function addressTo(to) {
- const who = to || 'coordinator';
- $('shout-to').value = who;
- $('shout-to-chip').hidden = who === 'coordinator';
- $('shout-to-chip').innerHTML = who === 'coordinator' ? '' : 'to <b>' + esc(agentName(who)) + '</b><button class="to-clear" data-to-clear type="button" aria-label="Shout to the coordinator instead">×</button>';
- $('shout-text').placeholder = 'Shout to ' + (who === 'coordinator' ? 'the coordinator' : agentName(who));
-}
-
-/**
- * Put the shout form in answer mode for an open decision (B21), or back to a plain shout with null.
- * The form is never redrawn, so what the person types survives every refresh; only its answer line,
- * its To and its button change. The To the person had comes back when the answer is done. An answer
- * belongs to the project whose question it shows: leaving that project leaves answer mode.
- */
-function answer(id) {
- const ask = id === null ? null : data.project.decisions.find((d) => d.shout_id === id) || null;
- if (ask && !view.answering) view.to = $('shout-to').value;
- if (!ask && view.answering) addressTo(view.to);
- view.answering = ask ? { root: view.root, id: ask.shout_id } : null;
- $('answering').hidden = !ask;
- $('answering-who').textContent = ask ? agentName(ask.shout_from) : '';
- const question = ask ? linked(ask.shout_text, new Map(data.project.items.map((i) => [String(i.id), i.title]))) : '';
- if (question.includes('<a class="ref"')) $('answering-q').innerHTML = question;
- else $('answering-q').textContent = ask ? ask.shout_text : '';
- if (ask) addressTo(ask.shout_from);
- $('shout-to').disabled = Boolean(ask);
- $('shout-to-chip').hidden = Boolean(ask) || $('shout-to').value === 'coordinator';
- const verb = ask ? 'Answer' : 'Shout';
- $('shout-send').setAttribute('aria-label', verb);
- $('shout-send').title = verb + ' (Enter; Shift+Enter for a new line)';
- if (ask) $('shout-text').focus();
-}
-
-/** Open what a status-bar part counts: its tab, narrowed to exactly those. */
-function statusGo(to) {
- view.unread = null;
- view.roadmapOnly = null;
- if (to.startsWith('item:')) return go(to);
- if (to === 'items') { view.state = 'active'; view.lane = null; view.before = null; $('q').value = ''; openTab('items'); }
- else if (to === 'verify' || to === 'gated') { view.state = to; view.lane = null; view.before = null; $('q').value = ''; openTab('items'); }
- else if (to === 'unread') {
- // Only the shouts after the mark the person had; opening Shouts then moves the mark past them.
- const key = 'pb.seen.' + view.root;
- view.unread = { root: view.root, after: Number(view.seen[key] ?? keep(key) ?? 0) };
- view.agent = null;
- openTab('shouts');
- }
- // The agents it counts are the panel's rows, so it opens the panel even where the person hid it.
- else if (to === 'agents') { view.agentsHidden = false; keep('pb.agents', 'shown'); view.agent = null; openTab('shouts'); }
- // The release it counts is one milestone, so the Roadmap opens on that one alone.
- else if (to === 'release') { view.roadmapOnly = nextMilestone(data.project)?.name ?? null; openTab('roadmap'); }
- else openTab(to);
- showTab();
- render();
-}
-
-/**
- * Follow a link in the page: an item, a spec row, a tab or a decision to answer. An item can live on
- * another project's board, root, which the page then switches to.
- */
-function go(target, root = view.root) {
- const [kind, id] = target.split(':');
- let tab = view.tab;
- if (kind === 'item') { tab = 'items'; view.state = 'all'; view.before = null; }
- else if (kind === 'spec') { tab = 'spec'; view.row.spec = id; view.rows.spec = 'all'; }
- else if (kind === 'doctrine') { tab = 'doctrine'; view.row.doctrine = id; view.rows.doctrine = 'all'; }
- else if (kind === 'shout') { tab = 'shouts'; view.agent = null; view.unread = null; }
- else if (kind === 'tab') tab = id;
- else if (kind === 'decide') { tab = 'shouts'; answer(Number(id)); }
- if (kind === 'item') { view.tab = 'items'; view.itemsView = 'list'; pick(Number(id), root); }
- else { openTab(tab, ['spec', 'doctrine', 'shout'].includes(kind) ? id : null); render(); }
- if (kind === 'shout') void loadAddressedShout();
-}
-
-/** An item's state as a word, for a search result. */
-const stateLabel = (i) => ({ building: 'building', verify: 'to verify', verified: 'verified', back: 'sent back', open: 'open', withdrawn: 'withdrawn' })[stateOf(i)] || stateOf(i);
-
-/** A shout's kind as a word, for a search result. */
-const shoutKind = (x) => (x.shout_decision ? 'decision' : x.shout_answers ? 'answer' : x.shout_evidence_kind ? 'evidence' : 'shout');
-
-/** Everything on the board that matches the top bar's words: items, Spec rows, Doctrine rules and shouts, newest first. */
-function findAll(words) {
- const p = data?.project, q = words.trim().toLowerCase();
- if (!p || !q) return [];
- const has = (...parts) => parts.join(' ').toLowerCase().includes(q);
- const ids = searchIds(p, q);
- const items = p.items.filter((item) => ids.has(item.id))
- .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).map((item) => ({ go: 'item:' + item.id, id: '#' + item.id, text: item.title, note: stateLabel(item) }));
- // A Spec row or Doctrine rule is as new as the commit that added it (0 not yet committed; a standard rule, never added
- // here, last); rows one commit added together read newest first by their place in the file.
- const rows = (kind, list) => list.map((r, at) => ({ r, at })).filter(({ r }) => has(r.id, r.text))
- .sort((a, b) => (a.r.added ?? Infinity) - (b.r.added ?? Infinity) || b.at - a.at)
- .map(({ r }) => ({ go: kind + ':' + r.id, id: r.id, text: r.text, note: r.stage || r.status }));
- const shouts = p.shouts.filter((x) => has(x.shout_from, x.shout_to, x.shout_text)).map((x) => ({ go: 'shout:' + x.shout_id, id: '#' + x.shout_id, text: firstLine(x.shout_text), note: shoutKind(x) }));
- return [['Items', items], ['Spec', rows('spec', p.spec)], ['Doctrine', rows('doctrine', p.practice)], ['Shouts', shouts]].filter(([, list]) => list.length);
-}
-
-/** Draw the search's results under it: up to five a group, the highlighted one ready for Enter. */
-function showFound() {
- const box = $('find-results'), words = $('q').value;
- const groups = findAll(words);
- view.found = groups.flatMap(([, list]) => list.slice(0, 5));
- view.foundAt = Math.min(view.foundAt || 0, Math.max(0, view.found.length - 1));
- let n = 0;
- box.innerHTML = groups.length ? groups.map(([name, list]) => '<h4>' + name + '<span>' + (list.length > 5 ? '5 of ' + list.length : list.length) + '</span></h4>'
- + list.slice(0, 5).map((hit) => '<button class="find-hit' + (n++ === view.foundAt ? ' on' : '') + '" data-find="' + esc(hit.go) + '" type="button" role="option"><code>' + esc(hit.id) + '</code><span>' + esc(hit.text) + '</span><small>' + esc(hit.note) + '</small></button>').join('')).join('')
- : '<div class="find-empty">Nothing on this board matches “' + esc(words.trim()) + '”.</div>';
- box.hidden = !words.trim();
- box.dataset.why = box.hidden ? 'no words' : '';
-}
-
-/** Put the search's results away, and say why on the box, so whoever finds them gone can name what closed them. */
-function hideFound(why) {
- $('find-results').hidden = true;
- $('find-results').dataset.why = why;
-}
-
-/** Open what a result names, and put the results away. */
-function openFound(target) {
- hideFound('opened');
- $('q').blur();
- go(target);
-}
-
-/** Show an item's detail, on another project's board when root names one. */
-function pick(id, root = view.root) {
- view.adding = false;
- if (root !== view.root) return switchTo(root, id);
- if (itemDetails.get(root + '\\n' + id)?.error) itemDetails.delete(root + '\\n' + id);
- view.tab = 'items';
- keep('pb.tab', view.tab);
- view.item = id;
- view.addressDetail = String(id);
- address();
- render();
- reveal();
-}
-
-/** Where the list and the detail stack (under 900px), bring the detail into view. */
-function reveal() {
- if (matchMedia('(max-width: 900px)').matches) $('detail').scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' });
-}
-
-/**
- * A search looks through every state. Each keystroke with text in the box selects All, even after a
- * chip was clicked mid-search; emptying the box brings back the chip from before the search began.
- */
-function search() {
- if ($('q').value.trim()) {
- if (view.before == null) view.before = view.state;
- view.state = 'all';
- } else if (view.before != null) {
- view.state = view.before;
- view.before = null;
- }
- render();
-}
-
-/**
- * Open or close the code a path:lines@commit reference names (B23). The first open asks the view for
- * those lines as they were at that commit; the answer stays with the page, so every refresh redraws
- * it, and a failed ask is tried again on the next open.
- */
-async function code(ref, before) {
- const c = (view.code[view.root + '\\n' + before + '\\n' + ref] ??= { open: false });
- c.open = !c.open;
- render();
- if (!c.open || c.lines) return;
- c.error = null;
- if (snapshot) {
- c.error = 'Source code is not included in this relay snapshot; open the reference in the local project view.';
- render();
- return;
- }
- if (relayProject(view.root)) {
- c.error = 'Source code is unavailable in a relay view; open this reference in the local project view.';
- render();
- return;
- }
- try {
- const reply = await api(boardPath(view.root) + '/code?ref=' + encodeURIComponent(ref) + '&before=' + encodeURIComponent(before));
- Object.assign(c, reply.code);
- } catch (error) {
- c.error = String(error.message || error);
- }
- render();
-}
-
-/** Fetch the rest of a bounded local reference in API-sized windows after an explicit request. */
-async function showAllCode(ref, before) {
- const root = view.root;
- const c = view.code[root + '\\n' + before + '\\n' + ref];
- const parts = codeReferenceParts(ref);
- if (!c || c.allLoading) return;
- if (relayProject(root)) { c.error = 'Source code is unavailable in a relay view; open this reference in the local project view.'; render(); return; }
- if (!parts) { c.error = 'Code reference has an invalid path, range or commit SHA.'; render(); return; }
- c.error = null;
- c.allLoading = true;
- render();
- try {
- const lines = [];
- for (let from = parts.from; from <= parts.to; from += 60) {
- const to = Math.min(parts.to, from + 59);
- const pageRef = parts.path + ':' + from + (to === from ? '' : '-' + to) + '@' + parts.commit;
- const page = await api(boardPath(root) + '/code?ref=' + encodeURIComponent(pageRef) + '&before=' + encodeURIComponent(before));
- lines.push(...page.code.lines);
- }
- if (lines.length !== parts.to - parts.from + 1) throw new Error('The local view returned an incomplete code range.');
- c.allLines = lines;
- c.all = true;
- } catch (error) {
- c.error = String(error.message || error);
- } finally {
- c.allLoading = false;
- render();
- }
-}
-
-/** Return an expanded preview to its first bounded window without closing the reference. */
-function showLessCode(ref, before) {
- const c = view.code[view.root + '\\n' + before + '\\n' + ref];
- if (!c) return;
- c.all = false;
- render();
-}
-
-/** Translate person actions into their public literal intent and a familiar command label. */
-function pageMove(command, args = {}) {
- /** Trim form values before constructing the move and its display label. */
- const text = (value) => String(value || '').trim();
- if (command === 'add') {
- const fields = { lane: text(args.lane), title: text(args.title) };
- const label = ['add', fields.lane, fields.title];
- for (const name of ['criterion', 'specs', 'brief']) if (text(args[name])) { fields[name] = text(args[name]); label.push('--' + name, fields[name]); }
- return { body: { verb: 'add', args: fields }, label: label.join(' ') };
- }
- if (command === 'shout') return { body: { verb: 'shout', args: { to: text(args.to), text: text(args.text) } }, label: ['shout', text(args.to), text(args.text)].join(' ') };
- if (command === 'answer') return { body: { verb: 'answer', item: Number(args.id), args: { text: text(args.text), as: 'person' } }, label: ['answer', text(args.id), text(args.text), '--as', 'person'].join(' ') };
- if (command === 'hold') return { body: { verb: 'hold', args: { lane: text(args.lane), reason: text(args.reason) } }, label: ['hold', text(args.lane), '--reason', text(args.reason)].join(' ') };
- if (command === 'release') return { body: { verb: 'hold', args: { lane: text(args.lane), off: true } }, label: ['hold', text(args.lane), '--off'].join(' ') };
- if (command === 'spec-approve') {
- const ids = text(args.ids);
- if (!ids) throw new Error('Choose at least one spec row to approve.');
- return { body: { verb: 'spec-approve', args: { ids } }, label: 'spec approve ' + ids };
- }
- if (command === 'spec-decline') {
- const ids = text(args.ids), reason = text(args.reason);
- if (!ids || !reason) throw new Error('Choose a spec row and enter a reason to decline it.');
- return { body: { verb: 'spec-decline', args: { ids, reason } }, label: 'spec decline ' + ids + ' --reason ' + reason };
- }
- throw new Error('No view action ' + String(command) + '; choose add, shout, answer, hold or release.');
-}
-
-/** Describe an API-confirmed move without exposing its transport document in the page. */
-function moveMessage(move, result) {
- if (move.verb === 'add') return 'added #' + result.item.item_id;
- if (move.verb === 'shout') return 'shouted to ' + move.args.to;
- if (move.verb === 'answer') return 'answered #' + move.item;
- if (move.verb === 'spec-approve') return 'approved rows ' + move.args.ids + ' (pending apply)';
- if (move.verb === 'spec-decline') return 'declined rows ' + move.args.ids + ' (pending apply)';
- return move.args.off ? 'released the ' + move.args.lane + ' lane' : 'holding the ' + move.args.lane + ' lane: ' + move.args.reason;
-}
-
-/** Render escaped decision feedback beside the affected Spec row (B26, N26). */
-function specFeedback(feedback) {
- return '<div class="spec-feedback ' + feedback.tone + '" role="status">' + esc(feedback.text) + '</div>';
-}
-
-/** Ask why a Spec row or Doctrine rule is declined; the reason, once given, is recorded where it was asked. */
-function askDecline(kind, id, from) {
- view.declining = id;
- view.declineKind = kind;
- view.declineFrom = from;
- // The dialog belongs to the board it was opened on, as Approve all's confirmation does (#612).
- view.declineRoot = view.root;
- $('spec-decline-title').textContent = 'Decline ' + id;
- $('spec-decline-reason').value = '';
- openModal($('spec-decline-dialog'), $('spec-decline-reason'));
-}
-
-/**
- * Close the decline dialog and return what it asked about. Closed by the person, focus returns to the list it was asked
- * from; closed because the page left its board, focus stays where the person put it.
- */
-function closeDecline(left = false) {
- const asked = view.declining ? { id: view.declining, kind: view.declineKind, root: view.declineRoot, from: view.declineFrom } : null;
- view.declining = null;
- closeModal($('spec-decline-dialog'));
- if (!left && asked?.from === 'list') $(asked.kind + '-list').focus({ preventScroll: true });
- return asked;
-}
-
-/**
- * Ask in the page before one press approves every undecided row of a Spec section (B26, N26). The browser's own confirm
- * dialog can be dismissed or never shown, and then the press recorded nothing and said nothing; this one is the page's.
- */
-function askApproveAll(section) {
- const ids = data.project.spec.filter((row) => row.section === section && ['pending', 'draft'].includes(row.status) && !row.decision).map((row) => row.id);
- // Every row was decided after the last redraw; this one drops the stale control.
- if (!ids.length) { render(); return; }
- // The confirmation belongs to the board it was opened on: its rows are that board's, and only that board records them.
- view.approvingAll = { root: view.root, section, ids };
- $('spec-approve-title').textContent = 'Approve all ' + ids.length + (ids.length === 1 ? ' undecided row in “' : ' undecided rows in “') + section + '”?';
- $('spec-approve-rows').textContent = 'Rows: ' + ids.join(', ');
- $('spec-approve-submit').textContent = 'Approve ' + ids.length + (ids.length === 1 ? ' row' : ' rows');
- openModal($('spec-approve-dialog'), $('spec-approve-submit'));
-}
-
-/**
- * Close the Approve all confirmation. Cancelled, focus returns to the section control that opened it; approved, to the
- * list, since the section's control leaves once its rows are decided. Closed because the page left its board, focus
- * stays where the person put it.
- */
-function closeApproveAll(approved = false, left = false) {
- const asked = view.approvingAll;
- view.approvingAll = null;
- closeModal($('spec-approve-dialog'));
- if (left) return asked;
- const control = !approved && asked && [...$('spec-list').querySelectorAll('[data-section-approve]')].find((button) => button.dataset.sectionApprove === asked.section);
- (control || $('spec-list')).focus({ preventScroll: true });
- return asked;
-}
-
-/** Close, recording nothing, a confirmation or decline opened on another board than the one the page now shows. */
-function closeIfLeft() {
- if (view.approvingAll && view.approvingAll.root !== view.root) closeApproveAll(false, true);
- if (view.declining && view.declineRoot !== view.root) closeDecline(true);
-}
-
-/** Close every dialog bound to a board, recording nothing: the page is leaving the board it was asked on. */
-function leaveDialogs() {
- if (view.approvingAll) closeApproveAll(false, true);
- if (view.declining) closeDecline(true);
-}
-
-/**
- * Show a page dialog over an inert page: nothing behind it takes a click or focus while it is open, so the person
- * cannot act on the page, or switch the board, under a question the page is asking.
- */
-function openModal(dialog, focus) {
- openPageDialog(dialog, focus, pageDialogs);
-}
-
-/** Hide a page dialog and give the page back its clicks and focus. */
-function closeModal(dialog) {
- if (closePageDialog(dialog, pageDialogs) && deferredClickRender) requestAnimationFrame(() => { if (!pageDialogs.size && heldClickPointer === null && deferredClickRender) { deferredClickRender = false; render(); } });
-}
-
-/** Keep Tab and Shift+Tab cycling through an open page dialog's own controls. */
-function trapFocus(event) {
- if (event.key !== 'Tab') return;
- const controls = [...event.currentTarget.querySelectorAll('button, input, select, textarea, a[href]')].filter((control) => !control.disabled && control.offsetParent !== null);
- if (!controls.length) return;
- event.preventDefault();
- const at = controls.indexOf(document.activeElement);
- const next = at < 0 ? (event.shiftKey ? controls.length - 1 : 0) : (at + (event.shiftKey ? controls.length - 1 : 1)) % controls.length;
- controls[next].focus();
-}
-
-/**
- * Record a Spec or Doctrine decision beside its row and retain the list's reading position (B26, N26). A Doctrine rule
- * goes to the board by its qualified id, doctrine:D1, as the command line names it (pullboard spec approve doctrine:D1).
- */
-async function decideRow(kind, command, args, anchor) {
- if (snapshot || (readOnly && !requests)) return false;
- const requestMode = requests;
- const root = view.root, scroll = window.scrollY;
- const ids = String(args.ids).split(/\s+/);
- const prefix = kind + ':';
- const rows = [...$(kind + '-list').querySelectorAll('[data-row]')];
- const index = rows.findIndex((row) => row.dataset.row === prefix + ids[0]);
- const next = rows.slice(index + 1).find((row) => !ids.includes(row.dataset.row.slice(prefix.length)))?.dataset.row.slice(prefix.length);
- const feedback = { kind, root, id: ids[0], next, from: anchor?.closest('#' + kind + '-detail') ? 'detail' : 'list', tone: '', text: 'Recording decision…' };
- view.specFeedback = feedback;
- render();
- // A waiting request keeps its row; let browser anchoring follow growth above it.
- if (!requestMode) window.scrollTo({ top: scroll, behavior: 'instant' });
- try {
- const move = pageMove(command, kind === 'doctrine' ? { ...args, ids: ids.map((id) => 'doctrine:' + id).join(' ') } : args);
- const result = requestMode ? await sendPersonRequest(root, move.body) : await api(boardPath(root) + '/moves', move.body);
- const request = requestMode && result?.result?.request;
- if (requestMode && (!request?.id || !['waiting', 'done', 'refused'].includes(request.status))) throw new Error('The request did not include its status; refresh the board to check it.');
- feedback.tone = requestMode ? request.status === 'done' ? 'ok' : request.status === 'refused' ? 'no' : '' : 'ok';
- feedback.text = requestMode ? requestNotice(request) : moveMessage(move.body, result.result);
- if (requestMode) { feedback.requestId = request.id; feedback.status = request.status; }
- // Decided from the list, the pick moves on to the next row before the board redraws without the decided one, so
- // the next key decides that one.
- if (feedback.from === 'list' && feedback.tone !== 'no' && next && view.row[kind] === ids[0] && root === view.root) view.row[kind] = next;
- await refresh();
- } catch (error) {
- feedback.tone = 'no';
- feedback.text = String(error.message || error);
- }
- if (root === view.root && view.specFeedback === feedback) {
- render();
- if (!requestMode) window.scrollTo({ top: scroll, behavior: 'instant' });
- // A phone row click jumps to its detail. A later list-key decision returns the next pick to view,
- // instead of restoring that detail's scroll position with the focused list still offscreen.
- if (feedback.from === 'list' && feedback.tone === 'ok' && next && view.row[kind] === next) {
- const picked = [...$(kind + '-list').querySelectorAll('[data-row]')].find((row) => row.dataset.row === prefix + next);
- const rect = picked?.getBoundingClientRect();
- // Center an offscreen pick: nearest can round a half-pixel edge just outside the viewport.
- if (rect && (rect.top < 0 || rect.bottom > innerHeight)) picked.scrollIntoView({ block: 'center', behavior: 'instant' });
- }
- if (!requestMode || feedback.status === 'done') setTimeout(() => { if (view.specFeedback === feedback) { view.specFeedback = null; render(); } }, 6000);
- }
- return requestMode ? Boolean(feedback.requestId) && feedback.status !== 'refused' : feedback.tone === 'ok';
-}
-
-/**
- * Run a public API move beside its action and let only the latest one own the console and timer. The move's own
- * reply is its outcome (#748): the board is read again afterwards, but that read covers every source on a hosted
- * page, and a slow or failing read of another board must neither hold back nor undo a move that went through.
- */
-async function act(command, args, anchor) {
- const out = $('console');
- if (snapshot || (readOnly && !requests)) { out.hidden = false; out.className = 'console no'; out.textContent = snapshot ? 'This is a read-only snapshot.' : 'This is a read-only view.'; return false; }
- const requestMode = requests;
- // A form's result stands above its actions, or above the shout composer's bar, never inside that one row.
- if (anchor) {
- const target = anchor.matches('form')
- ? anchor.querySelector('.actions') || anchor.querySelector('.composer') || anchor.querySelector('[type="submit"]') || anchor
- : anchor.closest('#lanes') || anchor;
- target.insertAdjacentElement(anchor.matches('form') ? 'beforebegin' : 'afterend', out);
- }
- const run = (view.acting = (view.acting || 0) + 1);
- const root = view.root;
- const latest = () => run === view.acting && root === view.root;
- view.request = null;
- clearTimeout(view.closing);
- out.hidden = false;
- out.className = 'console';
- out.textContent = requestMode ? 'Request waiting…' : 'running…';
- out.scrollIntoView({ block: 'nearest' });
- try {
- // On the local view the person's word to the coordinator is the person's own request, not a shout the
- // coordinator sends itself; through the relay every action is already a sealed request.
- const asked = command === 'request' && !requestMode;
- const move = asked ? null : pageMove(command === 'request' ? 'shout' : command, command === 'request' ? { to: 'coordinator', text: args.text } : args);
- const result = asked ? await api(boardPath(root) + '/requests', { text: String(args.text || '').trim() })
- : requestMode ? await sendPersonRequest(root, move.body) : await api(boardPath(root) + '/moves', move.body);
- const request = requestMode && result?.result?.request;
- if (requestMode && (!request?.id || !['waiting', 'done', 'refused'].includes(request.status))) throw new Error('The request did not include its status; refresh the board to check it.');
- if (latest()) {
- out.className = 'console' + (requestMode ? request.status === 'done' ? ' ok' : request.status === 'refused' ? ' no' : '' : ' ok');
- out.textContent = requestMode ? requestNotice(request) : asked ? 'Sent to the coordinator.' : '$ pullboard ' + move.label + '\\n' + moveMessage(move.body, result.result);
- if (requestMode) view.request = { root, id: request.id, run };
- out.scrollIntoView({ block: 'center' });
- // What went through says so and then steps aside; a refusal stays until the person closes it.
- if (!requestMode || request.status === 'done') view.closing = setTimeout(() => { if (latest()) out.hidden = true; }, 6000);
- }
- // The result was already revealed. A late refresh must not scroll after the person aims at the next action.
- refresh().catch((error) => { $('live').textContent = 'offline: ' + String(error.message || error); });
- return !requestMode || request.status !== 'refused';
- } catch (error) {
- if (latest()) {
- out.className = 'console no';
- out.textContent = String(error.message || error);
- out.scrollIntoView({ block: 'center' });
- }
- return false;
- }
-}
-
-/**
- * Move every age on the page on to now, where it stands. A list is rebuilt only when the board
- * changes, so a click is never lost to a rebuild; on a quiet board the ages would otherwise stay
- * as old as the page.
- */
-/** Shouts the person opened past their six lines, kept across refreshes. */
-const openShouts = new Set();
-
-/** Fold each shout taller than six lines, with 'more' to open it; measured only while Shouts shows. */
-function foldShouts() {
- if ($('feed').offsetParent === null) return;
- document.querySelectorAll('#feed .shout, #decisions .shout').forEach((card) => {
- const text = card.querySelector('.text');
- card.classList.add('clamp');
- card.classList.toggle('clamp', card.classList.contains('open') || text.scrollHeight > text.clientHeight + 1);
- });
-}
-
-function tickAges() {
- document.querySelectorAll('[data-ago]').forEach((node) => { node.textContent = node.classList.contains('long') ? agoLong(node.dataset.ago) : ago(node.dataset.ago); });
- tickDays();
-}
-
-/**
- * Once the clock has passed midnight since the page named its days, rename them in place with no redraw (#644): the
- * day that was Today and the one that was Yesterday get their names for now, and the shouts, which carry no rule above
- * today's, get one above what is no longer today. Every other day was named by its date and stays true.
- */
-function tickDays() {
- const then = daysNamedAt, now = new Date();
- if (then.toDateString() === now.toDateString()) return;
- const before = new Date(then);
- before.setDate(then.getDate() - 1);
- const names = { Today: dayName(then.toISOString()), Yesterday: dayName(before.toISOString()) };
- document.querySelectorAll('.feed .day, #feed > .day-rule span').forEach((node) => { if (names[node.textContent]) node.textContent = names[node.textContent]; });
- const first = $('feed')?.querySelector?.('.shout');
- if (first && !first.previousElementSibling?.classList?.contains('day-rule')) first.insertAdjacentHTML('beforebegin', '<div class="day-rule" role="separator"><span>' + names.Today + '</span></div>');
- daysNamedAt = now;
-}
-
-/** Open or close the project list where the sidebar is folded into a top bar (under 900px). */
-function fold(open) {
- $('side').classList.toggle('open', open);
- $('proj-switch').setAttribute('aria-expanded', String(open));
-}
-
-/** Show another project and its item; history restores keep the tab their entry named. */
-function switchTo(root, target = null, record = true) {
- // Switching board or project closes Approve all's confirmation and the decline dialog; neither records on either board.
- leaveDialogs();
- const generation = ++switchGeneration;
- answer(null);
- view.root = root;
- syncBoardMode(root);
- const item = typeof target === 'number' ? target : /^item:(\\d+)$/.exec(target || '');
- const requestedItem = typeof item === 'number' ? item : item ? Number(item[1]) : null;
- view.item = requestedItem;
- view.adding = false;
- if (record && view.item !== null) { view.tab = 'items'; keep('pb.tab', view.tab); }
- keep('pb.project', root);
- if (record) { view.addressDetail = requestedItem === null ? null : String(requestedItem); view.shout = null; address(); }
- fold(false);
- // The board that arrives is drawn even if it matches the last one seen, so the pick is made from it.
- seen = '';
- if (data) render();
- document.body.classList.add('switching');
- return refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }).finally(() => {
- if (generation === switchGeneration) document.body.classList.remove('switching');
- if (generation === switchGeneration && requestedItem !== null && view.item === requestedItem && view.root === root && view.tab === 'items') reveal();
- });
-}
-
-// The Shouts tab's own controls: a folded shout's more and less, every agent or only those at work, the agents
-// panel hidden or shown, and an agent's name, which filters the feed to its shouts and addresses the composer to it.
-$('shouts-pane').addEventListener('click', (event) => {
- if (event.target.closest('[data-credentials]')) { void loadCredentials(); return; }
- const revoke = event.target.closest('[data-revoke-token]');
- if (revoke) { void revokeCredential(revoke.dataset.revokeToken); return; }
- const more = event.target.closest('[data-more]'), pick = event.target.closest('[data-agent]');
- if (more) {
- const card = more.closest('.shout'), id = Number(card.dataset.shoutId);
- if (openShouts.has(id)) openShouts.delete(id); else openShouts.add(id);
- card.classList.toggle('open', openShouts.has(id));
- more.textContent = openShouts.has(id) ? 'less' : 'more';
- return;
- }
- if (event.target.closest('[data-to-clear]')) { addressTo('coordinator'); $('shout-text').focus(); return; }
- const folded = event.target.closest('[data-fold]');
- if (folded) { view.open[folded.dataset.fold] = !view.open[folded.dataset.fold]; render(); return; }
- if (event.target.closest('[data-all-agents]')) { view.allAgents = !view.allAgents; render(); return; }
- if (event.target.closest('[data-agents-toggle]')) { view.agentsHidden = !view.agentsHidden; keep('pb.agents', view.agentsHidden ? 'hidden' : 'shown'); render(); return; }
- if (event.target.closest('[data-unread]')) { view.unread = null; render(); return; }
- if (!pick) return;
- view.unread = null;
- view.agent = pick.dataset.agent && pick.dataset.agent !== view.agent ? pick.dataset.agent : null;
- if (!view.answering) addressTo(view.agent);
- render();
-});
-// Enter shouts; Shift+Enter starts a new line.
-$('shout-text').addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); $('shout-form').requestSubmit(); } });
-document.addEventListener('click', (event) => {
- // The open-board screens name their state in data-state and handle their own presses (#764).
- if (event.target.closest('#local-note')) return;
- if (view.filterOpen && !event.target.closest('.filter-control')) { view.filterOpen = false; render(); }
- const t = event.target.closest('[data-filter-toggle],[data-filter-choice],[data-status],[data-roadmap-jump],[data-shout-id],[data-roadmap-key],[data-roadmap-all],[data-root],[data-tab],[data-go],[data-item],[data-items-view],[data-state],[data-rows],[data-row],[data-row-decision],[data-section-approve],[data-release],[data-shout],[data-new],[data-code],[data-code-all],[data-code-less],[data-stats-toggle],#proj-switch,#console');
- if (!event.target.closest('.side')) fold(false);
- if (!t) return;
- if (t.id === 'proj-switch') { fold(!$('side').classList.contains('open')); return; }
- if (t.id === 'console') { t.hidden = true; return; }
- if (t.tagName === 'A' && t.dataset.go?.startsWith('item:')) {
- if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
- event.preventDefault();
- }
- if (t.dataset.statsToggle !== undefined) {
- view.statsOpen = !view.statsOpen;
- render();
- $('proof-stats-summary').focus({ preventScroll: true });
- return;
- }
- if (t.dataset.status) { statusGo(t.dataset.status); return; }
- if (t.dataset.roadmapJump) { jumpToRoadmap(t.dataset.roadmapJump); return; }
- if (t.dataset.filterToggle !== undefined) { view.filterOpen = !view.filterOpen; render(); return; }
- if (t.dataset.filterChoice) {
- if (t.dataset.filterKind === 'state') view.state = t.dataset.filterValue;
- else view.lane = t.dataset.filterValue || null;
- view.filterOpen = false;
- render();
- $('filter-toggle').focus({ preventScroll: true });
- return;
- }
- if (t.dataset.itemsView) { view.itemsView = t.dataset.itemsView; view.addressDetail = null; address(); render(); return; }
- if ('roadmapKey' in t.dataset) {
- const key = t.dataset.roadmapKey;
- view.roadmapOpen.set(JSON.stringify([view.root, key]), t.getAttribute('aria-expanded') !== 'true');
- render();
- [...$('roadmap').querySelectorAll('[data-roadmap-key]')].find((head) => head.dataset.roadmapKey === key)?.focus({ preventScroll: true });
- return;
- }
- if ('roadmapAll' in t.dataset) { view.roadmapOnly = null; render(); return; }
- if (t.dataset.root) switchTo(t.dataset.root, t.dataset.go || '');
- else if (t.dataset.tab) { view.unread = null; view.roadmapOnly = null; openTab(t.dataset.tab); render(); }
- else if (t.dataset.go) go(t.dataset.go, t.dataset.board);
- else if (t.dataset.item) pick(Number(t.dataset.item));
- else if (t.dataset.state) { view.state = t.dataset.state; render(); }
- else if (t.dataset.rows) {
- const [kind, f] = t.dataset.rows.split(':');
- const addressed = view.addressDetail !== null;
- view.rows[kind] = f;
- view.addressDetail = null;
- render();
- if (addressed) { view.addressDetail = view.row[kind]; address(); }
- }
- else if (t.dataset.rowDecision) {
- const id = t.dataset.rowId, kind = t.dataset.rowKind;
- if (t.dataset.rowDecision === 'approve') decideRow(kind, 'spec-approve', { ids: id }, t);
- else askDecline(kind, id, t.closest('#' + kind + '-detail') ? 'detail' : 'list');
- }
- else if (t.dataset.sectionApprove) askApproveAll(t.dataset.sectionApprove);
- else if (t.dataset.shoutId && !event.target.closest('button,a,input,textarea,select')) { go('shout:' + t.dataset.shoutId); }
- else if (t.dataset.row) {
- const [kind, id] = t.dataset.row.split(':');
- view.row[kind] = id;
- view.addressDetail = id;
- address();
- render();
- $(kind + '-list').focus({ preventScroll: true });
- // Where the list and the detail stack, the picked row's detail, with its buttons, comes into view.
- if (matchMedia('(max-width: 900px)').matches) $(kind + '-detail').scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' });
- }
- else if (t.dataset.codeAll) showAllCode(t.dataset.codeAll, t.dataset.before || '');
- else if (t.dataset.codeLess) showLessCode(t.dataset.codeLess, t.dataset.before || '');
- else if (t.dataset.code) code(t.dataset.code, t.dataset.before || '');
- else if (t.dataset.release) act('release', { lane: t.dataset.release }, t);
- else if (t.dataset.shout) { answer(null); addressTo(t.dataset.shout); $('shout-text').value = '#' + t.dataset.about + ': '; openTab('shouts'); showTab(); $('shout-text').focus(); }
- else if (t.dataset.new !== undefined) { view.adding = true; render(); $('add-title').focus(); }
-});
-// The viewport's scroll is fired at the document; the tests' stand-in document has no window.
-document.addEventListener('scroll', updateRoadmapPanel, { passive: true });
-/** Close the expanded stats card and return focus to the list's summary control on Escape. */
-document.addEventListener('keydown', (event) => {
- if (event.key !== 'Escape' || !view.statsOpen || view.tab !== 'items' || document.querySelector('[data-pane="items"]')?.hidden) return;
- event.preventDefault();
- view.statsOpen = false;
- render();
- $('proof-stats-summary').focus({ preventScroll: true });
-});
-/** Let a Roadmap row with independent inline links keep its keyboard button behavior. */
-document.addEventListener('keydown', (event) => {
- if (!['Enter', ' '].includes(event.key)) return;
- const head = event.target.closest('.milestone-head');
- if (head && event.target === head) { event.preventDefault(); head.click(); return; }
- const row = event.target.closest('.milestone-item[role="button"]');
- if (event.target !== row) return;
- event.preventDefault();
- if (row.dataset.roadmapKey !== undefined) { row.click(); return; }
- go(row.dataset.go, row.dataset.board || view.root);
-});
-// In a focused Spec or Doctrine list the arrow keys move the pick, and A approves the picked row and D asks why it is
-// declined, as the detail's buttons do, wherever the detail offers that decision.
-for (const kind of ['spec', 'doctrine']) $(kind + '-list').addEventListener('keydown', (event) => {
- if (event.target !== event.currentTarget || event.metaKey || event.ctrlKey || event.altKey) return;
- const ids = [...event.currentTarget.querySelectorAll('[data-row]')].map((row) => row.dataset.row.slice(kind.length + 1));
- const at = ids.indexOf(view.row[kind]);
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
- event.preventDefault();
- const next = ids[Math.min(ids.length - 1, Math.max(0, at + (event.key === 'ArrowDown' ? 1 : -1)))];
- if (next && next !== view.row[kind]) { view.row[kind] = next; view.addressDetail = next; address(); render(); event.currentTarget.querySelector('.srow.on')?.scrollIntoView({ block: 'nearest' }); }
- } else if (event.key === 'Enter' && view.row[kind]) {
- event.preventDefault();
- $(kind + '-detail').scrollIntoView({ block: 'start', behavior: 'instant' });
- } else if ((event.key === 'a' || event.key === 'd') && view.row[kind] && $(kind + '-detail').querySelector('.approve-row')) {
- // Only a row still waiting on the person has a decision to make; the detail shows it.
- event.preventDefault();
- if (event.key === 'a') decideRow(kind, 'spec-approve', { ids: view.row[kind] }, event.currentTarget);
- else askDecline(kind, view.row[kind], 'list');
- }
-});
-// The form covers the picked item rather than dropping it, so Cancel brings it back.
-$('new-item').addEventListener('click', () => { view.adding = true; render(); $('add-title').focus(); });
-$('upgrade-note').addEventListener('click', (event) => {
- if (!event.target.closest('[data-upgrade-dismiss]')) return;
- const notice = releaseNotices.get(data.project?.root);
- if (notice) notice.releases = [];
- renderReleaseNotes(data.project);
-});
-$('add-cancel').addEventListener('click', () => { view.adding = false; render(); });
-$('spec-decline-cancel').addEventListener('click', () => { closeDecline(); });
-$('spec-decline-form').addEventListener('keydown', trapFocus);
-// The row the dialog named is declined, with its reason, on the board it was opened on and only there.
-$('spec-decline-form').addEventListener('submit', (event) => {
- event.preventDefault();
- const reason = $('spec-decline-reason').value.trim();
- if (!view.declining || !reason) return;
- const asked = closeDecline();
- if (asked.root !== view.root) return;
- const anchor = asked.from === 'detail' ? $(asked.kind + '-detail') : [...$(asked.kind + '-list').querySelectorAll('[data-row]')].find((row) => row.dataset.row === asked.kind + ':' + asked.id);
- decideRow(asked.kind, 'spec-decline', { ids: asked.id, reason }, anchor);
-});
-$('spec-approve-cancel').addEventListener('click', () => { closeApproveAll(); });
-$('spec-approve-form').addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); closeApproveAll(); } else trapFocus(event); });
-// The rows the confirmation named are the rows approved, on the board it was opened on and only there; the decision's
-// note beside them says what the board did.
-$('spec-approve-form').addEventListener('submit', (event) => {
- event.preventDefault();
- const asked = closeApproveAll(true);
- if (asked && asked.root === view.root) decideRow('spec', 'spec-approve', { ids: asked.ids.join(' ') });
-});
-$('answer-cancel').addEventListener('click', () => answer(null));
-$('flow-hide').addEventListener('click', () => showFlow(false));
-$('flow-show').addEventListener('click', () => showFlow(true));
-$('flow-panel').hidden = keep('pb.flow') === 'hidden';
-$('flow-show').hidden = !$('flow-panel').hidden;
-// Each press moves on one, from the system's theme to light, then dark, and back; this browser keeps it.
-$('side-toggle').addEventListener('click', () => {
- // A phone always shows the switcher, so there the logo is only the logo.
- if (!matchMedia('(width > 900px)').matches) return;
- const collapsed = !document.documentElement.dataset.side;
- collapseSide(collapsed);
- fold(false);
- keep('pb.side', collapsed ? 'collapsed' : 'open');
-});
-/** Pick the scheme the page does not show now, and keep it. */
-function flipTheme() {
- const next = document.documentElement.dataset.scheme === 'dark' ? 'light' : 'dark';
- keep('pb.theme', next);
- theme(next);
-}
-$('theme').addEventListener('click', flipTheme);
-$('ob-theme').addEventListener('click', flipTheme);
-$('q').addEventListener('input', () => { search(); view.foundAt = 0; showFound(); });
-// Leaving the field closes the results a moment later, so a press on a result lands first; coming back to the field
-// before then keeps them, or a search begun straight after Esc would lose its new results to the old close.
-let closingFound = 0;
-$('q').addEventListener('focus', () => { clearTimeout(closingFound); if ($('q').value.trim()) showFound(); });
-$('q').addEventListener('keydown', (event) => {
- if (event.key === 'Escape') { $('q').value = ''; search(); hideFound('escape'); $('q').blur(); return; }
- if (!view.found?.length || $('find-results').hidden) return;
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); view.foundAt = (view.foundAt + (event.key === 'ArrowDown' ? 1 : view.found.length - 1)) % view.found.length; showFound(); }
- else if (event.key === 'Enter') { event.preventDefault(); openFound(view.found[view.foundAt].go); }
-});
-// A press on a result opens it before the field loses focus and the results close.
-$('find-results').addEventListener('mousedown', (event) => { const hit = event.target.closest('[data-find]'); if (hit) { event.preventDefault(); openFound(hit.dataset.find); } });
-$('q').addEventListener('blur', () => {
- clearTimeout(closingFound);
- // Esc and opening a result already close explicitly; their blur must keep that reason.
- if ($('find-results').hidden) return;
- closingFound = setTimeout(() => hideFound('left the field'), 120);
-});
-// "/" goes to the search from anywhere but a field.
-document.addEventListener('keydown', (event) => {
- if (!view.filterOpen) return;
- if (event.key === 'Escape') {
- event.preventDefault();
- view.filterOpen = false;
- render();
- $('filter-toggle').focus({ preventScroll: true });
- return;
- }
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
- const choices = [...$('filter-menu').querySelectorAll('[data-filter-choice]')];
- const at = choices.indexOf(document.activeElement);
- if (choices.length) {
- event.preventDefault();
- const next = at < 0 ? (event.key === 'ArrowDown' ? 0 : choices.length - 1) : (at + (event.key === 'ArrowDown' ? 1 : choices.length - 1)) % choices.length;
- choices[next].focus({ preventScroll: true });
- }
- }
-});
-document.addEventListener('keydown', (event) => {
- if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || event.target.closest('input, textarea, select, [contenteditable]')) return;
- event.preventDefault();
- $('q').focus();
- $('q').select();
-});
-$('add-form').addEventListener('submit', async (event) => {
- event.preventDefault();
- const root = view.root;
- const submitted = { lane: $('add-lane').value, title: $('add-title').value, criterion: $('add-criterion').value, specs: $('add-specs').value, brief: $('add-brief').value };
- if (await act('add', submitted, event.currentTarget) && view.root === root
- && $('add-lane').value === submitted.lane && $('add-title').value === submitted.title
- && $('add-criterion').value === submitted.criterion && $('add-specs').value === submitted.specs
- && $('add-brief').value === submitted.brief) {
- $('add-title').value = '';
- $('add-criterion').value = '';
- $('add-specs').value = '';
- $('add-brief').value = '';
- }
-});
-$('shout-form').addEventListener('submit', async (event) => {
- event.preventDefault();
- const text = $('shout-text').value;
- const root = view.root;
- const ask = view.answering;
- const answerRoot = ask?.root ?? null;
- const answerId = ask?.id ?? null;
- if (ask && ask.root !== view.root) return answer(null);
- if (!(await (ask ? act('answer', { id: ask.id, text }, event.currentTarget) : ($('shout-to').value === 'coordinator' ? act('request', { text }, event.currentTarget) : act('shout', { to: $('shout-to').value, text }, event.currentTarget))))) return;
- const currentAnswer = view.answering;
- // An older completion must not erase a newer draft or answer selection.
- if (view.root !== root || $('shout-text').value !== text || (currentAnswer?.root ?? null) !== answerRoot
- || (currentAnswer?.id ?? null) !== answerId) return;
- $('shout-text').value = '';
- answer(null);
-});
-$('hold-form').addEventListener('submit', async (event) => {
- event.preventDefault();
- const root = view.root;
- const submitted = { lane: $('hold-lane').value, reason: $('hold-reason').value };
- if (await act('hold', submitted, event.currentTarget) && view.root === root
- && $('hold-lane').value === submitted.lane && $('hold-reason').value === submitted.reason) $('hold-reason').value = '';
-});
-// The first entry keeps the tab it opened on; Back and Forward show what each entry names.
-address(false);
-globalThis.addEventListener?.('popstate', fromAddress);
-showTab();
-if (snapshot) {
- $('replay-play').addEventListener('click', playReplay);
- $('replay-pause').addEventListener('click', pauseReplay);
- $('replay-speed').addEventListener('change', () => {
- if (snapshotReplay.playing) { clearTimeout(snapshotReplay.timer); snapshotReplay.timer = setTimeout(advanceReplay, 1000 / Number($('replay-speed').value)); }
- });
-}
-/** Copy a screen's command or sentence; a browser without the clipboard API copies from a selected field. */
-async function copyWords(text) {
- try { await navigator.clipboard.writeText(text); return true; }
- catch { /* Older and embedded browsers refuse the clipboard API: copy from a selected field below. */ }
- const field = document.createElement('textarea');
- field.value = text;
- field.setAttribute('readonly', '');
- field.style.position = 'fixed';
- field.style.opacity = '0';
- document.body.append(field);
- field.select();
- const copied = document.execCommand('copy');
- field.remove();
- return copied;
-}
-$('local-note').addEventListener('click', async (event) => {
- const button = event.target instanceof Element ? event.target.closest('button[data-copy]') : null;
- if (!button || !button.dataset.copy) return;
- button.textContent = await copyWords(button.dataset.copy) ? 'Copied' : 'Select and copy';
-});
-/**
- * Look for this machine's view again, by itself, while a screen waits on it or a signed-in person waits for a board:
- * the moment the view answers, the page opens the board, with no Try again (#764). Over a relay stream, a reload
- * starts both sources together.
- */
-let relisting = false;
-function lookAgain() {
- // This computer's view answered, then a read failed, as a busy view's can: read again every two seconds, so the
- // board shows the moment a list arrives (hostedListed clears the problem), never only on the slower fallback timer.
- if (hosted.local && localReached && !document.hidden && $('local-note').dataset.state === 'problem') {
- if (!relisting) { relisting = true; refresh().catch(() => {}).finally(() => { relisting = false; }); }
- return;
- }
- if (!hosted.local || relayPairing || localReached || localProblem || document.hidden) return;
- if (![...LOCAL_STATES, 'no-linked', 'unpaired'].includes($('local-note').dataset.state || '') || $('local-note').dataset.state === 'looking') return;
- connectLocal(true).then((local) => {
- if (local !== 'local') return;
- if (transport) { location.reload(); return; }
- transportModule = null;
- return refresh();
- }).catch((error) => localNote('problem', { detail: error.message }));
-}
-if (hosted.local && !snapshot) setInterval(lookAgain, 2000);
-
-/** Open a newly approved board's Items view after its real list entry arrives. */
-async function openApprovedBoard(boardId) {
- await refresh();
- const board = data?.projects.find(entry => entry.id === boardId && entry.ok);
- if (!board) throw new Error('The approved board did not load. Refresh the board list and try again.');
- view.tab = 'items';
- keep('pb.tab', view.tab);
- return switchTo(board.root);
-}
-
-/** Load the configured decrypting transport once, only when relay reads or pairing need it. */
-let transportLoading = null;
-async function loadTransport() {
- if (transport) return transport;
- if (!transportLoading) transportLoading = (async () => {
- const module = await pageStartup(document.documentElement).within(() => import(configuredTransportModule), 15_000, 'The relay client did not load within 15 seconds.');
- if (typeof module.createTransport !== 'function') throw new Error('The browser transport must export createTransport({ onUpdate }).');
- const configured = await module.createTransport({
- onUpdate: () => transport ? refresh().catch((error) => { $('live').textContent = 'offline: ' + error.message; }) : Promise.resolve(),
- onOpenBoard: openApprovedBoard, waitForRender: true, // A phone's transport keeps its shell until didRender (#899).
- });
- if (!configured || typeof configured.request !== 'function') throw new Error('The browser transport must provide request(path, body).');
- transportModule = configuredTransportModule;
- transport = configured;
- return transport;
- })();
- try { return await transportLoading; }
- catch (error) { transportLoadError = error; pageStartup(document.documentElement).say(error.message + ' Check your connection, then reload this page.'); throw error; }
- finally { transportLoading = null; }
-}
-
-/** Read local boards first; relay-only pages and pairing still load their configured client directly. */
-async function startPage() {
- let local = 'unreachable';
- if (hosted.local && !relayPairing) {
- if (localProblem) localNote('problem', { detail: localProblem });
- else local = await connectLocal();
- if (local === 'away') return;
- if (local === 'unreachable' && !hosted.relaySession) { hideRelayNotice(); return; }
- }
- if (hosted.local && local === 'local') transportModule = null;
- else if (configuredTransportModule) {
- // Signed out, a pairing link waits for sign-in, which its own state asks for.
- try { await loadTransport(); } catch (error) { if (!hosted.local || hosted.relaySession) throw error; localNote('signed-out'); return; }
- }
- await refresh();
-}
-startPage().catch((error) => {
- document.body.classList.remove('loading');
- $('live').textContent = 'cannot reach the view: ' + error.message;
- // Finding your boards never stays on a page that has stopped looking.
- if (hosted.local && $('local-note').dataset.state === 'looking') localNote('problem', { detail: 'Pullboard on this computer did not answer: ' + error.message });
-});
-// The relay transport keeps its own stream and timer. The local view reads on a timer only while it has no live
-// stream, and its live line says so (#545). Each timer asks which the page uses as it fires: the hosted page starts
-// out on the relay and turns to this machine's view once it reaches it (#513).
-if (!snapshot) setInterval(() => { if (!document.hidden && (transport || (hosted.local && hosted.relaySession && configuredTransportModule))) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, 3000);
-if (!snapshot) setInterval(() => { if (!document.hidden && !transport && !(hosted.local && hosted.relaySession && configuredTransportModule) && !connected()) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, FALLBACK_MS);
-setInterval(tickAges, 60000);
-</script>
+${pageScriptPart4(pageScope)}</script>
</body>
</html>`;
}
diff --git a/src/view/page-script-1.js b/src/view/page-script-1.js
new file mode 100644
index 00000000..d6683008
--- /dev/null
+++ b/src/view/page-script-1.js
@@ -0,0 +1,115 @@
+/**
+ * Part 1 of the hosted page's script, verbatim from src/cockpit.js lines 227-330 (#745): its
+ * text is what the page served before the split, with the values its ${} expressions read passed in as scope.
+ *
+ * @param {Record<string, any>} scope - The values cockpitPage passes for the names this part interpolates.
+ * @returns {string} The script text of this part.
+ */
+export function pageScriptPart1(scope) {
+ const { connection, hostedOptions, moduleOption, pageStartup, paths, readOnly, requestMode, snapshot, tabValue } = scope;
+return `const snapshot = ${JSON.stringify(snapshot)};
+let readOnly = ${JSON.stringify(readOnly)};
+let requests = ${JSON.stringify(requestMode)};
+const pageReadOnly = ${JSON.stringify(readOnly)};
+const pageRequests = ${JSON.stringify(requestMode)};
+const relayRequestsEnabled = requests;
+const configuredTransportModule = ${moduleOption};
+let transportModule = configuredTransportModule;
+const connection = ${connection};
+let transport = null;
+let transportLoadError = null;
+// Hosted pages can read two independent authorities at once. Local boards use the view's API; relay boards
+// retain the relay client's device-only decryption and event stream. The board id, never a mutable global mode,
+// selects the authority for each request.
+const boardSources = new Map();
+const localBoardIds = new Set();
+let localReadBase = connection.base;
+let localReadHeaders = { ...connection.headers };
+// The hosted page (N26, #513): at https://app.pullboard.dev, on the machine that runs pullboard view, the page reads
+// that view straight instead of the relay. The view hands it the session's secret by a round trip that ends back here
+// with the secret in the address's fragment, which no request carries; the page takes it out of the address before
+// anything else reads the address, and keeps it for this tab only. Every request then sends it in x-pullboard-key.
+const hosted = ${hostedOptions};
+const LOCAL_VIEW = 'http://127.0.0.1:4890';
+const LOCAL_TAB = 'pullboard.local.session';
+const LOCAL_TRIPS = 'pullboard.local.trips';
+let localSession = null;
+let localProblem = null;
+let localConfirmed = false;
+const tabValue = (${tabValue.toString()});
+/** Whether a value is a local session this page may use: version 1, a loopback origin with its port, and a secret. */
+function validLocalSession(value) {
+ if (!value || value.version !== 1 || typeof value.key !== 'string' || !/^[\\x21-\\x7e]{1,256}$/.test(value.key) || typeof value.origin !== 'string') return false;
+ try {
+ const address = new URL(value.origin);
+ return address.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(address.hostname) && address.port !== '' && address.origin === value.origin;
+ } catch { return false; }
+}
+const pageStartup = (${pageStartup.toString()});
+// A relay pairing link carries its own fragment; that load stays the relay's, as before.
+const relayPairing = hosted.local && ['board', 'key', 'device'].some((name) => new URLSearchParams(location.hash.slice(1)).has(name));
+if (hosted.local && !relayPairing) {
+ const fragment = new URLSearchParams(location.hash.slice(1));
+ const returned = fragment.get('pullboard-local');
+ if (returned !== null) {
+ fragment.delete('pullboard-local');
+ const rest = fragment.toString();
+ let removed = true;
+ try { history.replaceState(history.state, '', location.pathname + location.search + (rest ? '#' + rest : '')); }
+ catch { removed = false; }
+ let returnedSession = null;
+ try { returnedSession = JSON.parse(returned); } catch { /* refused below */ }
+ if (!removed) localProblem = 'This browser kept the connection secret in the address, so this page will not use it. Close this tab, then open your board below.';
+ else if (validLocalSession(returnedSession)) localSession = { version: 1, origin: returnedSession.origin, key: returnedSession.key };
+ else localProblem = 'Pullboard on this computer sent back a connection this page cannot read.';
+ } else {
+ try { const kept = JSON.parse(tabValue(LOCAL_TAB) ?? 'null'); if (validLocalSession(kept)) localSession = kept; } catch { /* nothing kept for this tab */ }
+ }
+ tabValue(LOCAL_TAB, localSession ? JSON.stringify(localSession) : null);
+}
+const snapshotReplay = { final: null, events: [], index: 0, playing: false, timer: null };
+const keep = (name, value) => { name = snapshot ? 'snapshot.' + name : name; try { if (value === undefined) return localStorage.getItem(name); localStorage.setItem(name, value); } catch { return null; } return value; };
+// Whether the host serves this page at /roadmap as well as at /, so the Roadmap's address is a path;
+// anywhere else it is a #roadmap fragment on the page's own address (N38).
+const routed = ${JSON.stringify(Boolean(paths) && !snapshot)};
+/** The tab the address names: the Roadmap at its own address, or null at the board's. */
+function addressTab() {
+ if (typeof location === 'undefined') return null;
+ if (snapshot) {
+ const tab = (location.hash || '').slice(1).split('/')[0] || '';
+ return ['items', 'shouts', 'spec', 'doctrine', 'activity', 'roadmap'].includes(tab) ? tab : null;
+ }
+ if (location.hash === '#items/pipeline') return 'items';
+ if (/^#items\\/\\d+$/.test(location.hash)) return 'items';
+ return (routed ? location.pathname === '/roadmap' : location.hash === '#roadmap') ? 'roadmap' : null;
+}
+/** Build an address for an item in the current app or an exported snapshot, preserving repo scope. */
+function itemAddress(id, root = view.root) {
+ if (snapshot) return location.pathname + location.search + '#items/' + encodeURIComponent(String(id));
+ const repo = data?.projects.find((entry) => entry.root === root);
+ const group = data?.groups.find((entry) => entry.key === root);
+ const name = repo?.name || group?.name;
+ const prefix = (data?.projects.filter((entry) => entry.ok).length || 0) > 1 && name ? '/' + encodeURIComponent(name) : '';
+ const path = prefix + '/items/' + encodeURIComponent(String(id));
+ return routed ? path + location.search : location.pathname + location.search + '#' + path.slice(1);
+}
+/** The tab the board's own address shows: the one last picked there, or Items. */
+function homeTab() {
+ const kept = keep('pb.tab');
+ return kept && kept !== 'roadmap' ? kept : 'items';
+}
+const view = { roadmapOpen: new Map(), root: keep('pb.project'), tab: addressTab() || homeTab(), itemsView: typeof location !== 'undefined' && location.hash === '#items/pipeline' ? 'pipeline' : 'list', filterOpen: false, seen: {}, code: {}, item: null, adding: false, declining: null, state: 'active', rows: { spec: 'decide', doctrine: 'all' }, row: { spec: null, doctrine: null }, agent: null, allAgents: false, agentsHidden: keep('pb.agents') === 'hidden', statsOpen: false, open: {}, addressDetail: null, shout: null, scrollPlace: false };
+let switchGeneration = 0;
+// Each board read in the order it started, and the newest one drawn: an answer older than that one is stale.
+let refreshStarted = 0;
+let refreshDrawn = { generation: 0, full: true };
+if (snapshot) view.state = 'all';
+let data = null;
+let seen = '';
+let addressReady = false;
+let heldClickPointer = null;
+let deferredClickRender = false; const pageDialogs = new Set(); // open page dialogs; the page holds its redraws while one is open
+// Detail replies stay with an unchanged summary, while search results are keyed by board and words.
+const itemDetails = new Map();
+`;
+}
diff --git a/src/view/page-script-2.js b/src/view/page-script-2.js
new file mode 100644
index 00000000..d83f70e8
--- /dev/null
+++ b/src/view/page-script-2.js
@@ -0,0 +1,978 @@
+/**
+ * Part 2 of the hosted page's script, verbatim from src/cockpit.js lines 332-1298 (#745): its
+ * text is what the page served before the split, with the values its ${} expressions read passed in as scope.
+ *
+ * @param {Record<string, any>} scope - The values cockpitPage passes for the names this part interpolates.
+ * @returns {string} The script text of this part.
+ */
+export function pageScriptPart2(scope) {
+ const { STAR_KEY, closePageDialog, connection, drawHosted, hostedBrowser, hostedReleaseDistance, hostedReleaseNote, hostedState, lifecycle, openPageDialog, personNeeds, releaseHosted, releaseInfo, roadmapBlock, roadmapHeaders, roadmapSummary, sharingPresentation, staleChip, transportModule } = scope;
+return `let detailRead = null;
+const addressedShouts = new Map();
+const $ = (id) => document.getElementById(id);
+// The update note from src/view/hosted-release.js (#632): only a confirmed read of this machine's view says how far behind it is.
+// Only the hosted page builds it; every other page draws nothing and never touches the DOM for it.
+const renderHostedReleaseNote = ${releaseHosted ? `(${hostedReleaseNote.toString()})(${releaseInfo}, { $, keep, distance: (${hostedReleaseDistance.toString()}),
+ // The selected board's own source decides (#632 review): a confirmed local board keeps its note on a mixed list that
+ // also reads relay boards, and a selected relay board never shows one; with no board selected, only an all-local page.
+ readable: () => {
+ if (!hosted.local || !localConfirmed || !localSession || connection.base !== localSession.origin) return false;
+ const board = data?.projects?.find((entry) => entry.root === view.root && entry.ok);
+ return board ? boardSources.get(board.id)?.kind === 'local' : !transportModule && !transport;
+ },
+ project: (project = data?.project) => project?.releaseNotes ? project : data?.projects?.find((entry) => entry.ok && entry.releaseNotes) })` : '() => {}'};
+
+const hostedState = (${hostedState.toString()});
+const hostedBrowser = (${hostedBrowser.toString()});
+const drawHosted = (${drawHosted.toString()});
+/**
+ * Show the open-board screen the page is in (src/view/hosted.js), or none with null. A phone is the one the relay's
+ * page names before first paint (#757), and it hears nothing about this computer.
+ */
+function localNote(state, facts = {}) {
+ drawHosted(document, hostedState(state, { browser: hostedBrowser(navigator), phone: document.documentElement.dataset.relayDevice === 'phone', ...facts }), { view: localSession?.origin || LOCAL_VIEW, signIn: hosted.signIn, session: hosted.relaySession });
+}
+
+let starLinked = { at: 0, linked: false, reading: false };
+/**
+ * Show the hosted page's star line (src/view/star.js) to a signed-in person whose account lists a linked board, until
+ * dismissed here; pass a board list through. Why the account's list: it is the linked-board metadata the relay serves
+ * this page, whichever source then draws a board, so a linked board this machine reads locally still counts, and no
+ * relay client loads to decide it. It is read until it lists one, at most every few seconds, and
+ * declares the relay's engine as every relay request does.
+ */
+function starLine(list) {
+ const line = $('star-line');
+ if (!line) return list;
+ const show = () => { line.hidden = !(hosted.relaySession && starLinked.linked && keep(${JSON.stringify(STAR_KEY)}) !== 'dismissed'); };
+ const learn = (reply) => {
+ const linked = Boolean(reply?.boards?.some((board) => typeof board?.id === 'string'));
+ starLinked = { at: Date.now(), linked, reading: false };
+ line.dataset.linked = linked ? 'yes' : 'no';
+ show();
+ };
+ if (hosted.relaySession && !starLinked.linked && !starLinked.reading) {
+ // The page's own read of the account, when it made one since the line last looked, answers the line, refused
+ // or not: the line reads the account itself only when the page made no such read, so a listing never brings a
+ // second one (#817).
+ if (linkedSeen && linkedSeen.at > starLinked.at) learn(linkedSeen.reply);
+ else if (Date.now() - starLinked.at > 2500) {
+ starLinked = { at: Date.now(), linked: false, reading: true };
+ linkedList().then(learn, () => learn(null));
+ }
+ }
+ show();
+ return list;
+}
+$('star-dismiss')?.addEventListener('click', () => { keep(${JSON.stringify(STAR_KEY)}, 'dismissed'); starLine(null); });
+// No first look of its own (#817): every signed-in page lists its boards, and api() hands that list here, so the
+// account is read only after a listing succeeds, never beside it. A session that its first listing revokes therefore
+// sees exactly one listing, and the line, hidden in its markup, stays hidden until a listing shows it.
+
+/** Hide the relay's own banner, which speaks for the relay, on a page the relay does not serve this time. */
+function hideRelayNotice() {
+ const banner = document.getElementById('relay-notice');
+ if (banner) banner.hidden = true;
+}
+
+/** Send this tab on the round trip to the local view, which sends it straight back here; two tries in a row at most. */
+function localTrip(base) {
+ const trips = Number(tabValue(LOCAL_TRIPS) || 0);
+ if (trips >= 2) {
+ tabValue(LOCAL_TRIPS, null);
+ localNote('problem', { detail: 'Pullboard on this computer did not give this page a session it accepts.' });
+ return false;
+ }
+ tabValue(LOCAL_TRIPS, String(trips + 1));
+ location.assign(base + '/local/connect');
+ return true;
+}
+
+/** The local view refused this tab's secret, as after a restart with a new one: go round again for it, unasked. */
+function localExpired() {
+ const base = localSession.origin;
+ localSession = null;
+ localConfirmed = false;
+ tabValue(LOCAL_TAB, null);
+ localTrip(base);
+}
+
+// The screens that wait on this computer: the page looks again by itself while one shows, with no Try again (#764).
+const LOCAL_STATES = ['looking', 'asking', 'blocked', 'not-running', 'mismatch'];
+let localChecking = false;
+let localReached = false;
+
+/**
+ * Reach this machine's view: read the view's public protocol, which holds no secret and no board, and take the session
+ * the round trip brought back. While the browser asks the person, which it does before the request goes anywhere, the
+ * page draws the prompt and says it waits. It is 'local' when the page now reads the local view, 'away' when the
+ * browser is on the round trip, 'unreachable' when the page cannot read it, with the screen that says why, and 'busy'
+ * while another look is still on its way. A look again by itself (again) redraws only a screen that waits on this
+ * computer, so a later screen, such as signing in, stays.
+ */
+async function connectLocal(again = false) {
+ // A phone never runs Pullboard: it is unreachable at once, before a permission query or a fetch can wait (#900).
+ if (pageStartup(document.documentElement).phone) return 'unreachable';
+ if (localChecking) return 'busy';
+ localChecking = true;
+ try { return await lookLocal(again); }
+ finally { localChecking = false; }
+}
+
+/** One look for this machine's view, for connectLocal, which keeps two from running at once. */
+async function lookLocal(again) {
+ const base = localSession?.origin || LOCAL_VIEW;
+ /** Draw this screen, unless the page has moved past the ones that wait on this computer. */
+ const show = (state) => {
+ const shown = $('local-note').dataset.state || '';
+ if (shown !== state && (!again || LOCAL_STATES.includes(shown))) localNote(state);
+ };
+ let permission = null;
+ for (const name of ['loopback-network', 'local-network-access']) {
+ try { permission = (await navigator.permissions.query({ name })).state; break; } catch { /* this browser has no such permission */ }
+ }
+ if (permission === 'denied') {
+ show('blocked');
+ return 'unreachable';
+ }
+ // A browser that says it will ask gets Click Allow on screen before the request that raises its prompt; one that
+ // says nothing gets it only once the request is slow to come back, as it is while a prompt waits.
+ let slow = null;
+ if (permission === 'prompt' && !again) {
+ show('asking');
+ await new Promise((painted) => requestAnimationFrame(() => requestAnimationFrame(painted)));
+ } else if (permission !== 'granted' && !again) slow = setTimeout(() => show('asking'), 800);
+ let reply;
+ try {
+ for (let attempt = 1; !reply; attempt += 1) {
+ try { reply = await fetch(base + '/local/protocol', { signal: AbortSignal.timeout(3000), credentials: 'omit', redirect: 'error' }); }
+ catch (error) {
+ // A read that ran out of time may have met a slow first answer or a browser prompt still open, so it asks once
+ // more (#786). After that, one that ran out of time while the browser may still be asking is the prompt waiting
+ // for the person, and one refused at once means nothing runs here (#764). One discovery request at a time is all
+ // this page makes of this device (P5), so a view too old to answer it reads as none.
+ if (attempt < 2 && error?.name === 'TimeoutError') continue;
+ show(error?.name === 'TimeoutError' && permission !== 'granted' ? 'asking' : 'not-running');
+ return 'unreachable';
+ }
+ }
+ } finally { clearTimeout(slow); }
+ let protocol = null;
+ try { protocol = await reply.json(); } catch { /* not this protocol */ }
+ if (!reply.ok || protocol?.version !== 1 || protocol?.apiVersion !== 1 || protocol?.hostedOrigin !== location.origin) {
+ show('mismatch');
+ return 'unreachable';
+ }
+ if (!localSession) return localTrip(base) ? 'away' : 'unreachable';
+ connection.base = localSession.origin;
+ connection.headers = { 'x-pullboard-key': localSession.key };
+ localReadBase = connection.base;
+ localReadHeaders = { ...connection.headers };
+ readOnly = false;
+ requests = false;
+ localReached = true;
+ document.body.classList.remove('read-only', 'requests');
+ hideRelayNotice();
+ // Finding your boards stays until the list arrives, so the page never shows an empty board on its way to one.
+ if (LOCAL_STATES.includes($('local-note').dataset.state || '')) localNote('looking');
+ return 'local';
+}
+
+/** Mark primary pointer targets whose click would be lost if a refresh replaces them. */
+function holdClickPointer(event) {
+ if (!event.isPrimary || event.button !== 0 || !(event.target instanceof Element && event.target.closest('#pipeline .pipeline-item, #spec-detail [data-row-decision="decline"], #spec-decline-submit, #roadmap-panel [data-roadmap-jump]'))) return;
+ heldClickPointer = event.pointerId;
+}
+
+/** Flush a deferred refresh only after the browser has had the chance to dispatch the resulting click. */
+function releaseClickPointer(event) {
+ if (event.pointerId !== heldClickPointer) return;
+ heldClickPointer = null;
+ if (deferredClickRender) requestAnimationFrame(() => {
+ if (heldClickPointer === null && deferredClickRender) {
+ deferredClickRender = false;
+ render();
+ }
+ });
+}
+
+document.addEventListener('pointerdown', holdClickPointer, true);
+document.addEventListener('pointerup', releaseClickPointer, true);
+document.addEventListener('pointercancel', releaseClickPointer, true);
+/**
+ * Draw the page in the theme the person picked, light or dark; with none picked it follows the system, live. The button
+ * only ever offers the other of the two: it shows the scheme on screen, and a press picks the opposite. Following the
+ * system again waits for a settings page. The tokens hold both values, so only the scheme they answer to changes.
+ */
+function theme(pick) {
+ if (pick === 'light' || pick === 'dark') document.documentElement.dataset.theme = pick;
+ else delete document.documentElement.dataset.theme;
+ const now = document.documentElement.dataset.theme || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
+ document.documentElement.dataset.scheme = now;
+ // The open-board screens carry the same toggle in their own header (#764), as the sidebar is hidden there.
+ for (const button of [$('theme'), $('ob-theme')]) {
+ button.title = now === 'dark' ? 'Dark theme: switch to light' : 'Light theme: switch to dark';
+ button.setAttribute('aria-label', button.title);
+ }
+}
+theme(keep('pb.theme'));
+matchMedia('(prefers-color-scheme: dark)').addEventListener?.('change', () => theme(keep('pb.theme')));
+/** Collapse the sidebar into the tab bar on a wide screen, or bring it back, as the person last chose. */
+function collapseSide(collapsed) {
+ if (collapsed) document.documentElement.dataset.side = 'collapsed';
+ else delete document.documentElement.dataset.side;
+ $('side-toggle').setAttribute('aria-pressed', String(collapsed));
+ $('side-toggle').title = collapsed ? 'Show the project list' : 'Collapse the project list';
+ $('side-toggle').setAttribute('aria-label', $('side-toggle').title);
+}
+collapseSide(keep('pb.side') === 'collapsed');
+const esc = (text) => String(text ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+// Inline code: a short chip stays whole on its line; one wider than a phone line's worth may wrap. Width
+// is in columns, as a terminal counts them: CJK, full-width and emoji characters take two.
+const wideChar = (c) => { const p = c.codePointAt(0); return (p >= 0x1100 && p <= 0x115f) || (p >= 0x2e80 && p <= 0xa4cf) || (p >= 0xac00 && p <= 0xd7a3) || (p >= 0xf900 && p <= 0xfaff) || (p >= 0xfe30 && p <= 0xfe4f) || (p >= 0xff00 && p <= 0xff60) || (p >= 0xffe0 && p <= 0xffe6) || (p >= 0x1f300 && p <= 0x1faff) || (p >= 0x20000 && p <= 0x3fffd); };
+const columns = (text) => [...String(text)].reduce((n, c) => n + (wideChar(c) ? 2 : 1), 0);
+const codeChip = (text, kind = '') => kind === 'sha' && String(text).length > 10
+ ? '<code class="inline sha" title="' + esc(text) + '">' + esc(String(text).slice(0, 10)) + '</code>'
+ : '<code class="inline' + (kind ? ' ' + kind : '') + (columns(text) > 24 ? ' long" title="' + esc(text) : '') + '">' + esc(text) + '</code>';
+// An age said in words, as a shout's card shows it: now, 2m ago, 1h ago.
+const agoLong = (iso) => { const short = ago(iso); return short === 'now' ? 'now' : short + ' ago'; };
+const ago = (iso) => { const m = Math.round((Date.now() - Date.parse(iso)) / 60000); return m < 1 ? 'now' : m < 60 ? m + 'm' : m < 2880 ? Math.round(m / 60) + 'h' : Math.round(m / 1440) + 'd'; };
+// An age as the page shows it: the moment it counts from stays on it, so tickAges can move it on.
+const age = (iso) => '<time data-ago="' + esc(iso) + '">' + ago(iso) + '</time>';
+const clock = (iso) => new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
+const when = (iso) => (new Date(iso).toDateString() === new Date().toDateString() ? '' : new Date(iso).toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ') + clock(iso);
+// A day as a feed names it: Today, Yesterday, or its weekday and date.
+const dayName = (iso) => {
+ const then = new Date(iso).toDateString(), today = new Date();
+ if (then === today.toDateString()) return 'Today';
+ today.setDate(today.getDate() - 1);
+ return then === today.toDateString() ? 'Yesterday' : new Date(iso).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' });
+};
+// When the page last named days, so tickDays can rename them in place once the clock passes midnight (#644).
+let daysNamedAt = new Date();
+// A feed's rows, newest first, with the day named above each run of rows from the same day.
+const byDay = (rows, at, row) => { daysNamedAt = new Date(); return rows.map((x, i) => (i && new Date(at(x)).toDateString() === new Date(at(rows[i - 1])).toDateString() ? '' : '<h4 class="day">' + dayName(at(x)) + '</h4>') + row(x)).join(''); };
+// Where the shouts cross into an earlier day, a rule names it in the middle; today needs no label at the top.
+const dayRules = (rows, at, row) => { daysNamedAt = new Date(); return rows.map((x, i) => {
+ const day = new Date(at(x)).toDateString(), before = i ? new Date(at(rows[i - 1])).toDateString() : new Date().toDateString();
+ return (day === before ? '' : '<div class="day-rule" role="separator"><span>' + dayName(at(x)) + '</span></div>') + row(x);
+}).join(''); };
+const firstLine = (text) => String(text ?? '').split('\\n').map((line) => line.trim()).find(Boolean) || '';
+/** Omit a duplicated leading verdict code from rendered copy while preserving the recorded note. */
+function visibleVerdictNote(reason, note) {
+ const text = String(note ?? '');
+ const code = String(reason ?? '');
+ const remainder = text.slice(code.length);
+ return code && text.startsWith(code) && (!remainder || /^\\s/u.test(remainder)) ? remainder.trimStart() : text;
+}
+// The latest verdict is a reject and no accept followed: open again, being reworked, resubmitted, or
+// withdrawn after it.
+const rejected = (i) => i.status !== 'verified' && !!i.verdict && i.verdict.decision === 'REJECT';
+/** Resolve visible agent text from this board's API without changing action identities. */
+function agentName(id, project = data?.project) {
+ const agent = project?.agents?.find((entry) => entry.agent_id === id);
+ return agent?.displayName || (agent ? id + ' (' + (agent.model || agent.agent_model || 'unknown') + ')' : id);
+}
+/** Keep a shout address whole while its model can shorten, retaining the API name for assistive readers. */
+function shoutAgentName(id) {
+ const name = agentName(id);
+ if (name === id) return esc(id);
+ const prefix = name.endsWith('-' + id);
+ const model = prefix ? name.slice(0, -id.length) : name.slice(id.length);
+ const address = '<span class="agent-id">' + esc(id) + '</span>';
+ const label = '<span class="agent-model">' + esc(model) + '</span>';
+ return '<span class="agent-label' + (prefix ? ' prefix' : '') + '" title="' + esc(name) + '" role="group" aria-label="' + esc(name) + '">' + (prefix ? label + address : address + label) + '</span>';
+}
+/** Render a review note with escaped text and references bound to the selected board. */
+const verdictHtml = (v, titles) => '<div class="verdict ' + (v.decision === 'ACCEPT' ? 'yes' : 'no') + '"><b>' + esc(v.decision) + ' ' + esc(v.reason) + '</b><span class="by">' + esc(agentName(v.by)) + ' · ' + when(v.at) + ' · at ' + esc(String(v.commit || '').slice(0, 12)) + '</span><div class="note">' + inline(visibleVerdictNote(v.reason, v.note), titles) + '</div></div>';
+const roadmapSummary = (${roadmapSummary.toString()}), roadmapHeaders = (${roadmapHeaders.toString()});
+const stateOf = (i) => i.status === 'claimed' ? 'building' : i.status === 'submitted' ? 'verify' : i.status === 'verified' ? 'verified' : i.status === 'withdrawn' ? 'withdrawn' : i.verdict && i.verdict.decision === 'REJECT' ? 'back' : 'open';
+const STATES = { building: ['building', 'busy'], verify: ['to verify', 'warn'], back: ['sent back', 'no'], verified: ['verified', 'ok'], open: ['unclaimed', 'free'], withdrawn: ['withdrawn', ''] };
+const chip = (s) => '<span class="chip ' + STATES[s][1] + '">' + STATES[s][0] + '</span>';
+// A verified item's stale mark from src/view/stale.js (#726): Core publishes verdictState and the page only draws it.
+const staleChip = (${staleChip.toString()});
+// A roadmap item's blocker dot and unfolded reason from src/view/roadmap-block.js (#605), read from the summaries held.
+const roadmapBlock = (${roadmapBlock.toString()});
+const openPageDialog = (${openPageDialog.toString()}), closePageDialog = (${closePageDialog.toString()});
+/** Parse the bounded reference syntax before requesting additional committed line windows. */
+function codeReferenceParts(ref) {
+ const match = /^(.+):(\\d+)(?:-(\\d+))?@([0-9a-f]{7,40})$/.exec(String(ref));
+ if (!match) return null;
+ const from = Number(match[2]);
+ const to = Number(match[3] ?? match[2]);
+ return Number.isSafeInteger(from) && Number.isSafeInteger(to) && from > 0 && to >= from
+ ? { path: match[1], from, to, commit: match[4] } : null;
+}
+/**
+ * Escape and color a source line using a small language-neutral set of common code tokens. A block comment or a
+ * template string still open at the line's end is left in state.open, and the next line given the same state goes on
+ * inside it, so a comment or a string spanning lines is colored on every one of them.
+ */
+function highlightCodeLine(line, path, state = {}) {
+ const source = String(line);
+ const extension = String(path).split('.').at(-1).toLowerCase();
+ let output = '', i = 0;
+ if (state.open) {
+ let end = -1;
+ if (state.open === 'comment') { const at = source.indexOf('*/'); end = at < 0 ? -1 : at + 2; }
+ else for (let k = 0; k < source.length; k++) { if (source.charCodeAt(k) === 92) { k++; continue; } if (source.charCodeAt(k) === 96) { end = k + 1; break; } }
+ const kind = state.open === 'comment' ? 'tok-comment' : 'tok-string';
+ if (end < 0) return '<span class="' + kind + '">' + esc(source) + '</span>';
+ output = '<span class="' + kind + '">' + esc(source.slice(0, end)) + '</span>';
+ i = end;
+ state.open = null;
+ } else {
+ // A preview may start inside a block comment, so a line that reads as one is all comment, and so is a whole-line
+ // hash comment where the language has them: their apostrophes are words, not strings.
+ const lead = source.trimStart();
+ if (/^(?:\\*\\/|\\*(?:\\s|$))/.test(lead) || (['py', 'sh', 'yml', 'yaml', 'rb', 'toml'].includes(extension) && lead.startsWith('#'))) return '<span class="tok-comment">' + esc(source) + '</span>';
+ }
+ const keywords = new Set(['const', 'let', 'var', 'function', 'return', 'if', 'else', 'new', 'class', 'export', 'import', 'from', 'async', 'await', 'throw', 'try', 'catch', 'true', 'false', 'null', 'undefined']);
+ while (i < source.length) {
+ if (source.startsWith('//', i) || (extension === 'py' && source[i] === '#')) {
+ output += '<span class="tok-comment">' + esc(source.slice(i)) + '</span>';
+ break;
+ }
+ if (source.startsWith('/*', i)) {
+ const at = source.indexOf('*/', i + 2), end = at < 0 ? source.length : at + 2;
+ output += '<span class="tok-comment">' + esc(source.slice(i, end)) + '</span>';
+ if (at < 0) state.open = 'comment';
+ i = end;
+ continue;
+ }
+ const char = source[i];
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
+ let end = i + 1, closed = false;
+ while (end < source.length) {
+ if (source.charCodeAt(end) === 92) { end += 2; continue; }
+ if (source[end++] === char) { closed = true; break; }
+ }
+ if (!closed && char.charCodeAt(0) === 96) state.open = 'template';
+ output += '<span class="tok-string">' + esc(source.slice(i, end)) + '</span>';
+ i = end;
+ continue;
+ }
+ const wordStart = (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z') || char === '_' || char === '$';
+ if (wordStart) {
+ let end = i + 1;
+ while (end < source.length && ((source[end] >= 'A' && source[end] <= 'Z') || (source[end] >= 'a' && source[end] <= 'z') || (source[end] >= '0' && source[end] <= '9') || source[end] === '_' || source[end] === '$')) end++;
+ const word = source.slice(i, end);
+ output += keywords.has(word) ? '<span class="tok-keyword">' + esc(word) + '</span>' : esc(word);
+ i = end;
+ continue;
+ }
+ if (char >= '0' && char <= '9') {
+ let end = i + 1;
+ while (end < source.length && ((source[end] >= '0' && source[end] <= '9') || source[end] === '.')) end++;
+ output += '<span class="tok-number">' + esc(source.slice(i, end)) + '</span>';
+ i = end;
+ continue;
+ }
+ output += esc(char);
+ i++;
+ }
+ return output;
+}
+// A shout or thread fact's path:lines@commit reference: keep only the reference in this button until
+// the person opens it. The text before a shout ref is retained so ambiguous paths can be refused.
+const codeRef = (ref, before, block = false) => {
+ const c = view.code[view.root + '\\n' + before + '\\n' + ref];
+ const open = Boolean(c && c.open);
+ const shownLines = c?.all ? c.allLines : c?.lines, carry = {};
+ const shown = !open ? '' : c.error ? '<span class="code no" role="status">' + esc(c.error) + '</span>' : !shownLines ? '<span class="code more">loading…</span>'
+ : '<div class="code-wrap"><pre class="code">' + shownLines.map((line, n) => '<span><i>' + (c.from + n) + '</i>' + highlightCodeLine(line, c.path, carry) + '</span>').join('') + '</pre>'
+ + (c.more && !c.all ? '<button class="code-control" data-code-all="' + esc(ref) + '"' + (before ? ' data-before="' + esc(before) + '"' : '') + ' type="button"' + (c.allLoading ? ' disabled' : '') + '>' + (c.allLoading ? 'loading all lines…' : 'show all lines') + '</button>' : '')
+ + (c.all ? '<button class="code-control" data-code-less="' + esc(ref) + '"' + (before ? ' data-before="' + esc(before) + '"' : '') + ' type="button">show less</button>' : '')
+ + '</div>';
+ // Its label is one piece: the path, cut short first where the line is narrow, then the lines and the commit's first
+ // ten characters; the whole reference is on hover.
+ const colon = ref.indexOf(':'), at = ref.lastIndexOf('@');
+ const label = '<span class="ref-path">' + esc(ref.slice(0, colon)) + '</span><span class="ref-at">' + esc(ref.slice(colon, at)) + '<span class="ref-sha">' + esc(ref.slice(at, at + 11)) + '</span></span>';
+ const button = (asBlock) => '<button class="ref' + (asBlock ? ' block' : '') + '" data-code="' + esc(ref) + '"' + (before ? ' data-before="' + esc(before) + '"' : '') + ' title="' + esc(ref) + '" aria-label="Open code reference ' + esc(ref) + '" type="button" aria-expanded="' + open + '">' + label + '</button>';
+ // A reference on a line of its own is a block, collapsed until asked: a caret, the path and lines, the short commit.
+ // One inside a sentence keeps its label, so the prose reads on, and opens that same block below it.
+ return block ? '<div class="code-ref' + (open ? ' open' : '') + '">' + button(true) + shown + '</div>'
+ : button(false) + (open ? '<div class="code-ref open">' + button(true) + shown + '</div>' : '');
+};
+/** Format the API's structured fact binding as the live reference the code preview accepts. */
+function factCodeRef(ref) {
+ if (!ref || typeof ref !== 'object') return String(ref ?? '');
+ const lines = ref.start === ref.end ? String(ref.start) : ref.start + '-' + ref.end;
+ return ref.path + ':' + lines + '@' + ref.commit;
+}
+const tone = (s) => s === 'approved' ? 'ok' : s === 'pending' ? 'no' : s === 'draft' ? 'warn' : '';
+/** Name a rule's actual packaged version or its repository source, including explicit overrides. */
+const ruleSource = (row) => row.standardVersion != null ? 'Pullboard v' + row.standardVersion + (row.overrides ? row.status === 'wont' ? ', declined here' : ', overridden here' : '') : 'this repo';
+/** Keep the full source label available when a narrow row clips it. */
+const ruleSourceTitle = (row) => ruleSource(row);
+/** Render the two-line record shared by Items, Spec and Doctrine, with one grid and type hierarchy. */
+function recordRow({ tag = 'li', classes = '', attributes, title, state, primary, secondary, rightTop = '', rightBottom = '' }) {
+ return '<' + tag + ' class="' + (tag === 'div' ? 'srow ' : '') + 'row s-' + state + (classes ? ' ' + classes.trim() : '') + '" ' + attributes + ' title="' + esc(title) + '"><span class="dot ' + state + '"></span><div><div class="t srow-text">' + primary + '</div>' + (rightTop ? '<span class="row-age">' + rightTop + '</span>' : '') + '<div class="meta">' + secondary + '</div></div>' + rightBottom + '</' + tag + '>';
+}
+const count = (n, one, many = one) => n + ' ' + (n === 1 ? one : many);
+// What needs the person in a project, as its Needs-you list counts it: only the person's calls (B26),
+// the decisions passed up to them, spec rows waiting for them, and held lanes, which only the main
+// checkout, the person's seat, can set. Work waiting for a verdict or sent back belongs to the agents,
+// and the line under the project says so without counting it.
+const needCount = (x) => x.ok && !x.loading ? x.decisions + x.pending + x.drafts + x.holds : 0;
+const doing = (x) => [x.decisions && count(x.decisions, 'decision', 'decisions'), x.pending && count(x.pending, 'question', 'questions'), x.drafts && count(x.drafts, 'draft row', 'draft rows'), x.holds && count(x.holds, 'lane held', 'lanes held'), x.sentBack && count(x.sentBack, 'sent back'), x.awaiting && count(x.awaiting, 'to verify'), x.building && count(x.building, 'building')].filter(Boolean).join(' · ') || (x.open ? count(x.open, 'item open', 'items open') : 'nothing open');
+// Embed the standalone shared builder for every page; the binding also lets the page fixture substitute its output.
+let personNeeds = (${personNeeds.toString()});
+/** The person's calls in one repo, reused by a combined project view. */
+function projectNeeds(p) {
+ return personNeeds(p);
+}
+// The item lifecycle as pullboard declares it in src/machine.js, embedded when the page is served.
+const FLOW = ${JSON.stringify(lifecycle()).replaceAll('<', '\\u003c')};
+
+/**
+ * An item's history replayed through the lifecycle: each event with the state it found the item in
+ * and the move it made, if it made one. The board logs a move under its verb, and a claim on a
+ * claimed item as renew, but never the clock's lapse: an event that cannot start where the replay
+ * stands, or an item that reads otherwise than where its history leaves it, means the clock moved
+ * first, and the replay puts that lapse in, with no time of its own.
+ */
+function replay(item) {
+ const clock = FLOW.moves.filter((m) => m.by.includes('clock'));
+ const steps = [];
+ let at = FLOW.initial;
+ const step = (move, e) => {
+ steps.push({ from: at, move, at: e ? e.at : null, by: e ? e.by : 'the clock', kind: e ? e.kind : move.verb });
+ if (move) at = move.to;
+ };
+ for (const e of item.history) {
+ const verb = e.kind === 'renew' ? 'claim' : e.kind;
+ // A renew is the claim that stays claimed; a claim logged as such is the one that arrives.
+ const fits = (s) => FLOW.moves.find((m) => m.verb === verb && m.from.includes(s) && (verb !== 'claim' || (e.kind === 'renew') === (m.to === s)));
+ const lapse = fits(at) ? null : clock.find((m) => m.from.includes(at) && fits(m.to));
+ if (lapse) step(lapse, null);
+ step(fits(at) || null, e);
+ }
+ const lapse = at === item.status ? null : clock.find((m) => m.from.includes(at) && m.to === item.status);
+ if (lapse) step(lapse, null);
+ return steps;
+}
+
+/** A recorded merge, rather than an accept, is the end of the shipping pipeline. */
+function pipelineStage(item) {
+ if (item.stage !== undefined) return item.stage;
+ if (item.merged) return 'merged';
+ return item.status === 'verified' ? 'accepted' : item.status;
+}
+
+/** The last arrival in this stage; edits, review reservations and renewals do not restart its age. */
+function pipelineSince(item) {
+ if (item.since !== undefined) return item.since;
+ if (item.merged) return item.history.findLast((event) => event.kind === 'merged')?.at || item.updatedAt;
+ const arrival = replay(item).findLast((step) => step.move && step.from !== step.move.to);
+ // Lapses are inferred, but the native claim receipt records the deadline that caused them.
+ if (arrival?.move?.verb === 'lapse') {
+ const claim = item.thread?.findLast((entry) => entry.type === 'move' && ['claim', 'renew'].includes(entry.kind));
+ if (claim?.detail?.leaseUntil) return claim.detail.leaseUntil;
+ }
+ return arrival ? arrival.at || item.updatedAt : item.history.find((event) => event.kind === 'add')?.at || item.updatedAt;
+}
+
+/** Add the list and pipeline fields omitted from full snapshots, while leaving API summaries intact. */
+function listFields(item, fresh = false) {
+ if (!fresh && item.stage !== undefined) return item;
+ const claim = item.status === 'claimed' && item.owner ? { by: item.owner, until: null }
+ : item.status === 'submitted' && item.reviewer ? { by: item.reviewer, until: item.reviewUntil ?? null } : null;
+ return { ...item, stage: pipelineStage(item), since: pipelineSince(item), claim,
+ counts: { verdicts: item.verdicts.length, facts: (item.thread || []).filter((entry) => entry.type === 'fact').length } };
+}
+
+/** Resolve a builder from the full item's owner or the live claim in an API summary. */
+const holderOf = (item) => item.status === 'claimed' ? item.claim?.by ?? item.owner ?? null : null;
+/** Resolve a reviewer from the full item or the live claim in an API summary. */
+const reviewerOf = (item) => item.status === 'submitted' ? item.claim?.by ?? item.reviewer ?? null : null;
+
+/** Render the same board's items in lifecycle order, retaining every item as a detail link. */
+function pipelineCard(items) {
+ const stages = [['open', 'Not started'], ['claimed', 'Building'], ['submitted', 'Waiting for review'], ['accepted', 'Accepted, waiting to merge'], ['merged', 'Merged']];
+ return stages.map(([stage, label]) => {
+ const rows = items.map((item) => listFields(item)).filter((item) => item.stage === stage).sort((a, b) => a.since.localeCompare(b.since) || a.id - b.id);
+ const oldest = rows[0];
+ return '<li class="card-panel pipeline-stage" data-pipeline-stage="' + stage + '"><header><h2>' + label + '</h2><b data-stage-count="' + stage + '">' + rows.length + '</b></header>'
+ + (oldest ? '<p class="pipeline-oldest">Oldest <a class="ref" href="' + esc(itemAddress(oldest.id)) + '" data-go="item:' + oldest.id + '">#' + oldest.id + '</a> · ' + age(oldest.since) + ' in this stage</p>' : '<p class="pipeline-oldest">No items</p>')
+ + '<ul>' + rows.map((item) => '<li><button class="pipeline-item' + (view.item === item.id ? ' on' : '') + '" type="button" data-item="' + item.id + '"><span>#' + item.id + '</span><span>' + esc(item.title) + '</span></button></li>').join('') + '</ul></li>';
+ }).join('');
+}
+
+/** How often each move was made on this board, keyed from>to:verb, from every item's replay. */
+function moveCounts(items) {
+ const counts = new Map();
+ for (const item of items) {
+ for (const s of replay(item)) {
+ if (s.move) counts.set(s.from + '>' + s.move.to + ':' + s.move.verb, (counts.get(s.from + '>' + s.move.to + ':' + s.move.verb) || 0) + 1);
+ }
+ }
+ return counts;
+}
+
+// A finished stay as the timeline says it: 45m, 3h 20m, 2d 4h.
+const span = (ms) => {
+ const m = Math.max(0, Math.round(ms / 60000));
+ return m < 1 ? 'under a minute' : m < 60 ? m + 'm' : m < 1440 ? Math.floor(m / 60) + 'h' + (m % 60 ? ' ' + (m % 60) + 'm' : '') : Math.floor(m / 1440) + 'd' + (Math.floor((m % 1440) / 60) ? ' ' + Math.floor((m % 1440) / 60) + 'h' : '');
+};
+
+/**
+ * An item's history drawn as a timeline. Each move is a dot in the colour of the state it led to, a
+ * reject in the colour of work sent back, and the item's creation (logged as add) one in the start
+ * state's colour; an event that moves nothing is a hollow dot. Between the dots runs a line in the
+ * colour of the state the item stayed in, and under each dot that began a stay, how long it lasted,
+ * or how long so far while the item can still leave. A lapse has a row but no time, so a stay that
+ * ends or begins at one says its length was not logged rather than guess it.
+ */
+function timeline(item) {
+ const entries = Array.isArray(item.thread) && item.thread.length
+ ? item.thread
+ : item.history.filter((entry) => entry.kind !== 'fact').map((entry, eventId) => ({ type: 'move', eventId: eventId + 1, ...entry }));
+ const steps = replay({ ...item, history: entries.filter((entry) => entry.type === 'move').map(({ kind, by, at }) => ({ kind, by, at })) });
+ const facts = entries.filter((entry) => entry.type === 'fact');
+ const replacements = new Map(facts.filter((fact) => fact.supersedes).map((fact) => [fact.supersedes, fact]));
+ const rows = [];
+ let stepIndex = 0;
+ /** Render a lifecycle step, keeping inferred clock lapses between recorded moves. */
+ const moveRow = (s, event, index) => {
+ const enters = s.move ? s.move.to : s.kind === 'add' ? FLOW.initial : null;
+ const state = enters || s.from;
+ const final = FLOW.states.some((f) => f.id === state && f.final);
+ const next = steps.slice(index + 1).find((n) => n.move);
+ const named = s.kind === 'reject' ? 'sent back' : state;
+ const stay = !enters || (final && !next) ? ''
+ : !s.at ? esc(named + (next ? ' after the ' : ' so far since the ') + s.kind + ', length not logged')
+ : !next ? esc(named) + ' for ' + age(s.at) + ' so far'
+ : !next.at ? esc(named + ' until the ' + next.kind + ', length not logged')
+ : esc(named + ' for ' + span(Date.parse(next.at) - Date.parse(s.at)));
+ rows.push('<li class="tl-' + esc(state) + (s.kind === 'reject' ? ' tl-back' : '') + (enters ? '' : ' tl-quiet') + '"' + (event ? ' data-event-id="' + event.eventId + '"' : '') + '><time>' + (s.at ? when(s.at) : '') + '</time><span><b>' + esc(s.kind) + '</b> ' + esc(agentName(s.by)) + '</span>' + (stay ? '<small>' + stay + '</small>' : '') + '</li>');
+ };
+ /** Render one API fact with its identity, replacement and committed code binding. */
+ const factRow = (fact) => {
+ const replacement = replacements.get(fact.id);
+ const judgement = ['decision', 'rejection', 'supersession', 'root-cause'].includes(fact.kind);
+ rows.push('<li id="fact-' + esc(fact.id) + '" class="tl-fact' + (judgement ? ' tl-judgement' : '') + (replacement ? ' tl-superseded' : '') + '" data-event-id="' + fact.eventId + '"><time>' + when(fact.at) + '</time><span class="tl-fact-head"><span class="chip">' + esc(fact.kind) + '</span> <b>' + esc(agentName(fact.by)) + '</b></span><span class="tl-body">' + esc(fact.text) + '</span><small>' + age(fact.at) + (replacement ? ' · <a class="thread-replacement" href="#fact-' + esc(replacement.id) + '">replaced by ' + esc(replacement.kind) + '</a>' : '') + '</small>' + (fact.ref ? '<div class="tl-code">' + codeRef(factCodeRef(fact.ref), '') + '</div>' : '') + '</li>');
+ };
+ for (const entry of entries) {
+ if (entry.type === 'fact') { factRow(entry); continue; }
+ while (stepIndex < steps.length && !(steps[stepIndex].kind === entry.kind && steps[stepIndex].by === entry.by && steps[stepIndex].at === entry.at)) {
+ moveRow(steps[stepIndex], null, stepIndex);
+ stepIndex += 1;
+ }
+ if (stepIndex < steps.length) {
+ moveRow(steps[stepIndex], entry, stepIndex);
+ stepIndex += 1;
+ }
+ }
+ while (stepIndex < steps.length) {
+ moveRow(steps[stepIndex], null, stepIndex);
+ stepIndex += 1;
+ }
+ return '<ol class="tl">' + rows.join('') + '</ol>';
+}
+
+/**
+ * The lifecycle drawn as SVG with this board's counts, the way the README's figure draws it. The
+ * longest way from the start to a final state runs along a row, the first-declared final winning a
+ * tie, its states joined by straight arrows. A pair of states a move leads back along takes a dashed
+ * square route above the row, the further back the higher. The moves that keep a state are written
+ * in its box after a ↻. A state off the row sits below the last state on the row that leads to it,
+ * and routes into it from the row join into one, labelled once. Moves out of those states take
+ * separate routes below the boxes, with their words above each route. Final states have a double border. Boxes
+ * count the items there now; labels count the moves made along each route, or name its moves when
+ * none was. Words are wrapped and placed by a generous estimate of their width, so none overlaps.
+ */
+function flowSvg(p) {
+ // Summary states include board-wide tallies, so the lifecycle drawing needs no per-item histories.
+ const counts = p.moveCounts ? new Map(Object.entries(p.moveCounts)) : moveCounts(p.items);
+ const finals = FLOW.states.filter((s) => s.final).map((s) => s.id);
+ const leads = (s) => FLOW.moves.filter((m) => m.from.includes(s) && m.to !== s).map((m) => m.to);
+ let row = [];
+ const walk = (trail) => {
+ const at = trail[trail.length - 1];
+ if (finals.includes(at)) {
+ if (trail.length > row.length || (trail.length === row.length && finals.indexOf(at) < finals.indexOf(row[row.length - 1]))) row = trail;
+ return;
+ }
+ for (const next of new Set(leads(at))) if (!trail.includes(next)) walk([...trail, next]);
+ };
+ walk([FLOW.initial]);
+ const W = 880, L = 20, BW = 160, step = (W - 2 * L - BW) / Math.max(row.length - 1, 1);
+ const f = (v) => String(Math.round(v * 10) / 10);
+ const col = (s) => row.indexOf(s);
+ const pairs = [];
+ for (const m of FLOW.moves) for (const from of m.from) {
+ let pair = pairs.find((e) => e.from === from && e.to === m.to);
+ if (!pair) pairs.push((pair = { from, to: m.to, moves: [] }));
+ pair.moves.push(m);
+ }
+ const made = (pair, m) => counts.get(pair.from + '>' + pair.to + ':' + m.verb) || 0;
+ const says = (pair) => pair.moves.map((m) => m.verb + ', ' + pair.from + ' to ' + pair.to + ', by the ' + m.by.join(' or ') + ': ' + m.how + '. Made ' + count(made(pair, m), 'time', 'times') + (m.checks.length ? '.\\nChecks, in order:\\n' + m.checks.map((c) => ' ' + c).join('\\n') : '.')).join('\\n\\n');
+ // What some pairs' moves come to: each verb with how often it was made, or every verb when none was.
+ const told = (list) => {
+ const sums = new Map();
+ for (const pair of list) for (const m of pair.moves) sums.set(m.verb, (sums.get(m.verb) || 0) + made(pair, m));
+ const done = [...sums].filter(([, n]) => n);
+ return { words: done.length ? done.map(([verb, n]) => verb + ' ' + n) : [...sums.keys()], idle: !done.length };
+ };
+ // A generous width for words at a size, and words joined by dots into the fewest even lines that
+ // fit a room, as the README's figure splits them.
+ const wide = (words, size) => words.length * size * 0.56;
+ const wrap = (words, room, size) => {
+ for (let n = 1; ; n += 1) {
+ const per = Math.ceil(words.length / n), lines = [];
+ for (let i = 0; i < words.length; i += per) lines.push(words.slice(i, i + per).join(' · '));
+ if (per === 1 || lines.every((line) => wide(line, size) <= room)) return lines;
+ }
+ };
+ const text = (x, y, words, cls, anchor = 'middle') => '<text class="' + cls + '" x="' + f(x) + '" y="' + f(y) + '" text-anchor="' + anchor + '">' + esc(words) + '</text>';
+ const lines = (x, y, said, cls, anchor) => said.map((line, i) => text(x, y - 15 * (said.length - 1 - i), line, cls, anchor)).join('');
+ const path = (points) => 'M' + points.map(([x, y]) => f(x) + ' ' + f(y)).join('L');
+
+ // Inside each box: its name and count, then the moves that keep it, then any items sent back.
+ const back = p.items.filter((i) => stateOf(i) === 'back').length;
+ const inside = new Map(FLOW.states.map((s) => {
+ const keeps = pairs.find((pair) => pair.from === s.id && pair.to === s.id);
+ const said = keeps ? told([keeps]) : null;
+ const kept = said ? wrap(said.words, BW - 28 - wide('↻ ', 11), 11).map((line, i) => (i ? ' ' : '↻ ') + line) : [];
+ return [s.id, { keeps, said, kept, back: s.id === FLOW.initial && back ? back + ' sent back' : '' }];
+ }));
+ const BH = 44 + 15 * Math.max(1, ...[...inside.values()].map((box) => box.kept.length + (box.back ? 1 : 0)));
+
+ // Routes back along the row, each at a level by how far back it goes; their words above them.
+ const ups = pairs.filter((pair) => pair.from !== pair.to && col(pair.from) >= 0 && col(pair.to) >= 0 && col(pair.to) !== col(pair.from) + 1)
+ .map((pair) => ({ pair, span: Math.abs(col(pair.from) - col(pair.to)) })).sort((a, b) => a.span - b.span);
+ const spans = [...new Set(ups.map((up) => up.span))];
+ for (const up of ups) {
+ up.level = spans.indexOf(up.span);
+ const a = L + BW / 2 + col(up.pair.from) * step, b = L + BW / 2 + col(up.pair.to) * step;
+ const before = (key, value) => ups.filter((other) => other !== up && other.pair[key] === value && other.span < up.span).length;
+ up.start = a + (a > b ? 16 : -16) + (a > b ? 26 : -26) * before('from', up.pair.from);
+ up.end = b + (a > b ? BW / 2 - 40 : 40 - BW / 2) + (a > b ? -30 : 30) * before('to', up.pair.to);
+ up.said = told([up.pair]);
+ up.lines = wrap(up.said.words, Math.abs(up.start - up.end) - 20, 12);
+ }
+ // Higher routes cross this level vertically; put its words in the widest gap between them.
+ for (const up of ups) {
+ const left = Math.min(up.start, up.end), right = Math.max(up.start, up.end);
+ const cuts = [left, ...ups.filter((other) => other.span > up.span).flatMap((other) => [other.start, other.end]).filter((x) => x > left && x < right), right].sort((a, b) => a - b);
+ const rooms = cuts.slice(1).map((end, index) => ({ left: cuts[index], right: end })).sort((a, b) => (b.right - b.left) - (a.right - a.left));
+ const room = rooms[0];
+ up.labelX = (room.left + room.right) / 2;
+ up.lines = wrap(up.said.words, room.right - room.left - 20, 12);
+ }
+ // Each level stands clear of the words of the level below it.
+ const rise = [];
+ for (const level of spans.keys()) {
+ const below = ups.filter((up) => up.level === level - 1);
+ rise[level] = level ? rise[level - 1] + 18 + 15 * Math.max(...below.map((up) => up.lines.length)) : 30;
+ }
+ const highest = ups.length ? Math.max(...ups.map((up) => rise[up.level] + 21 + 15 * (up.lines.length - 1))) : 0;
+ const top = 12 + highest, Y = top + BH / 2, bottom = top + BH;
+ const pos = new Map(row.map((s, i) => [s, { x: L + BW / 2 + i * step, y: Y }]));
+
+ // A state off the row sits below the last state on it that leads there.
+ const below = FLOW.states.filter((s) => !pos.has(s.id));
+ for (const s of below) {
+ const from = row.filter((r) => leads(r).includes(s.id));
+ pos.set(s.id, { x: from.length ? pos.get(from[from.length - 1]).x : W / 2, y: bottom + 80 + BH / 2 });
+ }
+ const outgoing = pairs.filter((pair) => pair.from !== pair.to && below.some((state) => state.id === pair.from));
+ const H = (below.length ? bottom + 80 + BH : bottom) + 14 + (outgoing.length ? 44 + 40 * (outgoing.length - 1) : 0);
+
+ const group = (pairList, route, label) => pairList.map((pair, n) => '<g><title>' + esc(says(pair)) + '</title><path class="edge' + (route.back ? ' back' : '') + '" d="' + route.d + '" marker-end="url(#pb-head' + (route.back ? '-back' : '') + ')"/>' + (n === 0 ? label : '') + '</g>').join('');
+ const tone = (said, extra = '') => 'tag' + (said.idle ? ' idle' : '') + extra;
+ const routes = [];
+ // Straight along the row.
+ for (const pair of pairs.filter((pair) => col(pair.from) >= 0 && col(pair.to) === col(pair.from) + 1)) {
+ const a = pos.get(pair.from), b = pos.get(pair.to), said = told([pair]);
+ const words = said.words.join(' · ');
+ // A long label sits above the boxes when the gap cannot hold it with clearance.
+ const labelY = wide(words, 12) + 8 > b.x - a.x - BW ? top - 8 : Y - 8;
+ routes.push(group([pair], { d: path([[a.x + BW / 2, Y], [b.x - BW / 2 - 1, Y]]) }, text((a.x + b.x) / 2, labelY, words, tone(said))));
+ }
+ // Square, above the row.
+ for (const up of ups) {
+ const isBack = col(up.pair.to) < col(up.pair.from), y = top - rise[up.level];
+ routes.push(group([up.pair], { back: isBack, d: path([[up.start, top], [up.start, y], [up.end, y], [up.end, top - 1]]) }, lines(up.labelX, y - 7, up.lines, tone(up.said, isBack ? ' back' : ''))));
+ }
+ // Down from the row, joining into one route per state below, labelled once on the way in.
+ for (const s of below) {
+ const t = pos.get(s.id), into = pairs.filter((pair) => pair.to === s.id && col(pair.from) >= 0);
+ const said = told(into), tTop = t.y - BH / 2;
+ const xs = into.map((pair) => pos.get(pair.from).x).sort((a, b) => a - b);
+ const left = xs.filter((x) => x < t.x - 0.5), right = xs.filter((x) => x > t.x + 0.5);
+ const label = left.length
+ ? lines((left[0] + (left[1] ?? t.x - BW / 2)) / 2, t.y - 8, wrap(said.words, (left[1] ?? t.x - BW / 2) - left[0] - 20, 12), tone(said))
+ : right.length
+ ? lines((right[right.length - 1] + (right[right.length - 2] ?? t.x + BW / 2)) / 2, t.y - 8, wrap(said.words, right[right.length - 1] - (right[right.length - 2] ?? t.x + BW / 2) - 20, 12), tone(said))
+ : lines(t.x + 10, (bottom + tTop) / 2 + 4, said.words, tone(said), 'start');
+ // The label goes with the route that reaches furthest, drawn first; the others join it.
+ const order = [...into].sort((p1, p2) => Math.abs(pos.get(p2.from).x - t.x) - Math.abs(pos.get(p1.from).x - t.x));
+ order.forEach((pair, n) => {
+ const a = pos.get(pair.from);
+ const d = Math.abs(a.x - t.x) < 0.5 ? path([[a.x, bottom], [t.x, tTop - 1]]) : path([[a.x, bottom], [a.x, t.y], [a.x < t.x ? t.x - BW / 2 - 1 : t.x + BW / 2 + 1, t.y]]);
+ routes.push(group([pair], { d }, n === 0 ? label : ''));
+ });
+ }
+ // A below-row state can move back into the row or on to another below-row state.
+ outgoing.forEach((pair, index) => {
+ const from = pos.get(pair.from), to = pos.get(pair.to);
+ const lane = bottom + 80 + BH + 26 + index * 40;
+ const side = to.x < from.x ? to.x + BW / 2 + 1 : to.x - BW / 2 - 1;
+ const said = told([pair]);
+ const room = Math.max(40, Math.abs(side - from.x) - 24);
+ const label = lines((from.x + side) / 2, lane - 8, wrap(said.words, room, 12), tone(said));
+ routes.push(group([pair], { d: path([[from.x, from.y + BH / 2], [from.x, lane], [side, lane], [side, to.y]]) }, label));
+ });
+
+ const boxes = FLOW.states.map((s) => {
+ const { x, y } = pos.get(s.id), box = inside.get(s.id), left = x - BW / 2, boxTop = y - BH / 2;
+ const tip = s.id + ': ' + s.means + (s.entry.length ? '.\\nEvery way in checks:\\n' + s.entry.map((r) => ' ' + r).join('\\n') : '.');
+ const keeps = box.kept.length ? '<g><title>' + esc(says(box.keeps)) + '</title>' + box.kept.map((line, i) => text(left + 14, boxTop + 47 + 15 * i, line, 'keep' + (box.said.idle ? ' idle' : ''), 'start')).join('') + '</g>' : '';
+ return '<g class="s-' + esc(s.id) + '"><title>' + esc(tip) + '</title><rect class="box" x="' + f(left) + '" y="' + f(boxTop) + '" width="' + BW + '" height="' + BH + '" rx="10"/>'
+ + (s.final ? '<rect class="box inner" x="' + f(left + 4) + '" y="' + f(boxTop + 4) + '" width="' + (BW - 8) + '" height="' + (BH - 8) + '" rx="7"/>' : '')
+ + text(left + 14, boxTop + 25, s.id, 'name', 'start') + text(x + BW / 2 - 14, boxTop + 29, String(p.items.filter((i) => i.status === s.id).length), 'n', 'end')
+ + keeps + (box.back ? text(left + 14, boxTop + 47 + 15 * box.kept.length, box.back, 'sub', 'start') : '') + '</g>';
+ });
+ const head = (id, cls) => '<marker id="' + id + '" class="' + cls + '" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z"/></marker>';
+ return '<svg viewBox="0 0 ' + W + ' ' + f(H) + '" role="img" aria-label="The item lifecycle, with counts from this board"><defs>' + head('pb-head', '') + head('pb-head-back', 'back') + '</defs>' + routes.join('') + boxes.join('') + '</svg>';
+}
+
+/** Read or move through API v1, retaining the rule and repair guidance in a refusal. */
+async function api(path, body) {
+ path = snapshot ? path.split('?')[0].slice(1) + '.json' : path;
+ if (snapshot) {
+ if (body !== undefined && body !== null) throw new Error('This is a read-only snapshot.');
+ return jsonRequest(path, undefined, '', {});
+ }
+ if (path === '/api/v1/boards') return starLine(await listedBoards());
+ const boardId = /^\\/api\\/v1\\/boards\\/([0-9a-f]{32})(?:\\/|$)/u.exec(path)?.[1];
+ const source = boardId ? boardSources.get(boardId) : null;
+ if (boardId && !source) throw new Error(transport
+ ? 'Pair this browser to read that board, or refresh the board list if the board is local.'
+ : 'This board is not available in the current view. Refresh the board list and retry.');
+ if (boardId && source?.kind === 'relay') {
+ if (body !== undefined && body !== null) throw new Error('This is a read-only view of relay boards.');
+ if (!transport) throw transportLoadError || new Error('The relay transport is still loading.');
+ const reply = await transport.request(path, body);
+ if (path.includes('/state') && reply.state) return { ...reply, state: { ...reply.state, root: source.board.root } };
+ return reply;
+ }
+ if (body && (hosted.local ? readOnly && source?.kind !== 'local' : pageReadOnly)) throw new Error('This is a read-only view.');
+ const base = source?.kind === 'local' ? localReadBase : connection.base;
+ const headers = source?.kind === 'local' ? localReadHeaders : connection.headers;
+ return jsonRequest(path, body, base, headers);
+}
+
+/** Use one JSON request primitive, capturing its local route and session before awaiting a reply. */
+async function jsonRequest(path, body, base, headers, cache, format = 'json') {
+ const session = localSession;
+ path = base + path;
+ const res = await fetch(path, { method: body ? 'POST' : 'GET', headers: { ...headers, ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined, cache });
+ const json = format === 'html' && res.ok ? await res.text() : await res.json();
+ if (session && session === localSession && base === session.origin) {
+ if (res.status === 401 || res.status === 403) localExpired();
+ else if (res.ok && !localConfirmed) { localConfirmed = true; tabValue(LOCAL_TRIPS, null); }
+ }
+ if (!res.ok) {
+ const refusal = json.error;
+ const message = refusal && typeof refusal === 'object' ? '[' + refusal.code + '] ' + refusal.message : refusal || res.status;
+ const error = new Error(message);
+ if (refusal && typeof refusal === 'object') error.code = refusal.code;
+ throw error;
+ }
+ return json;
+}
+
+/** Read only this machine's authenticated view, including when its page is hosted elsewhere. */
+function sharingApi(body) {
+ return jsonRequest('/api/v1/view-link', body, hosted.local ? localReadBase : connection.base,
+ hosted.local ? localReadHeaders : connection.headers);
+}
+
+let sharingReady = null;
+let sharingTask = Promise.resolve();
+let sharing = { state: 'idle', intentId: null, popup: null, timer: null, closing: false, boards: [] };
+
+${sharingPresentation()}/** Stop the one operation and await core cleanup; a linking batch is never described as rolled back. */
+async function closeSharing() {
+ clearTimeout(sharing.timer);
+ sharing.closing = true;
+ if (!sharing.intentId) return;
+ try {
+ const status = await sharingApi({ action: 'cancel', intentId: sharing.intentId });
+ sharingProgress(status);
+ sharing.popup?.close(); sharing.popup = null;
+ $('share-start').disabled = false;
+ sharingReady = sharingInvitation();
+ } catch (error) {
+ $('share-status').textContent = error.message;
+ if (error.code === 'VIEW_SIGN_IN_LINKING') {
+ sharing.closing = false;
+ sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);
+ } else { sharing.popup?.close(); sharing.popup = null; $('share-start').disabled = false; }
+ }
+}
+
+/** Poll public progress only while the person has an active sign-in or pairing step. */
+async function pollSharing() {
+ if (sharing.closing) return;
+ if (sharing.state === 'waiting' && sharing.popup?.closed) { sharingTask = closeSharing(); return sharingTask; }
+ try {
+ const status = await sharingApi({ action: 'status', intentId: sharing.intentId });
+ sharingProgress(status);
+ if (['waiting', 'linking', 'pairing'].includes(status.state)) sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);
+ else { $('share-start').disabled = false; sharingReady = sharingInvitation(); }
+ } catch (error) {
+ $('share-status').textContent = error.message;
+ $('share-start').disabled = false;
+ }
+}
+
+/** Begin one existing all-board sign-in; open its browser window in the native click before awaiting the server. */
+async function beginSharing(popup) {
+ sharing = { state: 'waiting', intentId: null, popup, timer: null, closing: false, boards: [] };
+ $('share-panel').hidden = false;
+ $('share-start').disabled = true;
+ $('share-status').textContent = 'Starting GitHub sign-in…';
+ try {
+ const instructions = await sharingApi({ action: 'start' });
+ sharing.intentId = instructions.intentId;
+ if (sharing.closing || popup?.closed) return await closeSharing();
+ $('share-status').textContent = 'Enter ' + instructions.userCode + ' in the GitHub window. Closing this sign-in before linking leaves every board local.';
+ popup.location.replace(instructions.verificationURL);
+ sharing.timer = setTimeout(() => { sharingTask = pollSharing(); }, 250);
+ } catch (error) {
+ popup?.close();
+ $('share-status').textContent = error.message;
+ $('share-start').disabled = false;
+ }
+}
+
+/** Open only core's transient device navigation in a separately authenticated HTML response, never a JSON URL. */
+async function pairSharing(popup) {
+ const base = hosted.local ? localReadBase : connection.base;
+ const headers = hosted.local ? localReadHeaders : connection.headers;
+ try {
+ const html = await jsonRequest('/api/v1/view-link', { action: 'pairing', intentId: sharing.intentId }, base, headers, undefined, 'html');
+ const destination = new DOMParser().parseFromString(html, 'text/html').querySelector('a')?.getAttribute('href');
+ if (!destination) throw new Error('Phone pairing is no longer waiting. Read the sign-in status and start again if needed.');
+ popup.location.replace(destination);
+ } catch (error) { popup?.close(); $('share-status').textContent = error.message; }
+}
+
+$('share-start')?.addEventListener('click', () => {
+ const popup = window.open('about:blank', '_blank');
+ if (!popup) { $('share-panel').hidden = false; $('share-status').textContent = 'Allow this view to open the GitHub sign-in window, then try again.'; return; }
+ popup.opener = null;
+ sharingTask = beginSharing(popup);
+});
+$('share-close')?.addEventListener('click', () => { sharingTask = closeSharing(); });
+$('share-pair')?.addEventListener('click', () => {
+ const popup = window.open('about:blank', '_blank');
+ if (!popup) { $('share-status').textContent = 'Allow this view to open the device-pairing window, then try again.'; return; }
+ popup.opener = null;
+ sharingTask = pairSharing(popup);
+});
+
+let relayEngine = null;
+/** The account's linked boards: a same-origin read that declares the relay's engine, as every relay request does. */
+// The account's last read and when it ended, answered or refused, for the star line, which reuses it rather than
+// asking again (#817): a refusal is an answer too, "not linked", and is not asked again straight away.
+let linkedSeen = null;
+async function linkedList() {
+ relayEngine ??= await import('/relay/engine.js').then((engine) => String(engine.ENGINE_VERSION), () => '');
+ try {
+ const reply = await jsonRequest('/api/v1/boards', undefined, '', relayEngine ? { 'x-pullboard-engine': relayEngine } : {}, 'no-store');
+ linkedSeen = { at: Date.now(), reply };
+ return reply;
+ } catch (error) {
+ linkedSeen = { at: Date.now(), reply: null };
+ throw error;
+ }
+}
+
+/**
+ * Whether the signed-in person's linked boards name one this machine's list lacks: only then does the page need the
+ * decrypting relay client. The metadata is a same-origin cookie-authenticated read, with none of this machine's local
+ * credential.
+ */
+async function linkedBoardMissing(localIds) {
+ const linked = await linkedList();
+ return Boolean(linked.boards?.some(board => typeof board.id === 'string' && /^[0-9a-f]{32}$/.test(board.id) && typeof board.repository === 'string' && !localIds.has(board.id)));
+}
+
+/** Read this machine's API list and the signed-in relay list, preferring a local registration with the same id. */
+async function listedBoards() {
+ let local = { boards: [], warnings: [] };
+ let relay = { boards: [], warnings: [] };
+ const hasLocal = hosted.local ? Boolean(localReadBase) && Boolean(localSession) : transportModule === null;
+ if (hasLocal) {
+ try {
+ local = await jsonRequest('/api/v1/boards', undefined, localReadBase, localReadHeaders, 'no-store');
+ } catch (error) {
+ // A local read that fails once, as while the view restarts, is no reason to load the relay client for a
+ // person whose linked boards are all on this machine or who has none (#748).
+ if (!transport && hosted.relaySession && configuredTransportModule) {
+ try { if (await linkedBoardMissing(new Set())) await loadTransport(); } catch { /* Keep the local refusal when neither source can be read. */ }
+ }
+ if (!transport) throw error;
+ localNote('local-failed', { detail: String(error.message || error) });
+ }
+ }
+ if (hosted.local && hasLocal && hosted.relaySession && configuredTransportModule && !transport) {
+ try {
+ if (await linkedBoardMissing(new Set((local.boards || []).map(board => board.id)))) await loadTransport();
+ } catch (error) { localNote('linked-failed', { detail: String(error.message || error) }); }
+ }
+ if (!hasLocal && transportModule && !transport) throw transportLoadError || new Error('The browser transport is still loading.');
+ if (transport) {
+ try { relay = await transport.request('/api/v1/boards'); }
+ catch (error) {
+ if (!hosted.local || !hasLocal) throw error;
+ localNote('linked-failed', { detail: String(error.message || error) });
+ }
+ }
+ boardSources.clear();
+ localBoardIds.clear();
+ const boards = [];
+ for (const board of local.boards || []) {
+ if (typeof board.id !== 'string') continue;
+ const row = { ...board, source: 'local' };
+ boardSources.set(row.id, { kind: 'local', board: row });
+ localBoardIds.add(row.id);
+ boards.push(row);
+ }
+ for (const board of relay.boards || []) {
+ if (typeof board.id !== 'string' || boardSources.has(board.id)) continue;
+ // A linked board reads by its own name, as it does locally, with its owner as a quiet prefix.
+ const [owner, name] = String(board.name || '').includes('/') ? board.name.split('/') : ['', board.name];
+ const row = { ...board, root: board.id, source: 'relay', name, owner };
+ boardSources.set(row.id, { kind: 'relay', board: row });
+ boards.push(row);
+ }
+ if (hosted.local) await hostedListed(boards);
+ return { version: 1, boards, warnings: [...(local.warnings || []), ...(relay.warnings || [])] };
+}
+
+/** After a hosted board list: a list clears a state it stood in for, and a signed-in empty one says why it is empty. */
+async function hostedListed(boards) {
+ let shown = $('local-note').dataset.state || '';
+ // A list that arrives after a failed read, once this computer's view answered, means the page recovered: the problem
+ // it showed is over, and this list decides what shows now.
+ if (shown === 'problem' && localReached) { localNote(null); shown = ''; }
+ if (boards.length) { if (['looking', 'not-running', 'no-linked', 'unpaired', 'signed-out'].includes(shown)) localNote(null); return; }
+ // Nobody signed in and no board on this computer yet: the page says how to make one, as the local view does.
+ if (!hosted.relaySession) { if (shown === 'looking') localNote(null); return; }
+ // An empty local view can still leave linked boards on another computer waiting for this browser to pair.
+ if (!['', 'looking', 'not-running', 'no-linked', 'unpaired'].includes(shown)) return;
+ let linked;
+ try { linked = await linkedList(); } catch { return; /* the relay's banner says why */ }
+ const names = (linked.boards || []).filter((board) => typeof board.repository === 'string').map((board) => board.repository);
+ localNote(names.length ? 'unpaired' : 'no-linked', { linked: names });
+}
+
+/** Set presentation controls for the selected board; API routing still checks the target board independently. */
+`;
+}
diff --git a/src/view/page-script-3.js b/src/view/page-script-3.js
new file mode 100644
index 00000000..b78f53ee
--- /dev/null
+++ b/src/view/page-script-3.js
@@ -0,0 +1,392 @@
+/**
+ * Part 3 of the hosted page's script, verbatim from src/cockpit.js lines 1310-1690 (#745): its
+ * text is what the page served before the split, with the values its ${} expressions read passed in as scope.
+ *
+ * @param {Record<string, any>} scope - The values cockpitPage passes for the names this part interpolates.
+ * @returns {string} The script text of this part.
+ */
+export function pageScriptPart3(scope) {
+ const { applyStateDelta } = scope;
+return `/** Whether a selected project is backed by the read-only relay transport. */
+function relayProject(root = view.root) {
+ const board = data?.projects.find((entry) => entry.root === root && entry.ok);
+ return boardSources.get(board?.id)?.kind === 'relay';
+}
+
+/** Send only literal person intent; the transport seals it and generic API writes stay refused. */
+async function sendPersonRequest(root, move) {
+ if (!requests || snapshot || !readOnly) throw new Error('This view cannot send person requests.');
+ if (!relayProject(root)) throw new Error('Person requests through the relay require a linked relay board.');
+ if (!['add', 'shout', 'answer', 'hold', 'spec-approve', 'spec-decline'].includes(move.verb)) throw new Error('Choose a person action from the view controls.');
+ if (!transport) throw transportLoadError || new Error('The browser transport is still loading.');
+ return transport.request(boardPath(root) + '/moves', move);
+}
+
+/** Name a person request using its public literal intent, without exposing its sealed document. */
+function requestLabel(request) {
+ const move = request.move;
+ const args = move?.args || {};
+ if (move?.verb === 'add') return 'New item: ' + (args.title || 'Untitled');
+ if (move?.verb === 'shout') return 'Shout to ' + (args.to || 'coordinator') + ': ' + (args.text || '');
+ if (move?.verb === 'answer') return 'Answer #' + move.item + ': ' + (args.text || '');
+ if (move?.verb === 'hold') return (args.off ? 'Release ' : 'Hold ') + (args.lane || '') + ' lane' + (!args.off && args.reason ? ': ' + args.reason : '');
+ if (move?.verb === 'spec-approve') return 'Approve row ' + (args.ids || '');
+ if (move?.verb === 'spec-decline') return 'Decline row ' + (args.ids || '');
+ return 'Person request';
+}
+
+/** Retain the native request status and the CLI's complete refusal guidance beside an action. */
+function requestNotice(request) {
+ const label = { waiting: 'Waiting', done: 'Done', refused: 'Refused' }[request.status] || 'Unknown status';
+ const error = request.status === 'refused' && request.error;
+ return label + ' · ' + requestLabel(request) + (error ? '\\n' + (error.code ? '[' + error.code + '] ' : '') + (error.message || '') + (error.next ? '\\n' + error.next : '') : '');
+}
+
+/** Show the public request receipts on every board tab and update the latest action's status. */
+function renderPersonRequests(project) {
+ const entries = project?.personRequests || [];
+ const panel = $('person-requests');
+ panel.hidden = !entries.length;
+ panel.innerHTML = entries.length ? '<h2>Your requests</h2><ul class="request-list">' + [...entries].sort((a, b) => b.sequence - a.sequence).map((request) => {
+ const status = { waiting: 'Waiting', done: 'Done', refused: 'Refused' }[request.status] || 'Unknown status';
+ const error = request.status === 'refused' && request.error;
+ const reason = error ? '<p class="request-error">' + (error.code ? '<b>' + esc(error.code) + '</b> ' : '') + esc(error.message || '') + '</p>' + (error.next ? '<p class="request-next">' + esc(error.next) + '</p>' : '') : '';
+ return '<li data-person-request="' + esc(request.id) + '"><span class="request-label">' + esc(requestLabel(request)) + '</span><span class="chip request-status ' + (request.status === 'done' ? 'ok' : request.status === 'refused' ? 'no' : 'warn') + '">' + status + '</span>' + reason + '</li>';
+ }).join('') + '</ul>' : '';
+ const active = view.request;
+ const current = active && active.root === view.root && active.run === view.acting && entries.find((request) => request.id === active.id);
+ if (current && !$('console').hidden) {
+ $('console').className = 'console' + (current.status === 'done' ? ' ok' : current.status === 'refused' ? ' no' : '');
+ $('console').textContent = requestNotice(current);
+ }
+ const feedback = view.specFeedback;
+ const rowRequest = feedback?.root === view.root && feedback.requestId && entries.find((request) => request.id === feedback.requestId);
+ if (rowRequest) {
+ feedback.status = rowRequest.status;
+ feedback.tone = rowRequest.status === 'done' ? 'ok' : rowRequest.status === 'refused' ? 'no' : '';
+ feedback.text = requestNotice(rowRequest);
+ }
+}
+
+/** A board's sidebar counts, derived from the same API state the page displays. */
+function boardSummary(board, state) {
+ const needs = personNeeds(state);
+ /** Count the calls, with draft rows retaining their individual count in the sidebar. */
+ const calls = (kind) => needs.filter((row) => row.kind === kind).reduce((total, row) => total + (row.count ?? 1), 0);
+ /** Count one item state for the sidebar. */
+ const count = (test) => state.items.filter(test).length;
+ return {
+ ...board, ok: true,
+ releaseNotes: state.releaseNotes,
+ building: count((item) => item.status === 'claimed'),
+ awaiting: count((item) => item.status === 'submitted'),
+ sentBack: count((item) => item.status === 'open' && item.verdict && item.verdict.decision === 'REJECT'),
+ open: count((item) => item.status === 'open'),
+ verified: count((item) => item.status === 'verified'),
+ pending: calls('pending'),
+ drafts: calls('draft') + calls('rigor-draft'),
+ holds: calls('hold'),
+ laneHolds: state.holds,
+ decisions: calls('decision'),
+ // What each item's state reads from, so another repo's roadmap can show it as this board's
+ // Items tab does, sent back included, and open it here.
+ items: state.items.map((item) => listFields(item)),
+ agents: state.agents, events: state.events, milestones: state.milestones,
+ };
+}
+
+/** Format an API-measured duration in readable units without deriving times from events [N26]. */
+function flowMinutes(value) {
+ if (value === null || value === undefined) return 'unmeasured';
+ const minutes = Math.round(value);
+ if (minutes < 60) return minutes + ' min';
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return hours + ' h ' + minutes % 60 + ' min';
+ return Math.floor(hours / 24) + ' d ' + hours % 24 + ' h';
+}
+
+/** A queue's oldest item and how long it has waited, as the flow card reads it. */
+function oldestLine(oldest) {
+ return 'Oldest: ' + (oldest ? '#' + oldest.id + ' · ' + flowMinutes(oldest.ageMinutes) : 'none');
+}
+
+/** Render the four stages, live queues and single recommendation supplied by stats [N26]. */
+function proofFlowCard(flow) {
+ if (!flow) return '';
+ const stages = [['build', 'Build'], ['reviewWait', 'Review wait'], ['review', 'Review'], ['mergeWait', 'Merge wait']];
+ const queues = [['open', 'Open'], ['claimed', 'Building'], ['submitted', 'In review'], ['accepted', 'Awaiting merge']];
+ const averages = stages.map(([key, label]) => {
+ const average = flow.stages[key].averageMinutes;
+ return '<div><span>' + label + ' average</span><b data-stage="' + key + '" data-value="' + esc(average ?? '') + '">' + esc(flowMinutes(average)) + '</b></div>';
+ }).join('');
+ const waiting = queues.map(([key, label]) => {
+ const queue = flow.queues[key];
+ const oldest = queue.oldest;
+ return '<div><span>' + label + ' queue</span><b data-queue="' + key + '" data-value="' + esc(queue.size) + '">' + esc(queue.size) + '</b>'
+ + '<small data-oldest="' + key + '" data-value="' + esc(oldest?.ageMinutes ?? '') + '">' + esc(oldestLine(oldest)) + '</small></div>';
+ }).join('');
+ const bottleneck = flow.bottleneck;
+ return '<div class="proof-stats-flow"><div class="proof-stats-grid">' + averages + waiting + '</div>'
+ + '<p class="proof-stats-bottleneck"><b>Bottleneck: </b><span data-flow="bottleneck">' + esc(bottleneck.message) + '</span>'
+ + (bottleneck.recommendation ? ' · <span data-flow="recommendation">' + esc(bottleneck.recommendation) + '</span>' : '') + '</p></div>';
+}
+
+/** Render the event-log totals already supplied by the shared stats API [V2,N26]. */
+function proofStatsCard(stats, expanded = false) {
+ if (!stats) return '<span class="muted">Stats unavailable</span>';
+ const percentage = (Number(stats.rejectionShare) * 100).toFixed(1) + '%';
+ const bottleneck = stats.flow?.bottleneck;
+ const stage = { build: 'Build', reviewWait: 'Review wait', review: 'Review', mergeWait: 'Merge wait' }[bottleneck?.stage];
+ const summary = stats.merged + ' merged · ' + percentage + ' sent back'
+ + (bottleneck ? ' · Bottleneck: ' + (stage || bottleneck.message) + (bottleneck.recommendation ? ', ' + bottleneck.recommendation : '') : '');
+ /** Format an API timestamp for the card without recalculating event statistics.
+ * @param {string|number|null} value
+ * @returns {string}
+ */
+ const dateText = (value) => value ? new Date(value).toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' }) : 'none';
+ const firstAt = stats.firstEventAt ?? '';
+ const lastAt = stats.lastEventAt ?? '';
+ return '<button class="proof-stats-summary" id="proof-stats-summary" data-stats-toggle type="button" aria-expanded="' + expanded + '" aria-controls="proof-stats-full">'
+ + '<span class="proof-stats-summary-text">' + esc(summary) + '</span><span class="proof-stats-caret" aria-hidden="true">' + (expanded ? '−' : '+') + '</span></button>'
+ + '<div class="proof-stats-full" id="proof-stats-full"' + (expanded ? '' : ' hidden') + '>'
+ + '<div class="proof-stats-head"><b>Proof stats</b><span>from recorded moves</span></div>'
+ + '<div class="proof-stats-grid">'
+ + '<div><span>Submissions</span><b data-stat="submissions" data-value="' + esc(stats.submissions) + '">' + esc(stats.submissions) + '</b></div>'
+ + '<div><span>Rejections</span><b data-stat="rejections" data-value="' + esc(stats.rejections) + '">' + esc(stats.rejections) + '</b></div>'
+ + '<div><span>Sent back</span><b data-stat="rejectionShare" data-value="' + esc(percentage) + '">' + esc(percentage) + '</b></div>'
+ + '<div><span>Merged</span><b data-stat="merged" data-value="' + esc(stats.merged) + '">' + esc(stats.merged) + '</b></div>'
+ + '<div><span>Without accept</span><b data-stat="mergedWithoutAccept" data-value="' + esc(stats.mergedWithoutAccept) + '">' + esc(stats.mergedWithoutAccept) + '</b></div>'
+ + '<div><span>Agents</span><b data-stat="agentCount" data-value="' + esc(stats.agentCount) + '">' + esc(stats.agentCount) + '</b></div>'
+ + '<div><span>First · latest</span><small><time data-stat="firstEventAt" data-value="' + esc(firstAt) + '" datetime="' + esc(firstAt) + '">' + esc(dateText(firstAt)) + '</time> · <time data-stat="lastEventAt" data-value="' + esc(lastAt) + '" datetime="' + esc(lastAt) + '">' + esc(dateText(lastAt)) + '</time></small></div>'
+ + '</div>' + proofFlowCard(stats.flow) + '</div>';
+}
+
+/** Resolve a displayed repo to the persistent board identity supplied by API v1. */
+function boardPath(root) {
+ const board = data && data.projects.find((entry) => entry.root === root && entry.ok);
+ if (!board) throw new Error('This board is unavailable; choose a readable project and retry.');
+ return '/api/v1/boards/' + encodeURIComponent(board.id);
+}
+
+/**
+ * What the page last drew for a listed board, to stand in for it in a catch-up that does not read it: its sidebar
+ * row, and its state when the page shows it. Nothing when the page has no such row, or shows the board without one.
+ */
+function lastRead(board, root) {
+ const row = data?.projects.find((entry) => entry.root === board.root && entry.id === board.id && entry.ok);
+ if (!row || row.loading) return null;
+ const state = data.root === board.root ? data.project : data.group?.repos.find((repo) => repo.root === board.root)?.board ?? null;
+ if (!state && (board.root === root || root === 'group:' + board.project)) return null;
+ return { row: { ...row, ...board, ok: true }, state };
+}
+
+/** Group the listed repositories without waiting for their individual board states. */
+function projectGroups(projects) {
+ const grouped = new Map();
+ for (const project of projects) {
+ if (!project.project) continue;
+ if (!grouped.has(project.project)) grouped.set(project.project, []);
+ grouped.get(project.project).push(project);
+ }
+ // One repository shows once, without a heading that repeats its name.
+ return [...grouped].filter(([, repos]) => repos.length > 1).map(([name, repos]) => ({ name, key: 'group:' + name, repos }));
+}
+
+/**
+ * Compose the multi-repo page from the public board list and each board's public state. A catch-up names the boards
+ * whose events arrived in fresh and reads only those; every other board keeps what the page last drew (#545).
+ */
+async function boardState(root, mark, fresh = null) {
+ const listed = await api('/api/v1/boards');
+ if (!data) {
+ // Names are already known: a slow board must not leave the project picker blank.
+ const projects = listed.boards.map((board) => ({ ...board, ok: true, loading: true }));
+ projects.push(...(listed.warnings || []).map((warning) => ({ ...warning, ok: false, error: warning.error.error.message })));
+ data = { root: null, project: null, group: null, projects, groups: projectGroups(projects) };
+ renderSide();
+ $('project-loading').hidden = projects.length === 0;
+ }
+ const states = new Map();
+ const cursor = mark !== null && mark !== undefined && /^\\d+$/.test(String(mark)) && Number.isSafeInteger(Number(mark)) ? Number(mark) : null;
+ const projects = await Promise.all(listed.boards.map(async (board) => {
+ const kept = fresh && !fresh.has(board.root) ? lastRead(board, root) : null;
+ if (kept) {
+ if (kept.state) states.set(board.root, kept.state);
+ return kept.row;
+ }
+ try {
+ const state = await boardRead(board, board.root === root ? cursor : null);
+ states.set(board.root, state);
+ return boardSummary(board, state);
+ } catch (error) {
+ return { ...board, ok: false, error: String(error.message || error) };
+ }
+ }));
+ projects.push(...(listed.warnings || []).map((warning) => ({ ...warning, ok: false, error: warning.error.error.message })));
+ const groups = projectGroups(projects);
+ const group = groups.find((entry) => entry.key === root);
+ return {
+ projects, groups, project: states.get(root) || null,
+ group: group ? { name: group.name, repos: group.repos.filter((repo) => repo.ok).map((repo) => ({ root: repo.root, name: repo.name, board: states.get(repo.root) })) } : null,
+ };
+}
+
+// What each local board last sent this page, {state, sequence, version}: the base its next read asks to extend.
+const sentStates = new Map();
+// #552's delta applier, embedded as the server's own source, so the page applies a delta and recomputes nothing.
+const applyStateDelta = (${applyStateDelta.toString()});
+
+/**
+ * Read one board's summary state. A local board the page read before asks only what changed since the state it holds
+ * (#552) and applies that delta as sent; it loads a fresh snapshot only when the answer resets, as when the server no
+ * longer keeps that base or the format changed (#555). Relay boards and snapshots have no deltas.
+ */
+async function boardRead(board, seen) {
+ const path = '/api/v1/boards/' + encodeURIComponent(board.id) + '/state', mark = seen === null ? '' : 'seen=' + encodeURIComponent(seen);
+ const local = !snapshot && localBoardIds.has(board.id), held = local ? sentStates.get(board.id) : null;
+ if (held && Number.isSafeInteger(held.sequence)) {
+ const reply = await api(path + '?since=' + held.sequence + (mark && '&' + mark) + (held.version === undefined ? '' : '&eventLogVersion=' + encodeURIComponent(held.version)));
+ if (reply.delta) {
+ const state = applyStateDelta(held.state, reply.delta);
+ sentStates.set(board.id, { state, sequence: reply.sequence, version: reply.eventLogVersion });
+ return state;
+ }
+ }
+ const reply = await api(path + (mark && '?' + mark));
+ if (local) sentStates.set(board.id, { state: reply.state, sequence: reply.state.sequence, version: reply.eventLogVersion });
+ return reply.state;
+}
+
+/** Whether a board state already carries every item's detail, as exports and event replays do. */
+const fullItems = (project) => project.items.every((item) => Array.isArray(item.history));
+
+/** Text available locally for an item before the API searches criteria omitted from summaries. */
+const searchedText = (item) => ('#' + item.id + ' ' + item.title + ' ' + item.lane + ' ' + item.specs.join(' ') + ' ' + (item.criterion || '')).toLowerCase();
+
+/** Whether the board has a gap in its retained events or an item event newer than a detail read. */
+function movedSince(project, id, cursor) {
+ const events = project.events || [];
+ if (!events.length || events[0].event_id <= cursor) return false;
+ if (events.at(-1).event_id > cursor + 1) return true;
+ return events.some((event) => event.event_id > cursor && event.item_id === id);
+}
+
+/** Load one opened item's omitted fields, retaining them only while its summary and event cursor stay current. */
+function detailOf(project, item, ask, root = view.root) {
+ if (Array.isArray(item.history)) return { item };
+ const drawnRoot = view.root, key = root + '\\n' + item.id, summary = JSON.stringify(item);
+ const kept = itemDetails.get(key);
+ /** Keep the prior detail visible during a refresh, or return the short initial loading state. */
+ const waiting = (entry) => (entry?.shown ? { item: { ...item, ...entry.shown } } : { loading: true });
+ if (kept?.loading) return waiting(kept);
+ if (kept && kept.summary === summary && !movedSince(project, item.id, kept.cursor) && !(ask && kept.error && Date.now() - kept.failedAt >= 2_500)) {
+ return kept.error ? { error: kept.error } : { item: { ...item, ...kept.detail } };
+ }
+ if (!ask) return waiting(kept && { shown: kept.detail });
+ const entry = { loading: true, summary, cursor: project.events?.[0]?.event_id ?? 0, detail: null, error: null, shown: kept?.detail ?? null };
+ itemDetails.set(key, entry);
+ detailRead = api(boardPath(root) + '/items/' + encodeURIComponent(String(item.id))).then((reply) => { entry.detail = reply.item; },
+ // A failed read is not the answer: while this item stays open it reads again in 3 s, so a dropped request recovers (#908).
+ (error) => { entry.error = String(error.message || error); entry.failedAt = Date.now(); setTimeout(() => { if (view.root === drawnRoot && view.item === item.id) render(); }, 3_000); }).finally(() => {
+ entry.loading = false;
+ if (view.root === drawnRoot && ((root === view.root && view.item === item.id) || view.tab === 'roadmap')) render();
+ });
+ return waiting(entry);
+}
+
+/** Search full snapshots locally and summary states through the API, once per query and board. */
+function searchIds(project, words) {
+ const query = words.trim().toLowerCase();
+ const local = new Set(project.items.filter((item) => searchedText(item).includes(query)).map((item) => item.id));
+ if (!query || fullItems(project) || data.root !== view.root) return local;
+ const root = view.root, key = root + '\\n' + query;
+ const kept = itemSearches.get(key);
+ if (kept) return kept.ids || local;
+ const entry = { ids: null };
+ itemSearches.set(key, entry);
+ api(boardPath(root) + '/items?q=' + encodeURIComponent(query)).then((reply) => {
+ entry.ids = new Set(reply.ids);
+ if (view.root !== root || $('q').value.trim().toLowerCase() !== query) return;
+ render();
+ if (!$('find-results').hidden) showFound();
+ }, () => {
+ if (itemSearches.get(key) === entry) itemSearches.delete(key);
+ });
+ return local;
+}
+
+// Keep credential metadata apart from board snapshots and scoped to the selected project (H2,H9).
+const credentials = new Map();
+
+/** Draw only allowlisted credential metadata; bearer values never enter page state or markup. */
+function renderCredentials() {
+ const region = $('credentials');
+ region.hidden = snapshot || readOnly;
+ if (region.hidden) { region.innerHTML = ''; return; }
+ const state = credentials.get(view.root);
+ /** Render an inventory timestamp without shortening its date or timezone. */
+ const stamp = (value) => value === null ? 'Unknown' : new Date(value).toISOString();
+ region.innerHTML = '<button class="link" data-credentials type="button" aria-expanded="' + Boolean(state) + '"' + (state?.busy ? ' disabled' : '') + '>Agent credentials</button>'
+ + (state ? '<p role="status">' + esc(state.message || '') + '</p>'
+ + state.tokens.map((row) => '<article class="credential" data-token-id="' + esc(row.id) + '"><b>' + esc(agentName(row.agent)) + '</b><code>' + esc(row.id) + '</code>'
+ + '<dl><dt>Created</dt><dd>' + esc(stamp(row.created)) + '</dd><dt>Expires</dt><dd>' + esc(stamp(row.expires)) + '</dd></dl>'
+ + (row.revoked ? '<span class="chip">Revoked</span>' : '<button class="ghost" type="button" data-revoke-token="' + esc(row.id) + '"' + (state.busy ? ' disabled' : '') + '>Revoke</button>') + '</article>').join('') : '');
+}
+
+/** Load this board's public metadata on demand, without granting any person authority. */
+async function loadCredentials(root = view.root) {
+ if (snapshot || relayProject(root) || (!hosted.local && pageReadOnly)) return;
+ const state = credentials.get(root) || { tokens: [], message: '', busy: false };
+ credentials.set(root, state);
+ state.message = 'Loading agent credentials…';
+ if (root === view.root) renderCredentials();
+ try {
+ const reply = await api(boardPath(root) + '/tokens');
+ state.tokens = reply.tokens.map(({ id, agent, created, expires, revoked }) => ({ id, agent, created, expires, revoked }));
+ state.message = state.tokens.length ? '' : 'No agent credentials.';
+ } catch (error) { state.message = String(error.message || error); }
+ if (root === view.root) renderCredentials();
+}
+
+/** Revoke a listed id through the existing one-tap phone grant, then reread its public metadata. */
+async function revokeCredential(id) {
+ if (snapshot || relayProject(view.root) || (!hosted.local && pageReadOnly)) return;
+ const root = view.root, state = credentials.get(root);
+ if (!state || state.busy || !state.tokens.some((row) => row.id === id && !row.revoked)) return;
+ state.busy = true;
+ state.message = 'Approve revocation on your phone…';
+ renderCredentials();
+ try {
+ const result = await api(boardPath(root) + '/tokens', { id });
+ if (result.id !== id || result.revoked !== true) throw new Error('Revocation was not acknowledged; refresh the credential list.');
+ state.tokens = state.tokens.map((row) => row.id === id ? { ...row, revoked: true } : row);
+ await loadCredentials(root);
+ state.message = 'Credential revoked.';
+ } catch (error) { state.message = String(error.message || error); }
+ state.busy = false;
+ if (root === view.root) renderCredentials();
+}
+
+/**
+ * A board read as text with its clock readings blanked: the flow's observation time (asOf) and each queue's oldest age
+ * (ageMinutes) are stamped afresh on every read, so two reads that differ only there show the same board (#644).
+ * Matching whole JSON keys is safe: a quote inside any string value is escaped, so no title can look like one.
+ */
+function boardText(state) {
+ return JSON.stringify(state).replace(/"(asOf|ageMinutes)":(?:"[^"]*"|[-+.0-9eE]+|null)/g, '"$1":null');
+}
+
+/** Show each queue's oldest age from the board on hand in place: the one thing on the page that moves with the clock alone. */
+function showFlowAges() {
+ const flow = data?.project?.proofStats?.flow;
+ if (!flow) return;
+ for (const node of document.querySelectorAll('#proof-stats [data-oldest]')) {
+ const oldest = flow.queues[node.dataset.oldest]?.oldest;
+ node.dataset.value = oldest?.ageMinutes ?? '';
+ node.textContent = oldestLine(oldest);
+ }
+}
+
+/** Refresh from API v1, every board or only those in fresh, and discard a response for a project the person left. */
+`;
+}
diff --git a/src/view/page-script-4.js b/src/view/page-script-4.js
new file mode 100644
index 00000000..9d974dc5
--- /dev/null
+++ b/src/view/page-script-4.js
@@ -0,0 +1,1121 @@
+/**
+ * Part 4 of the hosted page's script, verbatim from src/cockpit.js lines 2886-3996 (#745): its
+ * text is what the page served before the split, with the values its ${} expressions read passed in as scope.
+ *
+ * @param {Record<string, any>} scope - The values cockpitPage passes for the names this part interpolates.
+ * @returns {string} The script text of this part.
+ */
+export function pageScriptPart4(scope) {
+return `function showFlow(shown) {
+ keep('pb.flow', shown ? 'shown' : 'hidden');
+ $('flow-panel').hidden = !shown;
+ $('flow-show').hidden = shown;
+ if (shown && data && data.project) $('flow').innerHTML = flowSvg(data.project);
+}
+
+function showTab() {
+ document.querySelectorAll('[data-pane]').forEach((pane) => { pane.hidden = pane.dataset.pane !== view.tab; });
+ document.querySelectorAll('.tab').forEach((button) => button.classList.toggle('on', button.dataset.tab === view.tab));
+ countUnseen();
+ if (view.tab === 'shouts') foldShouts();
+}
+
+/** Read the selected repo, tab and detail from a path or the hosted page's fragment. */
+function placeAtAddress(page = data) {
+ const tabs = ['items', 'shouts', 'spec', 'doctrine', 'activity', 'roadmap'];
+ const hash = location.hash || '';
+ let path = routed ? location.pathname || '/' : hash.slice(1);
+ if (hash === '#items/pipeline' || hash === '#roadmap') path = hash.slice(1);
+ if (hash.startsWith('#shout-')) path = 'shouts/' + hash.slice(7);
+ let parts;
+ try { parts = path.split('/').filter(Boolean).map(decodeURIComponent); }
+ catch { parts = []; }
+ const repo = page?.projects.find((entry) => entry.ok && entry.name === parts[0]);
+ const group = page?.groups.find((entry) => entry.name === parts[0]);
+ const named = (repo || group) && tabs.includes(parts[1]);
+ const root = named ? repo?.root || group.key : null;
+ if (named) parts.shift();
+ const tab = tabs.includes(parts[0]) ? parts.shift() : (!path && transportModule && globalThis.history?.state?.tab) || homeTab();
+ return { root, tab, detail: parts[0] ?? null };
+}
+
+/** Name each repo even beneath a group; one repo needs no prefix. */
+function tabHref(tab) {
+ if (snapshot) {
+ const detail = tab === 'items' && view.itemsView === 'pipeline' ? 'pipeline' : view.addressDetail;
+ if (tab === 'items' && detail === null && !location.hash) return location.pathname + location.search;
+ return location.pathname + location.search + '#' + tab + (detail === null ? '' : '/' + encodeURIComponent(String(detail)));
+ }
+ const repo = data?.projects.find((entry) => entry.root === view.root);
+ const group = data?.groups.find((entry) => entry.key === view.root);
+ const name = repo?.name || group?.name;
+ const prefix = (data?.projects.filter((entry) => entry.ok).length || 0) > 1 && name ? '/' + encodeURIComponent(name) : '';
+ const detail = tab === 'items' && view.itemsView === 'pipeline' && (view.addressDetail === null || view.addressDetail === 'pipeline') ? 'pipeline' : view.addressDetail;
+ const path = prefix + '/' + tab + (detail === null ? '' : '/' + encodeURIComponent(String(detail)));
+ return routed ? path + location.search : location.pathname + location.search + '#' + path.slice(1);
+}
+
+/** Push one entry per changed place, and retain native fact anchors when restoring an entry. */
+function address(push = true) {
+ if (typeof history === 'undefined' || typeof location === 'undefined' || !addressReady) return;
+ const state = { tab: view.tab, root: view.root, item: view.item, itemsView: view.itemsView, detail: view.addressDetail };
+ let href = tabHref(view.tab);
+ if (!push && routed && location.hash && !['#roadmap', '#items/pipeline'].includes(location.hash)) href += location.hash;
+ try {
+ if (push && href !== location.pathname + location.search + (location.hash || '')) history.pushState(state, '', href);
+ else if (transportModule && !location.hash && view.tab === 'items' && view.addressDetail === null) history.replaceState(state, '');
+ else history.replaceState(state, '', href);
+ } catch { /* A host that refuses history changes still shows the selected place. */ }
+}
+
+/** Apply a parsed selection without recording another history entry. */
+function applyPlace(place, kept = null) {
+ if (place.root) view.root = place.root;
+ view.tab = place.tab;
+ view.addressDetail = place.detail;
+ view.item = place.tab === 'items' && place.detail !== null && place.detail !== 'pipeline' ? Number(place.detail) : null;
+ view.itemsView = place.tab === 'items' && place.detail === 'pipeline' ? 'pipeline' : 'list';
+ if (place.tab === 'items' && kept?.root === view.root && kept.tab === place.tab && kept.detail === place.detail && kept.itemsView === 'pipeline') view.itemsView = 'pipeline';
+ view.shout = place.tab === 'shouts' && place.detail !== null ? Number(place.detail) : null;
+ view.agent = null;
+ view.unread = null;
+ view.roadmapOnly = null;
+ if (place.tab === 'spec' || place.tab === 'doctrine') {
+ view.row[place.tab] = place.detail;
+ if (place.detail !== null) view.rows[place.tab] = 'all';
+ }
+ view.scrollPlace = place.detail !== null;
+ keep('pb.project', view.root);
+ if (place.tab !== 'roadmap') keep('pb.tab', place.tab);
+}
+
+/** Restore the address on Back and Forward, with a scoped refresh when the repo changes. */
+function fromAddress(event) {
+ if (!data) return;
+ // Back and Forward close Approve all's confirmation and the decline dialog without recording, wherever they lead.
+ leaveDialogs();
+ // The configured relay transport owns pairing fragments and removes their secrets itself.
+ if (transportModule) {
+ const pairing = new URLSearchParams((location.hash || '').slice(1));
+ if (['board', 'key', 'device'].some((name) => pairing.has(name))) return;
+ }
+ if (snapshot) {
+ const kept = event?.state || {};
+ const place = location.hash ? placeAtAddress() : { root: null, tab: kept.tab || homeTab(), detail: kept.detail ?? null };
+ applyPlace(place, kept);
+ if (kept.root && kept.root !== view.root) return switchTo(kept.root, view.item, false);
+ } else {
+ const place = placeAtAddress();
+ // A native timeline anchor keeps its existing DOM target and the browser's own scroll.
+ if ((location.hash || '').startsWith('#fact-') && place.tab === 'items' && (!place.root || place.root === view.root) && (place.detail === null || Number(place.detail) === view.item)) { address(false); return; }
+ const previous = view.root;
+ applyPlace(place, event?.state);
+ if (previous !== view.root) return switchTo(view.root, view.item, false);
+ }
+ address(false);
+ render();
+ void loadAddressedShout();
+}
+
+/** Pick a tab or an explicit detail and record the complete place once. */
+function openTab(tab, detail = null) {
+ view.tab = tab;
+ view.addressDetail = detail;
+ view.shout = tab === 'shouts' && detail !== null ? Number(detail) : null;
+ view.scrollPlace = detail !== null;
+ if (tab !== 'roadmap') keep('pb.tab', tab);
+ address();
+}
+
+/** Fetch one old shout through the same public read API used by local and relay views. */
+async function loadAddressedShout() {
+ if (!data?.project || view.tab !== 'shouts' || view.shout === null || data.root !== view.root) return;
+ const root = view.root, id = view.shout, key = JSON.stringify([root, id]);
+ if (data.project.shouts.some((entry) => entry.shout_id === id) || addressedShouts.has(key)) return;
+ const entry = { shout: null, error: null };
+ addressedShouts.set(key, entry);
+ try {
+ const reply = await api(boardPath(root) + '/shouts/' + encodeURIComponent(String(id)));
+ entry.shout = reply.shout;
+ } catch (error) {
+ const message = String(error.message || error);
+ entry.error = relayProject(root) && !message.includes('NO_SHOUT')
+ ? 'This shout is older than the relay holds. Open its address in the local project view.'
+ : 'No shout #' + id + ' exists here. ' + message;
+ }
+ if (view.root === root && view.shout === id && view.tab === 'shouts') render();
+}
+
+/** Scroll a newly addressed detail once, after its real content has arrived. */
+function revealPlace() {
+ if (!view.scrollPlace) return;
+ const fact = view.tab === 'items' && (location.hash || '').startsWith('#fact-') ? $(location.hash.slice(1)) : null;
+ const element = fact || (view.tab === 'shouts' ? $('shout-' + view.shout)
+ : view.tab === 'items' ? $('detail')
+ : ['spec', 'doctrine'].includes(view.tab) ? $(view.tab + '-detail') : null);
+ if (!element || (view.tab === 'shouts' && !element.querySelector('h2'))) return;
+ element.scrollIntoView({ block: 'center', behavior: 'instant' });
+ view.scrollPlace = false;
+}
+
+/**
+ * Count on the Shouts tab the shouts that came after the newest one the person has seen in this
+ * project. Seeing means having the Shouts tab open with the board drawn; a project shown for the
+ * first time has seen everything so far. The mark is kept in this browser, so a reload counts
+ * nothing old. The board counts the shouts since the mark the last refresh sent, so a burst larger
+ * than the forty loaded still counts in full; until a moved mark reaches the board, the loaded
+ * shouts count, which is exact then since the mark only ever moves to the newest.
+ */
+function countUnseen() {
+ const p = data && data.project;
+ // While a switch loads, the board on hand is the last project's: it marks nothing for this one.
+ if (!p || data.root !== view.root) return;
+ const key = 'pb.seen.' + view.root;
+ const kept = view.seen[key] ?? keep(key);
+ const newest = p.shouts.length ? p.shouts[0].shout_id : 0;
+ const seen = view.tab === 'shouts' || kept === null || kept === undefined ? newest : Number(kept);
+ if (String(seen) !== String(kept)) { view.seen[key] = seen; keep(key, String(seen)); }
+ const unread = (p.unseen && p.unseen.since === seen ? p.unseen.count : p.shouts.filter((x) => x.shout_id > seen).length) || 0;
+ const slot = $('status-unread');
+ if (slot) { slot.innerHTML = '<b>' + unread + '</b> unread'; slot.hidden = !unread; }
+}
+
+/** A quiet line that opens what it counts: what it says, everything it holds on hover, and show or hide. */
+function foldLine(name, text, names) {
+ return '<button class="fold-line" data-fold="' + name + '" type="button" aria-expanded="' + Boolean(view.open[name]) + '" title="' + esc(names) + '"><span>' + esc(text) + '</span><span class="fold-more">' + (view.open[name] ? 'hide' : 'show') + '</span></button>';
+}
+
+/**
+ * Address the composer: the coordinator unless someone else is named, who then shows as a chip the person can clear.
+ */
+function addressTo(to) {
+ const who = to || 'coordinator';
+ $('shout-to').value = who;
+ $('shout-to-chip').hidden = who === 'coordinator';
+ $('shout-to-chip').innerHTML = who === 'coordinator' ? '' : 'to <b>' + esc(agentName(who)) + '</b><button class="to-clear" data-to-clear type="button" aria-label="Shout to the coordinator instead">×</button>';
+ $('shout-text').placeholder = 'Shout to ' + (who === 'coordinator' ? 'the coordinator' : agentName(who));
+}
+
+/**
+ * Put the shout form in answer mode for an open decision (B21), or back to a plain shout with null.
+ * The form is never redrawn, so what the person types survives every refresh; only its answer line,
+ * its To and its button change. The To the person had comes back when the answer is done. An answer
+ * belongs to the project whose question it shows: leaving that project leaves answer mode.
+ */
+function answer(id) {
+ const ask = id === null ? null : data.project.decisions.find((d) => d.shout_id === id) || null;
+ if (ask && !view.answering) view.to = $('shout-to').value;
+ if (!ask && view.answering) addressTo(view.to);
+ view.answering = ask ? { root: view.root, id: ask.shout_id } : null;
+ $('answering').hidden = !ask;
+ $('answering-who').textContent = ask ? agentName(ask.shout_from) : '';
+ const question = ask ? linked(ask.shout_text, new Map(data.project.items.map((i) => [String(i.id), i.title]))) : '';
+ if (question.includes('<a class="ref"')) $('answering-q').innerHTML = question;
+ else $('answering-q').textContent = ask ? ask.shout_text : '';
+ if (ask) addressTo(ask.shout_from);
+ $('shout-to').disabled = Boolean(ask);
+ $('shout-to-chip').hidden = Boolean(ask) || $('shout-to').value === 'coordinator';
+ const verb = ask ? 'Answer' : 'Shout';
+ $('shout-send').setAttribute('aria-label', verb);
+ $('shout-send').title = verb + ' (Enter; Shift+Enter for a new line)';
+ if (ask) $('shout-text').focus();
+}
+
+/** Open what a status-bar part counts: its tab, narrowed to exactly those. */
+function statusGo(to) {
+ view.unread = null;
+ view.roadmapOnly = null;
+ if (to.startsWith('item:')) return go(to);
+ if (to === 'items') { view.state = 'active'; view.lane = null; view.before = null; $('q').value = ''; openTab('items'); }
+ else if (to === 'verify' || to === 'gated') { view.state = to; view.lane = null; view.before = null; $('q').value = ''; openTab('items'); }
+ else if (to === 'unread') {
+ // Only the shouts after the mark the person had; opening Shouts then moves the mark past them.
+ const key = 'pb.seen.' + view.root;
+ view.unread = { root: view.root, after: Number(view.seen[key] ?? keep(key) ?? 0) };
+ view.agent = null;
+ openTab('shouts');
+ }
+ // The agents it counts are the panel's rows, so it opens the panel even where the person hid it.
+ else if (to === 'agents') { view.agentsHidden = false; keep('pb.agents', 'shown'); view.agent = null; openTab('shouts'); }
+ // The release it counts is one milestone, so the Roadmap opens on that one alone.
+ else if (to === 'release') { view.roadmapOnly = nextMilestone(data.project)?.name ?? null; openTab('roadmap'); }
+ else openTab(to);
+ showTab();
+ render();
+}
+
+/**
+ * Follow a link in the page: an item, a spec row, a tab or a decision to answer. An item can live on
+ * another project's board, root, which the page then switches to.
+ */
+function go(target, root = view.root) {
+ const [kind, id] = target.split(':');
+ let tab = view.tab;
+ if (kind === 'item') { tab = 'items'; view.state = 'all'; view.before = null; }
+ else if (kind === 'spec') { tab = 'spec'; view.row.spec = id; view.rows.spec = 'all'; }
+ else if (kind === 'doctrine') { tab = 'doctrine'; view.row.doctrine = id; view.rows.doctrine = 'all'; }
+ else if (kind === 'shout') { tab = 'shouts'; view.agent = null; view.unread = null; }
+ else if (kind === 'tab') tab = id;
+ else if (kind === 'decide') { tab = 'shouts'; answer(Number(id)); }
+ if (kind === 'item') { view.tab = 'items'; view.itemsView = 'list'; pick(Number(id), root); }
+ else { openTab(tab, ['spec', 'doctrine', 'shout'].includes(kind) ? id : null); render(); }
+ if (kind === 'shout') void loadAddressedShout();
+}
+
+/** An item's state as a word, for a search result. */
+const stateLabel = (i) => ({ building: 'building', verify: 'to verify', verified: 'verified', back: 'sent back', open: 'open', withdrawn: 'withdrawn' })[stateOf(i)] || stateOf(i);
+
+/** A shout's kind as a word, for a search result. */
+const shoutKind = (x) => (x.shout_decision ? 'decision' : x.shout_answers ? 'answer' : x.shout_evidence_kind ? 'evidence' : 'shout');
+
+/** Everything on the board that matches the top bar's words: items, Spec rows, Doctrine rules and shouts, newest first. */
+function findAll(words) {
+ const p = data?.project, q = words.trim().toLowerCase();
+ if (!p || !q) return [];
+ const has = (...parts) => parts.join(' ').toLowerCase().includes(q);
+ const ids = searchIds(p, q);
+ const items = p.items.filter((item) => ids.has(item.id))
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).map((item) => ({ go: 'item:' + item.id, id: '#' + item.id, text: item.title, note: stateLabel(item) }));
+ // A Spec row or Doctrine rule is as new as the commit that added it (0 not yet committed; a standard rule, never added
+ // here, last); rows one commit added together read newest first by their place in the file.
+ const rows = (kind, list) => list.map((r, at) => ({ r, at })).filter(({ r }) => has(r.id, r.text))
+ .sort((a, b) => (a.r.added ?? Infinity) - (b.r.added ?? Infinity) || b.at - a.at)
+ .map(({ r }) => ({ go: kind + ':' + r.id, id: r.id, text: r.text, note: r.stage || r.status }));
+ const shouts = p.shouts.filter((x) => has(x.shout_from, x.shout_to, x.shout_text)).map((x) => ({ go: 'shout:' + x.shout_id, id: '#' + x.shout_id, text: firstLine(x.shout_text), note: shoutKind(x) }));
+ return [['Items', items], ['Spec', rows('spec', p.spec)], ['Doctrine', rows('doctrine', p.practice)], ['Shouts', shouts]].filter(([, list]) => list.length);
+}
+
+/** Draw the search's results under it: up to five a group, the highlighted one ready for Enter. */
+function showFound() {
+ const box = $('find-results'), words = $('q').value;
+ const groups = findAll(words);
+ view.found = groups.flatMap(([, list]) => list.slice(0, 5));
+ view.foundAt = Math.min(view.foundAt || 0, Math.max(0, view.found.length - 1));
+ let n = 0;
+ box.innerHTML = groups.length ? groups.map(([name, list]) => '<h4>' + name + '<span>' + (list.length > 5 ? '5 of ' + list.length : list.length) + '</span></h4>'
+ + list.slice(0, 5).map((hit) => '<button class="find-hit' + (n++ === view.foundAt ? ' on' : '') + '" data-find="' + esc(hit.go) + '" type="button" role="option"><code>' + esc(hit.id) + '</code><span>' + esc(hit.text) + '</span><small>' + esc(hit.note) + '</small></button>').join('')).join('')
+ : '<div class="find-empty">Nothing on this board matches “' + esc(words.trim()) + '”.</div>';
+ box.hidden = !words.trim();
+ box.dataset.why = box.hidden ? 'no words' : '';
+}
+
+/** Put the search's results away, and say why on the box, so whoever finds them gone can name what closed them. */
+function hideFound(why) {
+ $('find-results').hidden = true;
+ $('find-results').dataset.why = why;
+}
+
+/** Open what a result names, and put the results away. */
+function openFound(target) {
+ hideFound('opened');
+ $('q').blur();
+ go(target);
+}
+
+/** Show an item's detail, on another project's board when root names one. */
+function pick(id, root = view.root) {
+ view.adding = false;
+ if (root !== view.root) return switchTo(root, id);
+ if (itemDetails.get(root + '\\n' + id)?.error) itemDetails.delete(root + '\\n' + id);
+ view.tab = 'items';
+ keep('pb.tab', view.tab);
+ view.item = id;
+ view.addressDetail = String(id);
+ address();
+ render();
+ reveal();
+}
+
+/** Where the list and the detail stack (under 900px), bring the detail into view. */
+function reveal() {
+ if (matchMedia('(max-width: 900px)').matches) $('detail').scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' });
+}
+
+/**
+ * A search looks through every state. Each keystroke with text in the box selects All, even after a
+ * chip was clicked mid-search; emptying the box brings back the chip from before the search began.
+ */
+function search() {
+ if ($('q').value.trim()) {
+ if (view.before == null) view.before = view.state;
+ view.state = 'all';
+ } else if (view.before != null) {
+ view.state = view.before;
+ view.before = null;
+ }
+ render();
+}
+
+/**
+ * Open or close the code a path:lines@commit reference names (B23). The first open asks the view for
+ * those lines as they were at that commit; the answer stays with the page, so every refresh redraws
+ * it, and a failed ask is tried again on the next open.
+ */
+async function code(ref, before) {
+ const c = (view.code[view.root + '\\n' + before + '\\n' + ref] ??= { open: false });
+ c.open = !c.open;
+ render();
+ if (!c.open || c.lines) return;
+ c.error = null;
+ if (snapshot) {
+ c.error = 'Source code is not included in this relay snapshot; open the reference in the local project view.';
+ render();
+ return;
+ }
+ if (relayProject(view.root)) {
+ c.error = 'Source code is unavailable in a relay view; open this reference in the local project view.';
+ render();
+ return;
+ }
+ try {
+ const reply = await api(boardPath(view.root) + '/code?ref=' + encodeURIComponent(ref) + '&before=' + encodeURIComponent(before));
+ Object.assign(c, reply.code);
+ } catch (error) {
+ c.error = String(error.message || error);
+ }
+ render();
+}
+
+/** Fetch the rest of a bounded local reference in API-sized windows after an explicit request. */
+async function showAllCode(ref, before) {
+ const root = view.root;
+ const c = view.code[root + '\\n' + before + '\\n' + ref];
+ const parts = codeReferenceParts(ref);
+ if (!c || c.allLoading) return;
+ if (relayProject(root)) { c.error = 'Source code is unavailable in a relay view; open this reference in the local project view.'; render(); return; }
+ if (!parts) { c.error = 'Code reference has an invalid path, range or commit SHA.'; render(); return; }
+ c.error = null;
+ c.allLoading = true;
+ render();
+ try {
+ const lines = [];
+ for (let from = parts.from; from <= parts.to; from += 60) {
+ const to = Math.min(parts.to, from + 59);
+ const pageRef = parts.path + ':' + from + (to === from ? '' : '-' + to) + '@' + parts.commit;
+ const page = await api(boardPath(root) + '/code?ref=' + encodeURIComponent(pageRef) + '&before=' + encodeURIComponent(before));
+ lines.push(...page.code.lines);
+ }
+ if (lines.length !== parts.to - parts.from + 1) throw new Error('The local view returned an incomplete code range.');
+ c.allLines = lines;
+ c.all = true;
+ } catch (error) {
+ c.error = String(error.message || error);
+ } finally {
+ c.allLoading = false;
+ render();
+ }
+}
+
+/** Return an expanded preview to its first bounded window without closing the reference. */
+function showLessCode(ref, before) {
+ const c = view.code[view.root + '\\n' + before + '\\n' + ref];
+ if (!c) return;
+ c.all = false;
+ render();
+}
+
+/** Translate person actions into their public literal intent and a familiar command label. */
+function pageMove(command, args = {}) {
+ /** Trim form values before constructing the move and its display label. */
+ const text = (value) => String(value || '').trim();
+ if (command === 'add') {
+ const fields = { lane: text(args.lane), title: text(args.title) };
+ const label = ['add', fields.lane, fields.title];
+ for (const name of ['criterion', 'specs', 'brief']) if (text(args[name])) { fields[name] = text(args[name]); label.push('--' + name, fields[name]); }
+ return { body: { verb: 'add', args: fields }, label: label.join(' ') };
+ }
+ if (command === 'shout') return { body: { verb: 'shout', args: { to: text(args.to), text: text(args.text) } }, label: ['shout', text(args.to), text(args.text)].join(' ') };
+ if (command === 'answer') return { body: { verb: 'answer', item: Number(args.id), args: { text: text(args.text), as: 'person' } }, label: ['answer', text(args.id), text(args.text), '--as', 'person'].join(' ') };
+ if (command === 'hold') return { body: { verb: 'hold', args: { lane: text(args.lane), reason: text(args.reason) } }, label: ['hold', text(args.lane), '--reason', text(args.reason)].join(' ') };
+ if (command === 'release') return { body: { verb: 'hold', args: { lane: text(args.lane), off: true } }, label: ['hold', text(args.lane), '--off'].join(' ') };
+ if (command === 'spec-approve') {
+ const ids = text(args.ids);
+ if (!ids) throw new Error('Choose at least one spec row to approve.');
+ return { body: { verb: 'spec-approve', args: { ids } }, label: 'spec approve ' + ids };
+ }
+ if (command === 'spec-decline') {
+ const ids = text(args.ids), reason = text(args.reason);
+ if (!ids || !reason) throw new Error('Choose a spec row and enter a reason to decline it.');
+ return { body: { verb: 'spec-decline', args: { ids, reason } }, label: 'spec decline ' + ids + ' --reason ' + reason };
+ }
+ throw new Error('No view action ' + String(command) + '; choose add, shout, answer, hold or release.');
+}
+
+/** Describe an API-confirmed move without exposing its transport document in the page. */
+function moveMessage(move, result) {
+ if (move.verb === 'add') return 'added #' + result.item.item_id;
+ if (move.verb === 'shout') return 'shouted to ' + move.args.to;
+ if (move.verb === 'answer') return 'answered #' + move.item;
+ if (move.verb === 'spec-approve') return 'approved rows ' + move.args.ids + ' (pending apply)';
+ if (move.verb === 'spec-decline') return 'declined rows ' + move.args.ids + ' (pending apply)';
+ return move.args.off ? 'released the ' + move.args.lane + ' lane' : 'holding the ' + move.args.lane + ' lane: ' + move.args.reason;
+}
+
+/** Render escaped decision feedback beside the affected Spec row (B26, N26). */
+function specFeedback(feedback) {
+ return '<div class="spec-feedback ' + feedback.tone + '" role="status">' + esc(feedback.text) + '</div>';
+}
+
+/** Ask why a Spec row or Doctrine rule is declined; the reason, once given, is recorded where it was asked. */
+function askDecline(kind, id, from) {
+ view.declining = id;
+ view.declineKind = kind;
+ view.declineFrom = from;
+ // The dialog belongs to the board it was opened on, as Approve all's confirmation does (#612).
+ view.declineRoot = view.root;
+ $('spec-decline-title').textContent = 'Decline ' + id;
+ $('spec-decline-reason').value = '';
+ openModal($('spec-decline-dialog'), $('spec-decline-reason'));
+}
+
+/**
+ * Close the decline dialog and return what it asked about. Closed by the person, focus returns to the list it was asked
+ * from; closed because the page left its board, focus stays where the person put it.
+ */
+function closeDecline(left = false) {
+ const asked = view.declining ? { id: view.declining, kind: view.declineKind, root: view.declineRoot, from: view.declineFrom } : null;
+ view.declining = null;
+ closeModal($('spec-decline-dialog'));
+ if (!left && asked?.from === 'list') $(asked.kind + '-list').focus({ preventScroll: true });
+ return asked;
+}
+
+/**
+ * Ask in the page before one press approves every undecided row of a Spec section (B26, N26). The browser's own confirm
+ * dialog can be dismissed or never shown, and then the press recorded nothing and said nothing; this one is the page's.
+ */
+function askApproveAll(section) {
+ const ids = data.project.spec.filter((row) => row.section === section && ['pending', 'draft'].includes(row.status) && !row.decision).map((row) => row.id);
+ // Every row was decided after the last redraw; this one drops the stale control.
+ if (!ids.length) { render(); return; }
+ // The confirmation belongs to the board it was opened on: its rows are that board's, and only that board records them.
+ view.approvingAll = { root: view.root, section, ids };
+ $('spec-approve-title').textContent = 'Approve all ' + ids.length + (ids.length === 1 ? ' undecided row in “' : ' undecided rows in “') + section + '”?';
+ $('spec-approve-rows').textContent = 'Rows: ' + ids.join(', ');
+ $('spec-approve-submit').textContent = 'Approve ' + ids.length + (ids.length === 1 ? ' row' : ' rows');
+ openModal($('spec-approve-dialog'), $('spec-approve-submit'));
+}
+
+/**
+ * Close the Approve all confirmation. Cancelled, focus returns to the section control that opened it; approved, to the
+ * list, since the section's control leaves once its rows are decided. Closed because the page left its board, focus
+ * stays where the person put it.
+ */
+function closeApproveAll(approved = false, left = false) {
+ const asked = view.approvingAll;
+ view.approvingAll = null;
+ closeModal($('spec-approve-dialog'));
+ if (left) return asked;
+ const control = !approved && asked && [...$('spec-list').querySelectorAll('[data-section-approve]')].find((button) => button.dataset.sectionApprove === asked.section);
+ (control || $('spec-list')).focus({ preventScroll: true });
+ return asked;
+}
+
+/** Close, recording nothing, a confirmation or decline opened on another board than the one the page now shows. */
+function closeIfLeft() {
+ if (view.approvingAll && view.approvingAll.root !== view.root) closeApproveAll(false, true);
+ if (view.declining && view.declineRoot !== view.root) closeDecline(true);
+}
+
+/** Close every dialog bound to a board, recording nothing: the page is leaving the board it was asked on. */
+function leaveDialogs() {
+ if (view.approvingAll) closeApproveAll(false, true);
+ if (view.declining) closeDecline(true);
+}
+
+/**
+ * Show a page dialog over an inert page: nothing behind it takes a click or focus while it is open, so the person
+ * cannot act on the page, or switch the board, under a question the page is asking.
+ */
+function openModal(dialog, focus) {
+ openPageDialog(dialog, focus, pageDialogs);
+}
+
+/** Hide a page dialog and give the page back its clicks and focus. */
+function closeModal(dialog) {
+ if (closePageDialog(dialog, pageDialogs) && deferredClickRender) requestAnimationFrame(() => { if (!pageDialogs.size && heldClickPointer === null && deferredClickRender) { deferredClickRender = false; render(); } });
+}
+
+/** Keep Tab and Shift+Tab cycling through an open page dialog's own controls. */
+function trapFocus(event) {
+ if (event.key !== 'Tab') return;
+ const controls = [...event.currentTarget.querySelectorAll('button, input, select, textarea, a[href]')].filter((control) => !control.disabled && control.offsetParent !== null);
+ if (!controls.length) return;
+ event.preventDefault();
+ const at = controls.indexOf(document.activeElement);
+ const next = at < 0 ? (event.shiftKey ? controls.length - 1 : 0) : (at + (event.shiftKey ? controls.length - 1 : 1)) % controls.length;
+ controls[next].focus();
+}
+
+/**
+ * Record a Spec or Doctrine decision beside its row and retain the list's reading position (B26, N26). A Doctrine rule
+ * goes to the board by its qualified id, doctrine:D1, as the command line names it (pullboard spec approve doctrine:D1).
+ */
+async function decideRow(kind, command, args, anchor) {
+ if (snapshot || (readOnly && !requests)) return false;
+ const requestMode = requests;
+ const root = view.root, scroll = window.scrollY;
+ const ids = String(args.ids).split(/\s+/);
+ const prefix = kind + ':';
+ const rows = [...$(kind + '-list').querySelectorAll('[data-row]')];
+ const index = rows.findIndex((row) => row.dataset.row === prefix + ids[0]);
+ const next = rows.slice(index + 1).find((row) => !ids.includes(row.dataset.row.slice(prefix.length)))?.dataset.row.slice(prefix.length);
+ const feedback = { kind, root, id: ids[0], next, from: anchor?.closest('#' + kind + '-detail') ? 'detail' : 'list', tone: '', text: 'Recording decision…' };
+ view.specFeedback = feedback;
+ render();
+ // A waiting request keeps its row; let browser anchoring follow growth above it.
+ if (!requestMode) window.scrollTo({ top: scroll, behavior: 'instant' });
+ try {
+ const move = pageMove(command, kind === 'doctrine' ? { ...args, ids: ids.map((id) => 'doctrine:' + id).join(' ') } : args);
+ const result = requestMode ? await sendPersonRequest(root, move.body) : await api(boardPath(root) + '/moves', move.body);
+ const request = requestMode && result?.result?.request;
+ if (requestMode && (!request?.id || !['waiting', 'done', 'refused'].includes(request.status))) throw new Error('The request did not include its status; refresh the board to check it.');
+ feedback.tone = requestMode ? request.status === 'done' ? 'ok' : request.status === 'refused' ? 'no' : '' : 'ok';
+ feedback.text = requestMode ? requestNotice(request) : moveMessage(move.body, result.result);
+ if (requestMode) { feedback.requestId = request.id; feedback.status = request.status; }
+ // Decided from the list, the pick moves on to the next row before the board redraws without the decided one, so
+ // the next key decides that one.
+ if (feedback.from === 'list' && feedback.tone !== 'no' && next && view.row[kind] === ids[0] && root === view.root) view.row[kind] = next;
+ await refresh();
+ } catch (error) {
+ feedback.tone = 'no';
+ feedback.text = String(error.message || error);
+ }
+ if (root === view.root && view.specFeedback === feedback) {
+ render();
+ if (!requestMode) window.scrollTo({ top: scroll, behavior: 'instant' });
+ // A phone row click jumps to its detail. A later list-key decision returns the next pick to view,
+ // instead of restoring that detail's scroll position with the focused list still offscreen.
+ if (feedback.from === 'list' && feedback.tone === 'ok' && next && view.row[kind] === next) {
+ const picked = [...$(kind + '-list').querySelectorAll('[data-row]')].find((row) => row.dataset.row === prefix + next);
+ const rect = picked?.getBoundingClientRect();
+ // Center an offscreen pick: nearest can round a half-pixel edge just outside the viewport.
+ if (rect && (rect.top < 0 || rect.bottom > innerHeight)) picked.scrollIntoView({ block: 'center', behavior: 'instant' });
+ }
+ if (!requestMode || feedback.status === 'done') setTimeout(() => { if (view.specFeedback === feedback) { view.specFeedback = null; render(); } }, 6000);
+ }
+ return requestMode ? Boolean(feedback.requestId) && feedback.status !== 'refused' : feedback.tone === 'ok';
+}
+
+/**
+ * Run a public API move beside its action and let only the latest one own the console and timer. The move's own
+ * reply is its outcome (#748): the board is read again afterwards, but that read covers every source on a hosted
+ * page, and a slow or failing read of another board must neither hold back nor undo a move that went through.
+ */
+async function act(command, args, anchor) {
+ const out = $('console');
+ if (snapshot || (readOnly && !requests)) { out.hidden = false; out.className = 'console no'; out.textContent = snapshot ? 'This is a read-only snapshot.' : 'This is a read-only view.'; return false; }
+ const requestMode = requests;
+ // A form's result stands above its actions, or above the shout composer's bar, never inside that one row.
+ if (anchor) {
+ const target = anchor.matches('form')
+ ? anchor.querySelector('.actions') || anchor.querySelector('.composer') || anchor.querySelector('[type="submit"]') || anchor
+ : anchor.closest('#lanes') || anchor;
+ target.insertAdjacentElement(anchor.matches('form') ? 'beforebegin' : 'afterend', out);
+ }
+ const run = (view.acting = (view.acting || 0) + 1);
+ const root = view.root;
+ const latest = () => run === view.acting && root === view.root;
+ view.request = null;
+ clearTimeout(view.closing);
+ out.hidden = false;
+ out.className = 'console';
+ out.textContent = requestMode ? 'Request waiting…' : 'running…';
+ out.scrollIntoView({ block: 'nearest' });
+ try {
+ // On the local view the person's word to the coordinator is the person's own request, not a shout the
+ // coordinator sends itself; through the relay every action is already a sealed request.
+ const asked = command === 'request' && !requestMode;
+ const move = asked ? null : pageMove(command === 'request' ? 'shout' : command, command === 'request' ? { to: 'coordinator', text: args.text } : args);
+ const result = asked ? await api(boardPath(root) + '/requests', { text: String(args.text || '').trim() })
+ : requestMode ? await sendPersonRequest(root, move.body) : await api(boardPath(root) + '/moves', move.body);
+ const request = requestMode && result?.result?.request;
+ if (requestMode && (!request?.id || !['waiting', 'done', 'refused'].includes(request.status))) throw new Error('The request did not include its status; refresh the board to check it.');
+ if (latest()) {
+ out.className = 'console' + (requestMode ? request.status === 'done' ? ' ok' : request.status === 'refused' ? ' no' : '' : ' ok');
+ out.textContent = requestMode ? requestNotice(request) : asked ? 'Sent to the coordinator.' : '$ pullboard ' + move.label + '\\n' + moveMessage(move.body, result.result);
+ if (requestMode) view.request = { root, id: request.id, run };
+ out.scrollIntoView({ block: 'center' });
+ // What went through says so and then steps aside; a refusal stays until the person closes it.
+ if (!requestMode || request.status === 'done') view.closing = setTimeout(() => { if (latest()) out.hidden = true; }, 6000);
+ }
+ // The result was already revealed. A late refresh must not scroll after the person aims at the next action.
+ refresh().catch((error) => { $('live').textContent = 'offline: ' + String(error.message || error); });
+ return !requestMode || request.status !== 'refused';
+ } catch (error) {
+ if (latest()) {
+ out.className = 'console no';
+ out.textContent = String(error.message || error);
+ out.scrollIntoView({ block: 'center' });
+ }
+ return false;
+ }
+}
+
+/**
+ * Move every age on the page on to now, where it stands. A list is rebuilt only when the board
+ * changes, so a click is never lost to a rebuild; on a quiet board the ages would otherwise stay
+ * as old as the page.
+ */
+/** Shouts the person opened past their six lines, kept across refreshes. */
+const openShouts = new Set();
+
+/** Fold each shout taller than six lines, with 'more' to open it; measured only while Shouts shows. */
+function foldShouts() {
+ if ($('feed').offsetParent === null) return;
+ document.querySelectorAll('#feed .shout, #decisions .shout').forEach((card) => {
+ const text = card.querySelector('.text');
+ card.classList.add('clamp');
+ card.classList.toggle('clamp', card.classList.contains('open') || text.scrollHeight > text.clientHeight + 1);
+ });
+}
+
+function tickAges() {
+ document.querySelectorAll('[data-ago]').forEach((node) => { node.textContent = node.classList.contains('long') ? agoLong(node.dataset.ago) : ago(node.dataset.ago); });
+ tickDays();
+}
+
+/**
+ * Once the clock has passed midnight since the page named its days, rename them in place with no redraw (#644): the
+ * day that was Today and the one that was Yesterday get their names for now, and the shouts, which carry no rule above
+ * today's, get one above what is no longer today. Every other day was named by its date and stays true.
+ */
+function tickDays() {
+ const then = daysNamedAt, now = new Date();
+ if (then.toDateString() === now.toDateString()) return;
+ const before = new Date(then);
+ before.setDate(then.getDate() - 1);
+ const names = { Today: dayName(then.toISOString()), Yesterday: dayName(before.toISOString()) };
+ document.querySelectorAll('.feed .day, #feed > .day-rule span').forEach((node) => { if (names[node.textContent]) node.textContent = names[node.textContent]; });
+ const first = $('feed')?.querySelector?.('.shout');
+ if (first && !first.previousElementSibling?.classList?.contains('day-rule')) first.insertAdjacentHTML('beforebegin', '<div class="day-rule" role="separator"><span>' + names.Today + '</span></div>');
+ daysNamedAt = now;
+}
+
+/** Open or close the project list where the sidebar is folded into a top bar (under 900px). */
+function fold(open) {
+ $('side').classList.toggle('open', open);
+ $('proj-switch').setAttribute('aria-expanded', String(open));
+}
+
+/** Show another project and its item; history restores keep the tab their entry named. */
+function switchTo(root, target = null, record = true) {
+ // Switching board or project closes Approve all's confirmation and the decline dialog; neither records on either board.
+ leaveDialogs();
+ const generation = ++switchGeneration;
+ answer(null);
+ view.root = root;
+ syncBoardMode(root);
+ const item = typeof target === 'number' ? target : /^item:(\\d+)$/.exec(target || '');
+ const requestedItem = typeof item === 'number' ? item : item ? Number(item[1]) : null;
+ view.item = requestedItem;
+ view.adding = false;
+ if (record && view.item !== null) { view.tab = 'items'; keep('pb.tab', view.tab); }
+ keep('pb.project', root);
+ if (record) { view.addressDetail = requestedItem === null ? null : String(requestedItem); view.shout = null; address(); }
+ fold(false);
+ // The board that arrives is drawn even if it matches the last one seen, so the pick is made from it.
+ seen = '';
+ if (data) render();
+ document.body.classList.add('switching');
+ return refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }).finally(() => {
+ if (generation === switchGeneration) document.body.classList.remove('switching');
+ if (generation === switchGeneration && requestedItem !== null && view.item === requestedItem && view.root === root && view.tab === 'items') reveal();
+ });
+}
+
+// The Shouts tab's own controls: a folded shout's more and less, every agent or only those at work, the agents
+// panel hidden or shown, and an agent's name, which filters the feed to its shouts and addresses the composer to it.
+$('shouts-pane').addEventListener('click', (event) => {
+ if (event.target.closest('[data-credentials]')) { void loadCredentials(); return; }
+ const revoke = event.target.closest('[data-revoke-token]');
+ if (revoke) { void revokeCredential(revoke.dataset.revokeToken); return; }
+ const more = event.target.closest('[data-more]'), pick = event.target.closest('[data-agent]');
+ if (more) {
+ const card = more.closest('.shout'), id = Number(card.dataset.shoutId);
+ if (openShouts.has(id)) openShouts.delete(id); else openShouts.add(id);
+ card.classList.toggle('open', openShouts.has(id));
+ more.textContent = openShouts.has(id) ? 'less' : 'more';
+ return;
+ }
+ if (event.target.closest('[data-to-clear]')) { addressTo('coordinator'); $('shout-text').focus(); return; }
+ const folded = event.target.closest('[data-fold]');
+ if (folded) { view.open[folded.dataset.fold] = !view.open[folded.dataset.fold]; render(); return; }
+ if (event.target.closest('[data-all-agents]')) { view.allAgents = !view.allAgents; render(); return; }
+ if (event.target.closest('[data-agents-toggle]')) { view.agentsHidden = !view.agentsHidden; keep('pb.agents', view.agentsHidden ? 'hidden' : 'shown'); render(); return; }
+ if (event.target.closest('[data-unread]')) { view.unread = null; render(); return; }
+ if (!pick) return;
+ view.unread = null;
+ view.agent = pick.dataset.agent && pick.dataset.agent !== view.agent ? pick.dataset.agent : null;
+ if (!view.answering) addressTo(view.agent);
+ render();
+});
+// Enter shouts; Shift+Enter starts a new line.
+$('shout-text').addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); $('shout-form').requestSubmit(); } });
+document.addEventListener('click', (event) => {
+ // The open-board screens name their state in data-state and handle their own presses (#764).
+ if (event.target.closest('#local-note')) return;
+ if (view.filterOpen && !event.target.closest('.filter-control')) { view.filterOpen = false; render(); }
+ const t = event.target.closest('[data-filter-toggle],[data-filter-choice],[data-status],[data-roadmap-jump],[data-shout-id],[data-roadmap-key],[data-roadmap-all],[data-root],[data-tab],[data-go],[data-item],[data-items-view],[data-state],[data-rows],[data-row],[data-row-decision],[data-section-approve],[data-release],[data-shout],[data-new],[data-code],[data-code-all],[data-code-less],[data-stats-toggle],#proj-switch,#console');
+ if (!event.target.closest('.side')) fold(false);
+ if (!t) return;
+ if (t.id === 'proj-switch') { fold(!$('side').classList.contains('open')); return; }
+ if (t.id === 'console') { t.hidden = true; return; }
+ if (t.tagName === 'A' && t.dataset.go?.startsWith('item:')) {
+ if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
+ event.preventDefault();
+ }
+ if (t.dataset.statsToggle !== undefined) {
+ view.statsOpen = !view.statsOpen;
+ render();
+ $('proof-stats-summary').focus({ preventScroll: true });
+ return;
+ }
+ if (t.dataset.status) { statusGo(t.dataset.status); return; }
+ if (t.dataset.roadmapJump) { jumpToRoadmap(t.dataset.roadmapJump); return; }
+ if (t.dataset.filterToggle !== undefined) { view.filterOpen = !view.filterOpen; render(); return; }
+ if (t.dataset.filterChoice) {
+ if (t.dataset.filterKind === 'state') view.state = t.dataset.filterValue;
+ else view.lane = t.dataset.filterValue || null;
+ view.filterOpen = false;
+ render();
+ $('filter-toggle').focus({ preventScroll: true });
+ return;
+ }
+ if (t.dataset.itemsView) { view.itemsView = t.dataset.itemsView; view.addressDetail = null; address(); render(); return; }
+ if ('roadmapKey' in t.dataset) {
+ const key = t.dataset.roadmapKey;
+ view.roadmapOpen.set(JSON.stringify([view.root, key]), t.getAttribute('aria-expanded') !== 'true');
+ render();
+ [...$('roadmap').querySelectorAll('[data-roadmap-key]')].find((head) => head.dataset.roadmapKey === key)?.focus({ preventScroll: true });
+ return;
+ }
+ if ('roadmapAll' in t.dataset) { view.roadmapOnly = null; render(); return; }
+ if (t.dataset.root) switchTo(t.dataset.root, t.dataset.go || '');
+ else if (t.dataset.tab) { view.unread = null; view.roadmapOnly = null; openTab(t.dataset.tab); render(); }
+ else if (t.dataset.go) go(t.dataset.go, t.dataset.board);
+ else if (t.dataset.item) pick(Number(t.dataset.item));
+ else if (t.dataset.state) { view.state = t.dataset.state; render(); }
+ else if (t.dataset.rows) {
+ const [kind, f] = t.dataset.rows.split(':');
+ const addressed = view.addressDetail !== null;
+ view.rows[kind] = f;
+ view.addressDetail = null;
+ render();
+ if (addressed) { view.addressDetail = view.row[kind]; address(); }
+ }
+ else if (t.dataset.rowDecision) {
+ const id = t.dataset.rowId, kind = t.dataset.rowKind;
+ if (t.dataset.rowDecision === 'approve') decideRow(kind, 'spec-approve', { ids: id }, t);
+ else askDecline(kind, id, t.closest('#' + kind + '-detail') ? 'detail' : 'list');
+ }
+ else if (t.dataset.sectionApprove) askApproveAll(t.dataset.sectionApprove);
+ else if (t.dataset.shoutId && !event.target.closest('button,a,input,textarea,select')) { go('shout:' + t.dataset.shoutId); }
+ else if (t.dataset.row) {
+ const [kind, id] = t.dataset.row.split(':');
+ view.row[kind] = id;
+ view.addressDetail = id;
+ address();
+ render();
+ $(kind + '-list').focus({ preventScroll: true });
+ // Where the list and the detail stack, the picked row's detail, with its buttons, comes into view.
+ if (matchMedia('(max-width: 900px)').matches) $(kind + '-detail').scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'instant' : 'smooth' });
+ }
+ else if (t.dataset.codeAll) showAllCode(t.dataset.codeAll, t.dataset.before || '');
+ else if (t.dataset.codeLess) showLessCode(t.dataset.codeLess, t.dataset.before || '');
+ else if (t.dataset.code) code(t.dataset.code, t.dataset.before || '');
+ else if (t.dataset.release) act('release', { lane: t.dataset.release }, t);
+ else if (t.dataset.shout) { answer(null); addressTo(t.dataset.shout); $('shout-text').value = '#' + t.dataset.about + ': '; openTab('shouts'); showTab(); $('shout-text').focus(); }
+ else if (t.dataset.new !== undefined) { view.adding = true; render(); $('add-title').focus(); }
+});
+// The viewport's scroll is fired at the document; the tests' stand-in document has no window.
+document.addEventListener('scroll', updateRoadmapPanel, { passive: true });
+/** Close the expanded stats card and return focus to the list's summary control on Escape. */
+document.addEventListener('keydown', (event) => {
+ if (event.key !== 'Escape' || !view.statsOpen || view.tab !== 'items' || document.querySelector('[data-pane="items"]')?.hidden) return;
+ event.preventDefault();
+ view.statsOpen = false;
+ render();
+ $('proof-stats-summary').focus({ preventScroll: true });
+});
+/** Let a Roadmap row with independent inline links keep its keyboard button behavior. */
+document.addEventListener('keydown', (event) => {
+ if (!['Enter', ' '].includes(event.key)) return;
+ const head = event.target.closest('.milestone-head');
+ if (head && event.target === head) { event.preventDefault(); head.click(); return; }
+ const row = event.target.closest('.milestone-item[role="button"]');
+ if (event.target !== row) return;
+ event.preventDefault();
+ if (row.dataset.roadmapKey !== undefined) { row.click(); return; }
+ go(row.dataset.go, row.dataset.board || view.root);
+});
+// In a focused Spec or Doctrine list the arrow keys move the pick, and A approves the picked row and D asks why it is
+// declined, as the detail's buttons do, wherever the detail offers that decision.
+for (const kind of ['spec', 'doctrine']) $(kind + '-list').addEventListener('keydown', (event) => {
+ if (event.target !== event.currentTarget || event.metaKey || event.ctrlKey || event.altKey) return;
+ const ids = [...event.currentTarget.querySelectorAll('[data-row]')].map((row) => row.dataset.row.slice(kind.length + 1));
+ const at = ids.indexOf(view.row[kind]);
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ const next = ids[Math.min(ids.length - 1, Math.max(0, at + (event.key === 'ArrowDown' ? 1 : -1)))];
+ if (next && next !== view.row[kind]) { view.row[kind] = next; view.addressDetail = next; address(); render(); event.currentTarget.querySelector('.srow.on')?.scrollIntoView({ block: 'nearest' }); }
+ } else if (event.key === 'Enter' && view.row[kind]) {
+ event.preventDefault();
+ $(kind + '-detail').scrollIntoView({ block: 'start', behavior: 'instant' });
+ } else if ((event.key === 'a' || event.key === 'd') && view.row[kind] && $(kind + '-detail').querySelector('.approve-row')) {
+ // Only a row still waiting on the person has a decision to make; the detail shows it.
+ event.preventDefault();
+ if (event.key === 'a') decideRow(kind, 'spec-approve', { ids: view.row[kind] }, event.currentTarget);
+ else askDecline(kind, view.row[kind], 'list');
+ }
+});
+// The form covers the picked item rather than dropping it, so Cancel brings it back.
+$('new-item').addEventListener('click', () => { view.adding = true; render(); $('add-title').focus(); });
+$('upgrade-note').addEventListener('click', (event) => {
+ if (!event.target.closest('[data-upgrade-dismiss]')) return;
+ const notice = releaseNotices.get(data.project?.root);
+ if (notice) notice.releases = [];
+ renderReleaseNotes(data.project);
+});
+$('add-cancel').addEventListener('click', () => { view.adding = false; render(); });
+$('spec-decline-cancel').addEventListener('click', () => { closeDecline(); });
+$('spec-decline-form').addEventListener('keydown', trapFocus);
+// The row the dialog named is declined, with its reason, on the board it was opened on and only there.
+$('spec-decline-form').addEventListener('submit', (event) => {
+ event.preventDefault();
+ const reason = $('spec-decline-reason').value.trim();
+ if (!view.declining || !reason) return;
+ const asked = closeDecline();
+ if (asked.root !== view.root) return;
+ const anchor = asked.from === 'detail' ? $(asked.kind + '-detail') : [...$(asked.kind + '-list').querySelectorAll('[data-row]')].find((row) => row.dataset.row === asked.kind + ':' + asked.id);
+ decideRow(asked.kind, 'spec-decline', { ids: asked.id, reason }, anchor);
+});
+$('spec-approve-cancel').addEventListener('click', () => { closeApproveAll(); });
+$('spec-approve-form').addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); closeApproveAll(); } else trapFocus(event); });
+// The rows the confirmation named are the rows approved, on the board it was opened on and only there; the decision's
+// note beside them says what the board did.
+$('spec-approve-form').addEventListener('submit', (event) => {
+ event.preventDefault();
+ const asked = closeApproveAll(true);
+ if (asked && asked.root === view.root) decideRow('spec', 'spec-approve', { ids: asked.ids.join(' ') });
+});
+$('answer-cancel').addEventListener('click', () => answer(null));
+$('flow-hide').addEventListener('click', () => showFlow(false));
+$('flow-show').addEventListener('click', () => showFlow(true));
+$('flow-panel').hidden = keep('pb.flow') === 'hidden';
+$('flow-show').hidden = !$('flow-panel').hidden;
+// Each press moves on one, from the system's theme to light, then dark, and back; this browser keeps it.
+$('side-toggle').addEventListener('click', () => {
+ // A phone always shows the switcher, so there the logo is only the logo.
+ if (!matchMedia('(width > 900px)').matches) return;
+ const collapsed = !document.documentElement.dataset.side;
+ collapseSide(collapsed);
+ fold(false);
+ keep('pb.side', collapsed ? 'collapsed' : 'open');
+});
+/** Pick the scheme the page does not show now, and keep it. */
+function flipTheme() {
+ const next = document.documentElement.dataset.scheme === 'dark' ? 'light' : 'dark';
+ keep('pb.theme', next);
+ theme(next);
+}
+$('theme').addEventListener('click', flipTheme);
+$('ob-theme').addEventListener('click', flipTheme);
+$('q').addEventListener('input', () => { search(); view.foundAt = 0; showFound(); });
+// Leaving the field closes the results a moment later, so a press on a result lands first; coming back to the field
+// before then keeps them, or a search begun straight after Esc would lose its new results to the old close.
+let closingFound = 0;
+$('q').addEventListener('focus', () => { clearTimeout(closingFound); if ($('q').value.trim()) showFound(); });
+$('q').addEventListener('keydown', (event) => {
+ if (event.key === 'Escape') { $('q').value = ''; search(); hideFound('escape'); $('q').blur(); return; }
+ if (!view.found?.length || $('find-results').hidden) return;
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); view.foundAt = (view.foundAt + (event.key === 'ArrowDown' ? 1 : view.found.length - 1)) % view.found.length; showFound(); }
+ else if (event.key === 'Enter') { event.preventDefault(); openFound(view.found[view.foundAt].go); }
+});
+// A press on a result opens it before the field loses focus and the results close.
+$('find-results').addEventListener('mousedown', (event) => { const hit = event.target.closest('[data-find]'); if (hit) { event.preventDefault(); openFound(hit.dataset.find); } });
+$('q').addEventListener('blur', () => {
+ clearTimeout(closingFound);
+ // Esc and opening a result already close explicitly; their blur must keep that reason.
+ if ($('find-results').hidden) return;
+ closingFound = setTimeout(() => hideFound('left the field'), 120);
+});
+// "/" goes to the search from anywhere but a field.
+document.addEventListener('keydown', (event) => {
+ if (!view.filterOpen) return;
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ view.filterOpen = false;
+ render();
+ $('filter-toggle').focus({ preventScroll: true });
+ return;
+ }
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ const choices = [...$('filter-menu').querySelectorAll('[data-filter-choice]')];
+ const at = choices.indexOf(document.activeElement);
+ if (choices.length) {
+ event.preventDefault();
+ const next = at < 0 ? (event.key === 'ArrowDown' ? 0 : choices.length - 1) : (at + (event.key === 'ArrowDown' ? 1 : choices.length - 1)) % choices.length;
+ choices[next].focus({ preventScroll: true });
+ }
+ }
+});
+document.addEventListener('keydown', (event) => {
+ if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || event.target.closest('input, textarea, select, [contenteditable]')) return;
+ event.preventDefault();
+ $('q').focus();
+ $('q').select();
+});
+$('add-form').addEventListener('submit', async (event) => {
+ event.preventDefault();
+ const root = view.root;
+ const submitted = { lane: $('add-lane').value, title: $('add-title').value, criterion: $('add-criterion').value, specs: $('add-specs').value, brief: $('add-brief').value };
+ if (await act('add', submitted, event.currentTarget) && view.root === root
+ && $('add-lane').value === submitted.lane && $('add-title').value === submitted.title
+ && $('add-criterion').value === submitted.criterion && $('add-specs').value === submitted.specs
+ && $('add-brief').value === submitted.brief) {
+ $('add-title').value = '';
+ $('add-criterion').value = '';
+ $('add-specs').value = '';
+ $('add-brief').value = '';
+ }
+});
+$('shout-form').addEventListener('submit', async (event) => {
+ event.preventDefault();
+ const text = $('shout-text').value;
+ const root = view.root;
+ const ask = view.answering;
+ const answerRoot = ask?.root ?? null;
+ const answerId = ask?.id ?? null;
+ if (ask && ask.root !== view.root) return answer(null);
+ if (!(await (ask ? act('answer', { id: ask.id, text }, event.currentTarget) : ($('shout-to').value === 'coordinator' ? act('request', { text }, event.currentTarget) : act('shout', { to: $('shout-to').value, text }, event.currentTarget))))) return;
+ const currentAnswer = view.answering;
+ // An older completion must not erase a newer draft or answer selection.
+ if (view.root !== root || $('shout-text').value !== text || (currentAnswer?.root ?? null) !== answerRoot
+ || (currentAnswer?.id ?? null) !== answerId) return;
+ $('shout-text').value = '';
+ answer(null);
+});
+$('hold-form').addEventListener('submit', async (event) => {
+ event.preventDefault();
+ const root = view.root;
+ const submitted = { lane: $('hold-lane').value, reason: $('hold-reason').value };
+ if (await act('hold', submitted, event.currentTarget) && view.root === root
+ && $('hold-lane').value === submitted.lane && $('hold-reason').value === submitted.reason) $('hold-reason').value = '';
+});
+// The first entry keeps the tab it opened on; Back and Forward show what each entry names.
+address(false);
+globalThis.addEventListener?.('popstate', fromAddress);
+showTab();
+if (snapshot) {
+ $('replay-play').addEventListener('click', playReplay);
+ $('replay-pause').addEventListener('click', pauseReplay);
+ $('replay-speed').addEventListener('change', () => {
+ if (snapshotReplay.playing) { clearTimeout(snapshotReplay.timer); snapshotReplay.timer = setTimeout(advanceReplay, 1000 / Number($('replay-speed').value)); }
+ });
+}
+/** Copy a screen's command or sentence; a browser without the clipboard API copies from a selected field. */
+async function copyWords(text) {
+ try { await navigator.clipboard.writeText(text); return true; }
+ catch { /* Older and embedded browsers refuse the clipboard API: copy from a selected field below. */ }
+ const field = document.createElement('textarea');
+ field.value = text;
+ field.setAttribute('readonly', '');
+ field.style.position = 'fixed';
+ field.style.opacity = '0';
+ document.body.append(field);
+ field.select();
+ const copied = document.execCommand('copy');
+ field.remove();
+ return copied;
+}
+$('local-note').addEventListener('click', async (event) => {
+ const button = event.target instanceof Element ? event.target.closest('button[data-copy]') : null;
+ if (!button || !button.dataset.copy) return;
+ button.textContent = await copyWords(button.dataset.copy) ? 'Copied' : 'Select and copy';
+});
+/**
+ * Look for this machine's view again, by itself, while a screen waits on it or a signed-in person waits for a board:
+ * the moment the view answers, the page opens the board, with no Try again (#764). Over a relay stream, a reload
+ * starts both sources together.
+ */
+let relisting = false;
+function lookAgain() {
+ // This computer's view answered, then a read failed, as a busy view's can: read again every two seconds, so the
+ // board shows the moment a list arrives (hostedListed clears the problem), never only on the slower fallback timer.
+ if (hosted.local && localReached && !document.hidden && $('local-note').dataset.state === 'problem') {
+ if (!relisting) { relisting = true; refresh().catch(() => {}).finally(() => { relisting = false; }); }
+ return;
+ }
+ if (!hosted.local || relayPairing || localReached || localProblem || document.hidden) return;
+ if (![...LOCAL_STATES, 'no-linked', 'unpaired'].includes($('local-note').dataset.state || '') || $('local-note').dataset.state === 'looking') return;
+ connectLocal(true).then((local) => {
+ if (local !== 'local') return;
+ if (transport) { location.reload(); return; }
+ transportModule = null;
+ return refresh();
+ }).catch((error) => localNote('problem', { detail: error.message }));
+}
+if (hosted.local && !snapshot) setInterval(lookAgain, 2000);
+
+/** Open a newly approved board's Items view after its real list entry arrives. */
+async function openApprovedBoard(boardId) {
+ await refresh();
+ const board = data?.projects.find(entry => entry.id === boardId && entry.ok);
+ if (!board) throw new Error('The approved board did not load. Refresh the board list and try again.');
+ view.tab = 'items';
+ keep('pb.tab', view.tab);
+ return switchTo(board.root);
+}
+
+/** Load the configured decrypting transport once, only when relay reads or pairing need it. */
+let transportLoading = null;
+async function loadTransport() {
+ if (transport) return transport;
+ if (!transportLoading) transportLoading = (async () => {
+ const module = await pageStartup(document.documentElement).within(() => import(configuredTransportModule), 15_000, 'The relay client did not load within 15 seconds.');
+ if (typeof module.createTransport !== 'function') throw new Error('The browser transport must export createTransport({ onUpdate }).');
+ const configured = await module.createTransport({
+ onUpdate: () => transport ? refresh().catch((error) => { $('live').textContent = 'offline: ' + error.message; }) : Promise.resolve(),
+ onOpenBoard: openApprovedBoard, waitForRender: true, // A phone's transport keeps its shell until didRender (#899).
+ });
+ if (!configured || typeof configured.request !== 'function') throw new Error('The browser transport must provide request(path, body).');
+ transportModule = configuredTransportModule;
+ transport = configured;
+ return transport;
+ })();
+ try { return await transportLoading; }
+ catch (error) { transportLoadError = error; pageStartup(document.documentElement).say(error.message + ' Check your connection, then reload this page.'); throw error; }
+ finally { transportLoading = null; }
+}
+
+/** Read local boards first; relay-only pages and pairing still load their configured client directly. */
+async function startPage() {
+ let local = 'unreachable';
+ if (hosted.local && !relayPairing) {
+ if (localProblem) localNote('problem', { detail: localProblem });
+ else local = await connectLocal();
+ if (local === 'away') return;
+ if (local === 'unreachable' && !hosted.relaySession) { hideRelayNotice(); return; }
+ }
+ if (hosted.local && local === 'local') transportModule = null;
+ else if (configuredTransportModule) {
+ // Signed out, a pairing link waits for sign-in, which its own state asks for.
+ try { await loadTransport(); } catch (error) { if (!hosted.local || hosted.relaySession) throw error; localNote('signed-out'); return; }
+ }
+ await refresh();
+}
+startPage().catch((error) => {
+ document.body.classList.remove('loading');
+ $('live').textContent = 'cannot reach the view: ' + error.message;
+ // Finding your boards never stays on a page that has stopped looking.
+ if (hosted.local && $('local-note').dataset.state === 'looking') localNote('problem', { detail: 'Pullboard on this computer did not answer: ' + error.message });
+});
+// The relay transport keeps its own stream and timer. The local view reads on a timer only while it has no live
+// stream, and its live line says so (#545). Each timer asks which the page uses as it fires: the hosted page starts
+// out on the relay and turns to this machine's view once it reaches it (#513).
+if (!snapshot) setInterval(() => { if (!document.hidden && (transport || (hosted.local && hosted.relaySession && configuredTransportModule))) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, 3000);
+if (!snapshot) setInterval(() => { if (!document.hidden && !transport && !(hosted.local && hosted.relaySession && configuredTransportModule) && !connected()) refresh().catch(() => { $('live').textContent = 'offline: is pullboard view still running?'; }); }, FALLBACK_MS);
+setInterval(tickAges, 60000);
+`;
+}
diff --git a/test/cockpit/layout.test.js b/test/cockpit/layout.test.js
index b2b5eb3b..d6d4f50a 100644
--- a/test/cockpit/layout.test.js
+++ b/test/cockpit/layout.test.js
@@ -4,6 +4,7 @@ import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { request } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
import { test } from 'node:test';
import { SPEC, machine, project, build, sendBack, fetchLive, startView, styleOf, element, settle, storage, openPage, accept, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, press } from './fixture.js';
@@ -698,3 +699,13 @@ test('targets are 44px for touch and compact under a mouse [N26]', { timeout: 15
await view.stop();
}
});
+
+test('no view source file is over the 1500-line cap [C7,D1]', async () => {
+ // The file-size check counts every source file in the repo; this test owns the view's source files (#745). The
+ // view's tests under test/cockpit are kept whole and unchanged, so they are not counted here.
+ const { fileSizeProblems } = await import('../../bin/checks/file-size.js');
+ const root = fileURLToPath(new URL('../../', import.meta.url));
+ const viewLane = /^(?:src\/cockpit\.js|src\/serve\.js|src\/view\.css|src\/view\/)/u;
+ const over = fileSizeProblems(root).filter((problem) => viewLane.test(problem.path)).map((problem) => `${problem.path}:${problem.line}`);
+ assert.deepEqual(over, [], 'every view file is under the 1500-line cap, so the file-size check prints no block for it');
+});