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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(view): open Items on work with compact stats [N26,V2]
Corey Olson3023f732856c
diff --git a/src/cockpit.js b/src/cockpit.jsindex 2e7d4829..858faa1b 100644--- a/src/cockpit.js+++ b/src/cockpit.js@@ -184,7 +184,7 @@ 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', 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', open: {} };+const view = { roadmapOpen: new Map(), root: keep('pb.project'), tab: addressTab() || homeTab(), itemsView: typeof location !== 'undefined' && location.hash === '#items/pipeline' ? 'pipeline' : 'list', 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: {} };let switchGeneration = 0;if (snapshot) view.state = 'all';let data = null;@@ -771,9 +771,14 @@ function boardSummary(board, state) {};}-/** Format the API's measured minutes without deriving new times from events [N26]. */+/** Format an API-measured duration in readable units without deriving times from events [N26]. */function flowMinutes(value) {- return value === null || value === undefined ? 'unmeasured' : Number(value.toFixed(2)) + ' min';+ 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';}/** Render the four stages, live queues and single recommendation supplied by stats [N26]. */@@ -797,24 +802,14 @@ function proofFlowCard(flow) {+ (bottleneck.recommendation ? ' · <span data-flow="recommendation">' + esc(bottleneck.recommendation) + '</span>' : '') + '</p></div>';}-/** Format a counted noun for the proof stats detail.- * @param {number} count- * @param {string} singular- * @param {string} plural- * @returns {string}- */-function counted(count, singular, plural) {- return count + ' ' + (count === 1 ? singular : plural);-}-/** Render the event-log totals already supplied by the shared stats API [V2,N26]. */-function proofStatsCard(stats) {+function proofStatsCard(stats, expanded = false) {if (!stats) return '<span class="muted">Stats unavailable</span>';- const families = stats.families || [];- const agents = stats.agents || [];const percentage = (Number(stats.rejectionShare) * 100).toFixed(1) + '%';- const familyDetail = families.map((family) => family.name + ' (' + counted(family.agents, 'agent', 'agents') + ', ' + counted(family.moves, 'move', 'moves') + ')').join(' · ') || 'none';- const agentDetail = agents.map((agent) => agent.id + ' (' + agent.families.join('/') + '; ' + counted(agent.moves, 'move', 'moves') + ')').join(' · ') || 'none';+ 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}@@ -822,7 +817,10 @@ function proofStatsCard(stats) {const dateText = (value) => value ? new Date(value).toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' }) : 'none';const firstAt = stats.firstEventAt ?? '';const lastAt = stats.lastEventAt ?? '';- return '<div class="proof-stats-head"><b>Proof stats</b><span>from recorded moves</span></div>'+ 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><button id="proof-stats-close" type="button" class="proof-stats-close" data-stats-close>Close</button></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>'@@ -830,10 +828,8 @@ function proofStatsCard(stats) {+ '<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>Families</span><b data-stat="familyCount" data-value="' + esc(stats.familyCount) + '">' + esc(stats.familyCount) + '</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 class="proof-stats-detail">'- + '<p><b>Families:</b> ' + esc(familyDetail) + '</p><p><b>Agents:</b> ' + esc(agentDetail) + '</p></div>';+ + '</div>' + proofFlowCard(stats.flow) + '</div>';}/** Resolve a displayed repo to the persistent board identity supplied by API v1. */@@ -1356,6 +1352,7 @@ if (typeof MutationObserver === 'function') new MutationObserver((changes) => {/** Draw the board shown: the sidebar, then every tab's panes from the project's board. */function render() {+ const statsFocus = ['proof-stats-summary', 'proof-stats-close'].includes(document.activeElement?.id) ? document.activeElement.id : null;const p = data.project;const group = data.group;renderSide();@@ -1375,7 +1372,9 @@ function render() {if (group) { renderGroup(group); return; }if (!p) return;$('proof-stats').hidden = false;- $('proof-stats').innerHTML = proofStatsCard(p.proofStats);+ $('proof-stats').innerHTML = proofStatsCard(p.proofStats, view.statsOpen);+ // Polling replaces this card's controls; keep the person's keyboard position through that redraw.+ if (statsFocus && view.tab === 'items') $(statsFocus)?.focus({ preventScroll: true });// Each product's progress (N28): the rows an accepted item cites, and its items by state.$('prod-list').innerHTML = p.products.map((x) => {const states = [['open', '', x.items.open], ['building', 'building', x.items.claimed], ['to verify', 'verify', x.items.submitted], ['verified', 'verified', x.items.verified]].filter(([, , n]) => n);@@ -2240,11 +2239,23 @@ $('shouts-pane').addEventListener('click', (event) => {// 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) => {- const t = event.target.closest('[data-status],[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],#proj-switch,#console');+ const t = event.target.closest('[data-status],[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],[data-stats-close],#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.dataset.statsToggle !== undefined) {+ view.statsOpen = true;+ render();+ $('proof-stats-close').focus({ preventScroll: true });+ return;+ }+ if (t.dataset.statsClose !== undefined) {+ view.statsOpen = false;+ render();+ $('proof-stats-summary').focus({ preventScroll: true });+ return;+ }if (t.dataset.status) { statusGo(t.dataset.status); return; }if (t.dataset.itemsView) { view.itemsView = t.dataset.itemsView; address(); render(); return; }if ('roadmapKey' in t.dataset) {@@ -2286,6 +2297,14 @@ document.addEventListener('click', (event) => {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(); }});+/** 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;diff --git a/src/view.css b/src/view.cssindex 534caebc..ce231589 100644--- a/src/view.css+++ b/src/view.css@@ -704,11 +704,20 @@ code.inline.long { white-space: break-spaces; overflow-wrap: anywhere; }.credential dd { margin: 0; overflow-wrap: anywhere; }.credential > button { justify-self: start; min-height: 44px; }-.proof-stats { padding: 10px 12px; display: grid; gap: 7px; }+.proof-stats { padding: 8px 10px; display: grid; gap: 8px; }.proof-stats[hidden] { display: none; }-.proof-stats-head { display: flex; align-items: baseline; gap: 8px; }+.proof-stats-summary { display: flex; align-items: center; gap: 8px; width: 100%; min-height: var(--tap); padding: 6px 8px; border: 0; border-radius: 8px; background: var(--surface-2); color: var(--ink); text-align: left; font-size: 13px; line-height: 1.3; cursor: pointer; }+.proof-stats-summary:hover { background: color-mix(in srgb, var(--surface-2) 82%, var(--ink) 18%); }+.proof-stats-summary > span:first-child { min-width: 0; flex: 1; }+.proof-stats-summary-text { min-width: 0; flex: 1; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 1; overflow: hidden; overflow-wrap: anywhere; }+@media (width < 900px) { .proof-stats-summary-text { -webkit-line-clamp: 2; } }+.proof-stats-caret { flex: none; color: var(--ink-muted); font-size: 16px; }+.proof-stats-full { display: grid; gap: 7px; }+.proof-stats-full[hidden] { display: none; }+.proof-stats-head { display: flex; align-items: center; gap: 8px; }.proof-stats-head b { font-size: 13px; }.proof-stats-head > span, .proof-stats-grid > div > span { color: var(--ink-muted); font-size: 11px; }+.proof-stats-close { min-height: var(--tap); margin-left: auto; padding: 4px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface-2); cursor: pointer; font-size: 12px; }.proof-stats-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 7px 12px; }.proof-stats-grid > div { min-width: 0; display: flex; flex-direction: column; gap: 2px; }.proof-stats-grid b { font-size: 14px; font-variant-numeric: tabular-nums; }diff --git a/test/cockpit/stats.test.js b/test/cockpit/stats.test.jsindex e4f35597..de745903 100644--- a/test/cockpit/stats.test.js+++ b/test/cockpit/stats.test.js@@ -1,11 +1,11 @@/** Cockpit stats checks, using the shared real-board fixtures [N26]. */import assert from 'node:assert/strict';-import { mkdtempSync, rmSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { test } from 'node:test';import * as store from '../../src/board.js';-import { SPEC, machine, project, build, sendBack, startView, accept, boardOf, earlier, proofShot, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, pickProject } from './fixture.js';+import { tapTarget, SPEC, machine, project, build, sendBack, startView, accept, boardOf, earlier, proofShot, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, pickProject, press } from './fixture.js';/** Add a real joined worktree to the shared test board.* @param {ReturnType<typeof machine>} box@@ -20,6 +20,15 @@ function joinedAgent(box, p, name) {return web;}+/** Express one API duration at its rounded, human-readable unit for visible-label assertions. */+function displayDuration(value) {+ if (value === null || value === undefined) return 'unmeasured';+ const rounded = Math.round(value);+ if (rounded < 60) return rounded + ' min';+ const hours = Math.floor(rounded / 60);+ return hours < 24 ? hours + ' h ' + rounded % 60 + ' min' : Math.floor(hours / 24) + ' d ' + hours % 24 + ' h';+}+test('[V2,N26] real Chrome shows matching proof stats at phone width and clears on a group [V2,N26]', { timeout: 90_000 }, async (t) => {const executable = chromeExecutable();@@ -50,7 +59,9 @@ test('[V2,N26] real Chrome shows matching proof stats at phone width and clearsawait chrome.waitFor("!!data?.project?.proofStats && document.querySelector('#proof-stats [data-stat=\"submissions\"]')");await pickProject(chrome, `document.querySelector('[data-root=${JSON.stringify(alpha.repo)}]')`);await chrome.waitFor(`data?.project?.root === ${JSON.stringify(alpha.repo)} && !!document.querySelector('#proof-stats [data-stat="submissions"]')`);- const keys = ['submissions', 'rejections', 'rejectionShare', 'merged', 'mergedWithoutAccept', 'agentCount', 'familyCount', 'firstEventAt', 'lastEventAt'];+ await press(chrome, "document.querySelector('#proof-stats-summary')");+ await chrome.waitFor("!document.querySelector('#proof-stats-full').hidden");+ const keys = ['submissions', 'rejections', 'rejectionShare', 'merged', 'mergedWithoutAccept', 'agentCount', 'firstEventAt', 'lastEventAt'];const expectedValues = Object.fromEntries(keys.map((key) => [key, key === 'rejectionShare' ? `${(expected[key] * 100).toFixed(1)}%` : String(expected[key] ?? '')]));for (const scheme of ['light', 'dark']) for (const width of [375, 1280]) {await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });@@ -119,14 +130,15 @@ test('[V2,N26] stats counts agree in number', { timeout: 90_000 }, async () => {let chrome;try {chrome = await openSnapshotChrome(executable, view.link.href, profile);- await chrome.waitFor("!!data?.project?.proofStats && document.querySelector('#proof-stats .proof-stats-detail')");+ await chrome.waitFor("!!data?.project?.proofStats && document.querySelector('#proof-stats-summary')");await pickProject(chrome, `document.querySelector('[data-root=${JSON.stringify(alpha.repo)}]')`);- await chrome.waitFor(`data?.project?.root === ${JSON.stringify(alpha.repo)} && !!document.querySelector('#proof-stats .proof-stats-detail')`);- const detail = await chrome.stable("document.querySelector('#proof-stats .proof-stats-detail').textContent");- assert.match(detail, /solo \(1 agent, 1 move\)/);- assert.match(detail, /crew \(3 agents, 14 moves\)/);- assert.match(detail, /web-5 \(unknown; 1 move\)/);- assert.match(detail, /web-2 \(crew\/other\/unknown; 24 moves\)/);+ await chrome.waitFor(`data?.project?.root === ${JSON.stringify(alpha.repo)} && !!document.querySelector('#proof-stats-summary')`);+ await press(chrome, "document.querySelector('#proof-stats-summary')");+ const detail = await chrome.stable("document.querySelector('#proof-stats-full').textContent");+ const count = await chrome.stable("document.querySelector('[data-stat=agentCount]').textContent");+ assert.equal(count, String(expected.agentCount), 'the expanded card keeps the API agent count');+ assert.doesNotMatch(detail, /solo|crew|web-\d+|Families/i, 'the card does not enumerate agent or family names');+ assert.equal(await chrome.stable("document.querySelector('[data-stat=familyCount]') === null"), true, 'the full card has no Families tile');} finally {if (chrome) await closeSnapshotChrome(chrome);await view.stop();@@ -134,6 +146,155 @@ test('[V2,N26] stats counts agree in number', { timeout: 90_000 }, async () => {}});+/** Exercise the glance layout with 300 real registrations and measured native lifecycle moves. */+// budget: 300 registrations plus four Chrome layouts; derived from the existing 90s browser ceiling with fixture headroom.+test('stats read at a glance on a board with hundreds of agents [N26,V2]', { timeout: 300_000 }, async (t) => {+ const executable = chromeExecutable();+ assert.ok(executable, 'Chrome is required for the 300-agent stats layout criterion.');+ const box = machine();+ const alpha = project(box, 'stats-at-a-glance');+ stageFlowBoard(box, alpha);+ stageAcceptedQueue(box, alpha);+ const board = store.openBoard(join(alpha.repo, '.git', 'pullboard', 'board.sqlite'));+ try {+ for (let index = 5; index <= 299; index += 1) {+ store.register(board, {+ lane: 'web',+ path: join(box.dir, `private-agent-${index}`),+ family: `private-family-${index % 7}`,+ model: `Private model ${index}`,+ });+ }+ } finally {+ store.closeBoard(board);+ }+ const stats = JSON.parse(box.run(alpha.repo, 'stats', '--json')).stats;+ assert.equal(stats.agentCount, 300, 'the actual board stats count all registered agents');++ const view = await startView(box);+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-stats-at-a-glance-chrome-'));+ let chrome;+ try {+ chrome = await openSnapshotChrome(executable, view.link.href, profile);+ await chrome.waitFor("!!data?.project?.proofStats && document.querySelector('#proof-stats-summary') && document.querySelector('#chain > li')");+ const api = JSON.parse(await chrome.stable('JSON.stringify(data.project.proofStats)'));+ assert.equal(api.flow.bottleneck.stage, 'mergeWait', 'the real measured board has an accepted queue bottleneck');+ const expectedSummary = `${api.merged} merged · ${(Number(api.rejectionShare) * 100).toFixed(1)}% sent back`+ + (api.flow?.bottleneck ? ` · Bottleneck: Merge wait${api.flow.bottleneck.recommendation ? ', ' + api.flow.bottleneck.recommendation : ''}` : '');+ const layouts = [];+ for (const scheme of ['light', 'dark']) for (const width of [375, 1280]) {+ const height = width < 900 ? 812 : 800;+ await chrome.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });+ await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });+ await chrome.waitFor(`innerWidth === ${width} && innerHeight === ${height} && matchMedia('(prefers-color-scheme: ${scheme})').matches`);+ const before = JSON.parse(await chrome.stable(`JSON.stringify((() => {+ const summary=document.querySelector('#proof-stats-summary'), text=summary.querySelector('.proof-stats-summary-text');+ const rect=node=>{const r=node.getBoundingClientRect();return {top:r.top,bottom:r.bottom,height:r.height,width:r.width,right:r.right};};+ const lineHeight=parseFloat(getComputedStyle(text).lineHeight);+ const natural=text.cloneNode(true);+ Object.assign(natural.style,{position:'absolute',visibility:'hidden',width:text.getBoundingClientRect().width+'px',webkitLineClamp:'unset'});+ text.parentNode.append(natural);+ const naturalHeight=natural.getBoundingClientRect().height; natural.remove();+ const first=document.querySelector('#chain > li');+ return {summary:text.textContent, summaryLines:Math.ceil(text.getBoundingClientRect().height/lineHeight), summaryClipped:text.scrollHeight > text.clientHeight + 1, naturalHeight, lineHeight, clamp:getComputedStyle(text).webkitLineClamp, summaryBox:rect(summary),+ expanded:summary.getAttribute('aria-expanded'), first:first?.dataset.item ?? null, firstBox:first&&rect(first), itemListHidden:document.querySelector('#item-list').hidden,+ viewportWidth:document.documentElement.clientWidth, pageWidth:document.documentElement.scrollWidth, viewportHeight:innerHeight};+ })())`));+ assert.equal(before.summary, expectedSummary, `${width}px ${scheme}: the line selects the API merged, sent-back and bottleneck values`);+ assert.equal(before.expanded, 'false', `${width}px ${scheme}: the compact summary starts closed`);+ assert.equal(before.summaryLines <= (width < 900 ? 2 : 1), true, `${width}px ${scheme}: the summary occupies at most two compact lines: ${JSON.stringify(before.summaryBox)}`);+ assert.equal(before.clamp, width < 900 ? '2' : '1', `${width}px ${scheme}: overflow uses the browser's line-clamp ellipsis`);+ if (before.naturalHeight > before.lineHeight * (width < 900 ? 2 : 1) + 1) assert.equal(before.summaryClipped, true, `${width}px ${scheme}: a recommendation that would exceed the line limit is clipped`);+ assert.ok(before.summaryBox.height >= tapTarget(width), `${width}px ${scheme}: the summary meets the #371 target size`);+ assert.equal(before.itemListHidden, false, `${width}px ${scheme}: the item list remains the visible default`);+ assert.equal(before.first, '4', `${width}px ${scheme}: the first real item row is present`);+ assert.ok(before.firstBox.bottom <= height, `${width}px ${scheme}: the first item appears without scrolling: ${JSON.stringify(before)}`);+ assert.ok(before.pageWidth <= before.viewportWidth, `${width}px ${scheme}: no horizontal page overflow`);+ layouts.push({ scheme, width, firstBottom: before.firstBox.bottom, summaryHeight: before.summaryBox.height });++ if (process.env.PULLBOARD_STATS_PROOF) {+ mkdirSync(process.env.PULLBOARD_STATS_PROOF, { recursive: true });+ const shot = await chrome.send('Page.captureScreenshot', { format: 'png' });+ writeFileSync(join(process.env.PULLBOARD_STATS_PROOF, `stats-${width}-${scheme}.png`), Buffer.from(shot.data, 'base64'));+ }++ await press(chrome, "document.querySelector('#proof-stats-summary')");+ await chrome.waitFor("!document.querySelector('#proof-stats-full').hidden");+ const card = await chrome.stable("document.querySelector('#proof-stats-full').textContent");+ const details = JSON.parse(await chrome.stable(`JSON.stringify({agentCount:document.querySelector('[data-stat="agentCount"]')?.textContent,+ familyTile:!!document.querySelector('[data-stat="familyCount"]'), hasFirstAgent:document.querySelector('#proof-stats-full').textContent.includes('web-1'),+ hasPrivateName:document.querySelector('#proof-stats-full').textContent.includes('Private model'), hasFamilyName:document.querySelector('#proof-stats-full').textContent.includes('private-family-')})`));+ for (const agent of api.agents) assert.equal(card.includes(agent.id), false, `${width}px ${scheme}: the card does not name ${agent.id}`);+ for (const family of api.families) assert.equal(card.includes(family.name), false, `${width}px ${scheme}: the card does not name family ${family.name}`);+ assert.equal(await chrome.stable("document.querySelector('[data-flow=bottleneck]').textContent"), api.flow.bottleneck.message, 'the full API message stays unchanged in the expanded card');+ assert.equal(await chrome.stable("document.querySelector('[data-flow=recommendation]').textContent"), api.flow.bottleneck.recommendation, 'the full API recommendation stays unchanged in the expanded card');+ assert.equal(details.agentCount, '300', `${width}px ${scheme}: the expanded card shows the count only`);+ assert.equal(details.familyTile, false, `${width}px ${scheme}: the expanded card has no Families tile`);+ assert.equal(details.hasFirstAgent || details.hasPrivateName || details.hasFamilyName, false, `${width}px ${scheme}: the card does not name agents or families`);+ assert.doesNotMatch(card, /Families:/i, `${width}px ${scheme}: no Families line appears in the card`);++ if (process.env.PULLBOARD_STATS_PROOF) {+ const shot = await chrome.send('Page.captureScreenshot', { format: 'png' });+ writeFileSync(join(process.env.PULLBOARD_STATS_PROOF, `stats-card-${width}-${scheme}.png`), Buffer.from(shot.data, 'base64'));+ }++ if (width === 375 && scheme === 'light') {+ await press(chrome, "document.querySelector('#proof-stats-close')");+ } else {+ for (const type of ['keyDown', 'keyUp']) await chrome.send('Input.dispatchKeyEvent', { type, key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });+ }+ assert.equal(await chrome.stable("document.querySelector('#proof-stats-full').hidden"), true, `${width}px ${scheme}: Close or Escape folds the expanded card`);+ assert.equal(await chrome.stable('document.activeElement?.id'), 'proof-stats-summary', `${width}px ${scheme}: closing returns focus to the list summary`);+ await chrome.stable('refresh().then(() => true)');+ assert.equal(await chrome.stable('document.activeElement?.id'), 'proof-stats-summary', `${width}px ${scheme}: a real API refresh preserves the returned keyboard focus`);+ assert.equal(await chrome.stable('document.querySelector("#chain > li")?.dataset.item'), '4', `${width}px ${scheme}: closing returns to the unchanged item list`);+ }+ assert.equal(layouts.length, 4, 'the compact board was checked in both themes at both target widths');+ } finally {+ if (chrome) await closeSnapshotChrome(chrome);+ await view.stop();+ rmSync(profile, { recursive: true, force: true });+ }+});++/** Call the actual page formatter with fixed numeric inputs; the flow-card story checks its real API binding. */+// budget: derived from the existing 90s real-browser fixture ceiling; the six formatter calls add no wait.+test('stats times read in human units [N26,V2]', { timeout: 90_000 }, async (t) => {+ const executable = chromeExecutable();+ assert.ok(executable, 'Chrome is required for the human-unit stats criterion.');+ const box = machine();+ project(box, 'stats-human-units');+ const view = await startView(box);+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-stats-human-units-chrome-'));+ let chrome;+ try {+ chrome = await openSnapshotChrome(executable, view.link.href, profile);+ await chrome.waitFor("!!data?.project?.proofStats?.flow && document.querySelector('#proof-stats-summary')");+ const actual = JSON.parse(await chrome.stable('JSON.stringify([42,213.9,5707.5,null,59.6,1439.6].map(flowMinutes))'));+ assert.deepEqual(actual, ['42 min', '3 h 34 min', '3 d 23 h', 'unmeasured', '1 h 0 min', '1 d 0 h'], 'the actual production formatter rounds fixed inputs, including unit boundaries, without altering the API');+ } finally {+ if (chrome) await closeSnapshotChrome(chrome);+ await view.stop();+ rmSync(profile, { recursive: true, force: true });+ }+});++/** Leave twenty real accepted items waiting long enough to exercise a long API recommendation. */+function stageAcceptedQueue(box, alpha) {+ const base = Date.now() - 120 * 60_000;+ const commit = box.git(alpha.repo, 'rev-parse', 'HEAD');+ const tree = box.git(alpha.repo, 'rev-parse', 'HEAD^{tree}');+ const digest = 'a'.repeat(64);+ for (let id = 6; id <= 26; id += 1) {+ earlier(alpha.repo, base, board => store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Waiting accepted item ' + id, specIds: ['G1'], criterion: 'Known accepted queue' }));+ earlier(alpha.repo, base + 60_000, board => store.claim(board, id, { agentId: 'web-1', lane: 'web', leaseMs: 24 * 60 * 60_000, head: commit, freeze: () => ({ text: '{}', digest }) }));+ earlier(alpha.repo, base + 2 * 60_000, board => store.submit(board, id, { agentId: 'web-1', commit, tree }));+ earlier(alpha.repo, base + 3 * 60_000, board => store.reserveReview(board, id, { agentId: 'tests-1', leaseMs: 24 * 60 * 60_000, policy: 'any' }));+ earlier(alpha.repo, base + 4 * 60_000, board => store.verify(board, id, { agentId: 'tests-1', decision: 'ACCEPT', note: 'Private accepted queue', head: commit, digest, policy: 'any' }));+ if (id === 26) earlier(alpha.repo, base + 104 * 60_000, board => store.merged(board, id, { agentId: 'coordinator', commit }));+ }+}+/** Stage a fully measured cycle and every live queue through native writers on a private clock. */function stageFlowBoard(box, alpha) {const base = Date.now() - 120 * 60_000;@@ -184,6 +345,8 @@ test('the stats card shows API flow and bottleneck at 375 and 1280 [N26]', { timawait chrome.waitFor('!!data?.project?.proofStats');await pickProject(chrome, 'document.querySelector(' + JSON.stringify('[data-root="' + alpha.repo + '"]') + ')');await chrome.waitFor('data?.project?.root === ' + JSON.stringify(alpha.repo) + ' && !!document.querySelector("[data-stage=build]")');+ await press(chrome, "document.querySelector('#proof-stats-summary')");+ await chrome.waitFor("!document.querySelector('#proof-stats-full').hidden");const backgrounds = {};for (const scheme of ['light', 'dark']) for (const width of [375, 1280]) {await chrome.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });@@ -205,10 +368,9 @@ test('the stats card shows API flow and bottleneck at 375 and 1280 [N26]', { timviewport:document.documentElement.clientWidth, pageWidth:document.documentElement.scrollWidth, rects };})())`));/** Format only the expected API number, independently of the page renderer. */- const minutes = value => value === null ? 'unmeasured' : Number(value.toFixed(2)) + ' min';- assert.deepEqual(actual.stages, Object.entries(actual.api.stages).map(([key, stage]) => ({key, value:String(stage.averageMinutes ?? ''), text:minutes(stage.averageMinutes)})), width + ': every stage displays the API average');+ assert.deepEqual(actual.stages, Object.entries(actual.api.stages).map(([key, stage]) => ({key, value:String(stage.averageMinutes ?? ''), text:displayDuration(stage.averageMinutes)})), width + ': every stage displays the API average in human units');assert.deepEqual(actual.queues, Object.entries(actual.api.queues).map(([key, queue]) => ({key, value:String(queue.size), text:String(queue.size)})), width + ': every queue displays the API size');- assert.deepEqual(actual.oldest, Object.entries(actual.api.queues).map(([key, queue]) => ({key, value:String(queue.oldest?.ageMinutes ?? ''), text:queue.oldest ? 'Oldest: #' + queue.oldest.id + ' · ' + minutes(queue.oldest.ageMinutes) : 'Oldest: none'})), width + ': oldest ages come from the same API observation');+ assert.deepEqual(actual.oldest, Object.entries(actual.api.queues).map(([key, queue]) => ({key, value:String(queue.oldest?.ageMinutes ?? ''), text:queue.oldest ? 'Oldest: #' + queue.oldest.id + ' · ' + displayDuration(queue.oldest.ageMinutes) : 'Oldest: none'})), width + ': oldest ages come from the same API observation');assert.equal(actual.bottleneck, actual.api.bottleneck.message);assert.equal(actual.action, actual.api.bottleneck.recommendation);assert.equal(actual.statementCount, 1, 'one element contains the complete API statement');@@ -222,7 +384,7 @@ test('the stats card shows API flow and bottleneck at 375 and 1280 [N26]', { timassert.equal(actual.darkTheme, scheme === 'dark', 'the browser observes the requested theme');backgrounds[scheme] = actual.background;assert.ok(actual.pageWidth <= actual.viewport + 1, width + ': no sideways page scroll');- assert.ok(actual.rects.every(rect => rect.width > 0 && rect.right <= actual.viewport + 1 && !rect.overflow), width + ': flow values and statement stay inside the card');+ assert.ok(actual.rects.every(rect => rect.width > 0 && rect.right <= actual.viewport + 1 && !rect.overflow), width + ': flow values and statement stay inside the card: ' + JSON.stringify(actual.rects));if (scheme === 'dark') await proofShot(chrome, 'stats-flow', width);}assert.notEqual(backgrounds.light, backgrounds.dark, 'both color themes were rendered');