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: add cockpit performance harness [N26]
Corey Olsonbc080af9dd69
diff --git a/test/cockpit/perf.test.js b/test/cockpit/perf.test.jsnew file mode 100644index 00000000..6e5e04a1--- /dev/null+++ b/test/cockpit/perf.test.js@@ -0,0 +1,60 @@+/** Exercise the deterministic stress fixture and the real-Chrome performance harness [N26]. */+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { generateStressBoard, removeStressBoard } from './perf/generate.mjs';+import { withPerfSlot } from './perf/run.mjs';++test('the perf harness measures every action on a stress board [N26]', async (t) => {+ let first = null;+ let second = null;+ t.after(() => {+ if (!t.passed) {+ console.error(`Performance evidence retained at ${first?.workspace ?? 'fixture setup did not finish'}${second ? ` and ${second.workspace}` : ''}`);+ return;+ }+ if (second) removeStressBoard(second);+ if (first) removeStressBoard(first);+ });+ await withPerfSlot(async (run) => {+ const evidenceRoot = process.env.PULLBOARD_PERF_EVIDENCE_ROOT;+ first = generateStressBoard({ seed: 'named-perf-test', size: 150, ...(evidenceRoot ? { parent: evidenceRoot } : {}) });+ second = generateStressBoard({ seed: 'named-perf-test', size: 150, ...(evidenceRoot ? { parent: evidenceRoot } : {}) });++ assert.equal(first.digest, second.digest, 'the same seed and size produce the same board digest');+ assert.equal(Object.values(first.statusTotals).reduce((sum, count) => sum + count, 0), 150);+ assert.ok(Object.values(first.statusTotals).every((count) => count > 0), 'all five item states are represented');+ assert.equal(Object.values(first.laneTotals).reduce((sum, count) => sum + count, 0), 150);+ assert.ok(Object.values(first.laneTotals).every((count) => count > 0), 'all four measured lanes are represented');+ assert.ok(first.itemEvents > 150, 'the generated board contains long item histories');+ assert.ok(first.shoutCount > 0 && first.milestoneRows > 0 && first.specRows > 0, 'the generated board covers feeds, roadmap and spec data');++ const report = await run({ board: first, runs: 1, idleMs: 30_000, liveEveryMs: 5_000 });+ t.diagnostic(JSON.stringify({ performanceReport: report }));+ const expected = ['firstLoad', 'tab:shouts', 'tab:spec', 'tab:doctrine', 'tab:activity', 'tab:roadmap', 'tab:items',+ 'openSmallItem', 'openLongestHistoryItem', 'search', 'idleWithLiveWrites'];+ assert.deepEqual(report.actions.map((action) => action.name), expected);+ for (const action of report.actions) {+ assert.ok(Number.isFinite(action.medianMs) && Number.isFinite(action.worstMs), `${action.name} has a stable-paint duration`);+ assert.ok(action.samples.every((sample) => sample.stable === true), `${action.name} reached a stable visible target`);+ assert.ok(action.samples.every((sample) => sample.longTaskObserverStatus === 'available'), `${action.name} has Long Task observation available`);+ assert.ok(action.samples.every((sample) => Array.isArray(sample.longTasks)), `${action.name} reports its observed long-task entries`);+ assert.ok(action.samples.every((sample) => sample.longTasks.every((task) => Number.isFinite(task.durationMs) && task.durationMs > 50)),+ `${action.name} reports only tasks longer than 50ms`);+ assert.ok(action.samples.every((sample) => Number.isFinite(sample.largestLongTaskMs)), `${action.name} has a numeric largest long task when observation is available`);+ assert.equal(action.requestBytesPerRun.length, 1, `${action.name} reports request bytes for the run`);+ assert.ok(Number.isSafeInteger(action.requestBytesPerRun[0]), `${action.name} reports encoded response bytes`);+ assert.ok(action.samples.every((sample) => Array.isArray(sample.requests)), `${action.name} reports individual local requests`);+ }+ const firstLoad = report.actions[0].samples[0];+ const successfulFirstLoadRequests = firstLoad.requests.filter((request) =>+ request.complete && !request.failed && request.status === 200 && Number.isSafeInteger(request.responseBytes) && request.responseBytes > 0);+ assert.ok(successfulFirstLoadRequests.some((request) => request.type === 'Document' && request.path === '/'),+ 'first load captured the local document response with positive encoded bytes');+ assert.ok(successfulFirstLoadRequests.some((request) => request.method === 'GET' && request.path === '/api/v1/boards'),+ 'first load captured the board-list API response with positive encoded bytes');+ assert.ok(successfulFirstLoadRequests.some((request) => request.method === 'GET' && /^\/api\/v1\/boards\/[^/]+\/state$/u.test(request.path)),+ 'first load captured a board-state API response with positive encoded bytes');+ assert.equal(report.actions.at(-1).samples[0].liveWrites, 6, 'the idle sample includes six five-second live writes');+ assert.equal(report.actions.at(-1).samples[0].renderedWrites, 6, 'all six live writes appeared in the open feed during the idle sample');+ });+});diff --git a/test/cockpit/perf/README.md b/test/cockpit/perf/README.mdnew file mode 100644index 00000000..c567e111--- /dev/null+++ b/test/cockpit/perf/README.md@@ -0,0 +1,13 @@+# Cockpit performance harness++Run a repeatable local sample with:++```sh+node test/cockpit/perf/run.mjs --seed pullboard-perf-606 --size 3000 --runs 5 --idle 30 --live-every 5+```++The harness holds the shared browser-capable gate slot across fixture setup and measurement, creates a disposable board and machine home, starts the normal local view server, and uses an isolated real Chrome profile with real pointer and keyboard input. It measures first load, each cockpit tab, opening a small item and the longest-history item, search typing, and a 30-second idle interval while one board API writer adds a shout every five seconds. It reports each action's median and worst stable-paint time, counts Long Tasks longer than 50ms, and records resource request sizes. Unsupported Long Task observation is reported as unavailable rather than as zero tasks. The harness records measurements without applying a performance pass/fail threshold.++The default size follows the measured 605-item board shape and scales its status mix, long histories, event stream, agents, roadmap and spec rows. The named test uses 150 items to check deterministic generation and action coverage; it does not assert timing values. Use the reported output as a measurement of the specific machine and run conditions, not as a guarantee for other environments.++The generated board, home, machine state and browser profile are temporary after a successful run. Use `--keep` to retain the generated board for inspection; local view keys are kept in process memory and are not included in output. A failed run retains its private board, browser profile and failure summary for diagnosis.diff --git a/test/cockpit/perf/generate.mjs b/test/cockpit/perf/generate.mjsnew file mode 100644index 00000000..d3e87747--- /dev/null+++ b/test/cockpit/perf/generate.mjs@@ -0,0 +1,344 @@+/** Deterministically seed a disposable Pullboard board through its public board operations. */+import { createHash } from 'node:crypto';+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, dirname, join, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { loadDoctrine } from '../../../src/doctrine.js';+import { frozenCriterion, loadSpec } from '../../../src/spec.js';+import {+ ACCEPT_REASON, addItem, addMilestone, allShouts, appendFact, claim, closeBoard,+ ensureCoordinator, events, listAgents, listItems, milestones, openBoard, recordAttempt,+ register, reopen, shout, submit, verify, withdraw,+} from '../../../src/board.js';++const ROOT = resolve(import.meta.dirname, '../../..');+const BIN = join(ROOT, 'bin', 'pullboard.js');+const LANES = ['core', 'view', 'coordinator', 'docs'];+const FIXED_NOW = new Date('2026-10-01T12:00:00.000Z');+const LEASE_MS = 100 * 365 * 24 * 60 * 60 * 1000;+const STATUS_WEIGHTS = [502, 58, 30, 14, 1];+const STATUS_NAMES = ['verified', 'open', 'withdrawn', 'submitted', 'claimed'];+const LANE_WEIGHTS = [317, 199, 46, 43];++/** Hash one stable tuple for generated commits, trees, criterion digests and fact ids. */+function digest(seed, ...parts) {+ return createHash('sha256').update(JSON.stringify([seed, ...parts])).digest('hex');+}++/** Build a deterministic text body near the requested size without storing fixture randomness. */+function textOf(seed, label, targetLength) {+ const piece = `${label} ${seed} records a reviewed change with its context, expected result, and follow-up. `;+ return (piece.repeat(Math.ceil(targetLength / piece.length))).slice(0, targetLength);+}++/** Allocate all five lifecycle states proportionally while keeping each state represented. */+function statusCounts(size) {+ const totalWeight = STATUS_WEIGHTS.reduce((sum, weight) => sum + weight, 0);+ const exact = STATUS_WEIGHTS.map((weight) => size * weight / totalWeight);+ const counts = exact.map(Math.floor);+ for (let index = 0; index < counts.length; index += 1) counts[index] = Math.max(1, counts[index]);+ while (counts.reduce((sum, count) => sum + count, 0) > size) {+ const candidate = counts.map((count, index) => ({ count, index, fraction: exact[index] - Math.floor(exact[index]) }))+ .filter((entry) => entry.count > 1).sort((left, right) => left.fraction - right.fraction || right.count - left.count)[0];+ counts[candidate.index] -= 1;+ }+ while (counts.reduce((sum, count) => sum + count, 0) < size) {+ const candidate = exact.map((value, index) => ({ index, fraction: value - Math.floor(value) }))+ .sort((left, right) => right.fraction - left.fraction || left.index - right.index)[0];+ counts[candidate.index] += 1;+ exact[candidate.index] = Math.floor(exact[candidate.index]);+ }+ return Object.fromEntries(STATUS_NAMES.map((name, index) => [name, counts[index]]));+}++/** Run a fixture process with explicit arguments and a private, deterministic environment. */+function run(command, args, cwd, env) {+ const result = spawnSync(command, args, { cwd, env, encoding: 'utf8', stdio: 'pipe' });+ if (result.status !== 0 || result.signal || result.error) {+ throw new Error(`${command} ${args.join(' ')} failed with status ${result.status ?? 'null'}: ${result.stderr ?? result.error?.message ?? ''}`);+ }+ return result.stdout;+}++/** Start from a caller environment without inherited board, machine or gate identity switches. */+function cleanEnvironment() {+ return Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('PULLBOARD_')));+}++/** Build an approved spec whose row count scales with the generated board size. */+function specText(seed, size) {+ const count = Math.max(5, Math.round(size * 250 / 605));+ const rows = Array.from({ length: count }, (_, index) =>+ `- P${index + 1} [approved, must] ${textOf(seed, `Spec row ${index + 1}`, 68)} | gate: none`);+ return `# Generated stress board\n\n## P · Performance fixtures\n${rows.join('\n')}\n`;+}++/** Write a private board config with the lanes exercised by the generated items. */+function writeConfig(root) {+ const lanes = Object.fromEntries([...LANES, 'review'].map((lane) => [lane, {+ owns: lane === 'review' ? [] : [`${lane}/`], specs: lane === 'review' ? [] : ['P'],+ }]));+ const config = { name: 'Generated stress board', project: 'Pullboard performance fixture', spec: 'SPEC.md',+ gate: 'node --check bin/pullboard.js', verify: { policy: 'any', family: 'off' }, lease: '2h', lanes, shared: [] };+ writeFileSync(join(root, 'pullboard.json'), `${JSON.stringify(config, null, 2)}\n`);+}++/** Choose integer counts that follow the measured board proportions for arbitrary sizes. */+function lifecyclePlan(size) {+ const counts = statusCounts(size);+ return STATUS_NAMES.flatMap((status) => Array.from({ length: counts[status] }, () => status));+}++/** Distribute item lanes in the observed 317/199/46/43 share without clustering one lane. */+function lanePlan(size) {+ const total = LANE_WEIGHTS.reduce((sum, weight) => sum + weight, 0);+ const exact = LANE_WEIGHTS.map((weight) => size * weight / total);+ const counts = exact.map((value) => Math.max(1, Math.floor(value)));+ while (counts.reduce((sum, count) => sum + count, 0) > size) {+ const candidate = counts.map((count, index) => ({ count, index, fraction: exact[index] - Math.floor(exact[index]) }))+ .filter((entry) => entry.count > 1).sort((left, right) => left.fraction - right.fraction || right.count - left.count)[0];+ counts[candidate.index] -= 1;+ }+ const remainder = size - counts.reduce((sum, count) => sum + count, 0);+ const priority = exact.map((value, index) => ({ index, fraction: value - counts[index] }))+ .sort((left, right) => right.fraction - left.fraction || left.index - right.index);+ for (let index = 0; index < remainder; index += 1) counts[priority[index].index] += 1;+ const current = counts.map(() => 0);+ const sequence = [];+ for (let index = 0; index < size; index += 1) {+ for (let lane = 0; lane < counts.length; lane += 1) current[lane] += counts[lane];+ let selected = 0;+ for (let lane = 1; lane < counts.length; lane += 1) if (current[lane] > current[selected]) selected = lane;+ sequence.push(LANES[selected]);+ current[selected] -= size;+ }+ return { sequence, counts: Object.fromEntries(LANES.map((lane, index) => [lane, counts[index]])) };+}++/** Register a stable pool of builders, a reviewer, and the live idle writer through board APIs. */+function registerAgents(board, root, size) {+ const target = Math.min(354, Math.max(12, Math.round(size * 354 / 605)));+ const byLane = Object.fromEntries(LANES.map((lane) => [lane, lane === 'coordinator' ? ['coordinator'] : []]));+ const builderCount = Math.max(0, target - 3);+ const builderLanes = ['core', 'view', 'docs'];+ for (let index = 0; index < builderCount; index += 1) {+ const lane = builderLanes[index % builderLanes.length];+ const agent = register(board, { lane, path: join(root, '.stress', lane, String(index + 1)), route: 'strong', family: 'builder', model: 'fixture' });+ byLane[lane].push(agent);+ }+ const writer = register(board, { lane: 'view', path: join(root, '.stress', 'writer'), route: 'strong', family: 'writer', model: 'fixture' });+ byLane.view.push(writer);+ const reviewer = register(board, { lane: 'review', path: join(root, '.stress', 'reviewer'), route: 'strong', family: 'reviewer', model: 'fixture' });+ return { byLane, reviewer, writer };+}++/** Freeze a generated item with the same serialized policy shape used by real claims. */+function freezeItem(item, spec, doctrine) {+ return frozenCriterion(spec, item, doctrine);+}++/** Move one synthetic item through a committed submission using Pullboard board operations. */+function submitItem(board, id, seed, lane, builder, commitNumber, freezer) {+ const commit = digest(seed, 'commit', id, commitNumber).slice(0, 40);+ const tree = digest(seed, 'tree', id, commitNumber).slice(0, 40);+ const frozen = claim(board, id, { agentId: builder, lane,+ leaseMs: LEASE_MS, freeze: freezer, head: digest(seed, 'claim-head', id, commitNumber).slice(0, 40) });+ submit(board, id, { agentId: builder, commit, tree, files: [`generated/${id}.txt`] });+ return { commit, tree, digest: frozen.digest };+}++/** Give one synthetic item a reject, an explicit reopen, a second rejection, and final acceptance. */+function exerciseReopen(board, id, seed, lane, builder, reviewer, freezer) {+ submitItem(board, id, seed, lane, builder, 1, freezer);+ reopen(board, id, { agentId: 'coordinator', note: 'Exercise the reopened submission path in the generated board.' });+ const second = submitItem(board, id, seed, lane, builder, 2, freezer);+ verify(board, id, { agentId: reviewer, decision: 'REJECT', reason: 'BEHAVIOR_MISMATCH',+ note: 'Exercise a reject before the final generated acceptance.', head: second.commit, digest: second.digest,+ policy: 'any', familyPolicy: 'off' });+ const final = submitItem(board, id, seed, lane, builder, 3, freezer);+ verify(board, id, { agentId: reviewer, decision: 'ACCEPT', reason: ACCEPT_REASON,+ note: 'The generated state records a final accepted review.', head: final.commit, digest: final.digest,+ policy: 'any', familyPolicy: 'off', check: 'none' });+}++/** Add one fact and enough ordinary attempt records to reach the chosen item history length. */+function fillHistory(board, id, seed, agentId, targetEvents, usedEvents, factCount) {+ for (let index = 0; index < factCount; index += 1) {+ appendFact(board, id, { agentId: 'coordinator', kind: 'note', text: textOf(seed, `Fact ${index + 1} for item ${id}`, 180),+ factId: `${digest(seed, 'fact-id').slice(0, 10)}-${id}-${index + 1}` });+ }+ const attempts = Math.max(0, targetEvents - usedEvents - factCount);+ for (let index = 0; index < attempts; index += 1) {+ recordAttempt(board, id, { agentId, n: index + 1, seconds: 1 + (index % 17), result: `fixture observation ${index + 1}` });+ }+}++/** Return the canonical, path-free projection used to compare two generated boards. */+function boardSnapshot(board, seed, source, baselineEventId) {+ // Project only stable board content: the random board_id and temporary agent paths are omitted.+ // Synthetic fact IDs are supplied from seed/item/index, so the fact events remain reproducible.+ return {+ seed,+ spec: source,+ agents: listAgents(board).map(({ agent_id, agent_lane, agent_route, agent_family, agent_model }) =>+ ({ id: agent_id, lane: agent_lane, route: agent_route, family: agent_family, model: agent_model })),+ items: listItems(board, { all: true }).map((item) => ({+ id: item.item_id, parent: item.item_parent_id, lane: item.item_lane, title: item.item_title,+ criterion: item.item_criterion, specs: item.item_spec_ids, after: item.item_after, brief: item.item_brief,+ route: item.item_route, check: item.item_check, status: item.item_status, owner: item.item_owner,+ leaseUntil: item.item_lease_until, frozen: item.item_frozen, frozenDigest: item.item_frozen_digest,+ builtBy: item.item_built_by, builderFamily: item.item_builder_family, commit: item.item_commit,+ tree: item.item_tree, verdict: item.item_verdict, verifiedBy: item.item_verified_by,+ mergedCommit: item.item_merged_commit, withdrawnReason: item.item_withdrawn_reason,+ holdReason: item.item_hold_reason, holdBy: item.item_hold_by, holdAt: item.item_hold_at,+ createdBy: item.item_created_by, createdAt: item.item_created_at, updatedAt: item.item_updated_at,+ })),+ events: events(board).filter((event) => event.event_id > baselineEventId)+ .map((event) => ({ id: event.event_id, at: event.event_at, by: event.event_by, kind: event.event_kind,+ itemId: event.item_id, detail: event.event_detail })),+ shouts: allShouts(board).map((entry) => ({ id: entry.shout_id, from: entry.shout_from, to: entry.shout_to,+ text: entry.shout_text, at: entry.shout_at })),+ milestones: milestones(board),+ };+}++/** Generate a reproducible fixture in a disposable repository without writing its SQLite file directly. */+export function generateStressBoard({ seed = 'pullboard-perf-606', size = 150, parent = tmpdir() } = {}) {+ if (typeof seed !== 'string' || !seed.trim()) throw new TypeError('seed must be a nonempty string');+ if (!Number.isSafeInteger(size) || size < 5 || size > 100_000) throw new RangeError('size must be an integer from 5 through 100000');+ const workspace = mkdtempSync(join(parent, 'pullboard-stress-'));+ let board = null;+ let keepWorkspace = false;+ try {+ const root = join(workspace, 'board');+ const home = join(workspace, 'home');+ const machineHome = join(workspace, 'machine-home');+ mkdirSync(root, { recursive: true });+ mkdirSync(home, { recursive: true });+ mkdirSync(machineHome, { recursive: true });+ const canonicalRoot = realpathSync(root);+ const env = { ...cleanEnvironment(), HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'Stress fixture',+ GIT_AUTHOR_EMAIL: '[email protected]', GIT_COMMITTER_NAME: 'Stress fixture', GIT_COMMITTER_EMAIL: '[email protected]' };+ run('git', ['init', '-q', '-b', 'main'], root, env);+ run(process.execPath, [BIN, 'init', '--model', 'Stress fixture'], root, env);+ writeConfig(root);+ const source = specText(seed, size);+ writeFileSync(join(root, 'SPEC.md'), source);+ writeFileSync(join(root, 'DOCTRINE.md'), '# Performance fixture rules\n\n## Rules\n- R1 [approved, must] Keep the generated board readable. | gate: review\n');+ const spec = loadSpec(root, { spec: 'SPEC.md' });+ const doctrine = loadDoctrine(root, { practice: 'DOCTRINE.md' });+ const freezer = (item) => freezeItem(item, spec, doctrine);+ const boardFile = join(root, '.git', 'pullboard', 'board.sqlite');+ board = openBoard(boardFile, { now: () => new Date(FIXED_NOW) });+ ensureCoordinator(board, canonicalRoot);+ const initialEvent = events(board).at(-1)?.event_id ?? 0;+ const agents = registerAgents(board, root, size);+ const statuses = lifecyclePlan(size);+ const firstOpenIndex = statuses.indexOf('open');+ const longestHistoryIndex = statuses.indexOf('claimed');+ const { sequence: itemLanes, counts: laneTotals } = lanePlan(size);+ // Keep claims within ONE_CLAIM while preserving the generated lane proportions. The synthetic+ // coordinator owns its lane; move any later coordinator-lane claims onto an unused docs item.+ for (let index = 0; index < statuses.length; index += 1) {+ if (statuses[index] !== 'claimed' || itemLanes[index] !== 'coordinator') continue;+ const replacement = statuses.findIndex((status, candidate) => status !== 'claimed' && itemLanes[candidate] === 'docs');+ if (replacement < 0) throw new Error('the generated lane mix has no docs item to keep coordinator claims unique');+ [itemLanes[index], itemLanes[replacement]] = [itemLanes[replacement], itemLanes[index]];+ }+ const ids = [];+ let smallItemId = null;+ let smallItemTitle = null;+ let longestHistoryItemId = null;+ let longestHistoryTitle = null;+ const claimOrdinalByLane = Object.fromEntries(LANES.map((lane) => [lane, 0]));+ for (let index = 0; index < statuses.length; index += 1) {+ const status = statuses[index];+ const lane = itemLanes[index];+ const title = index === firstOpenIndex ? `Small item ${seed}` : `Board item ${index + 1} in ${lane}`;+ const briefLength = index === firstOpenIndex ? 500 : index === Math.floor(size / 3) ? 3_300 : 1_350;+ const id = addItem(board, { by: 'coordinator', lane, title, specIds: [`P${(index % Math.max(5, Math.round(size * 250 / 605))) + 1}`],+ criterion: `The generated board retains item ${index + 1} in ${status}.`,+ brief: textOf(seed, `Item ${index + 1} brief`, briefLength), route: 'strong' });+ ids.push(id);+ if (status === 'open' && smallItemId === null) { smallItemId = id; smallItemTitle = title; }+ if (index === longestHistoryIndex) {+ longestHistoryItemId = id;+ longestHistoryTitle = title;+ }+ const laneBuilders = agents.byLane[lane];+ const builder = laneBuilders[index % laneBuilders.length];+ let usedEvents = 1;+ if (status === 'withdrawn') {+ withdraw(board, id, { agentId: 'coordinator', reason: 'The generated board includes withdrawn work.' });+ usedEvents += 1;+ } else if (status === 'claimed') {+ const claimOrdinal = claimOrdinalByLane[lane]++;+ if (claimOrdinal >= laneBuilders.length) throw new Error(`the generated ${lane} claim count exceeds its unique fixture agents`);+ const claimBuilder = laneBuilders[claimOrdinal];+ claim(board, id, { agentId: claimBuilder, lane, leaseMs: LEASE_MS, freeze: freezer,+ head: digest(seed, 'claim-head', id, 0).slice(0, 40) });+ usedEvents += 1;+ } else if (status === 'submitted') {+ submitItem(board, id, seed, lane, builder, 1, freezer);+ usedEvents += 2;+ } else if (status === 'verified') {+ if (index === statuses.indexOf('verified')) {+ exerciseReopen(board, id, seed, lane, builder, agents.reviewer, freezer);+ usedEvents += 9;+ } else {+ const submitted = submitItem(board, id, seed, lane, builder, 1, freezer);+ verify(board, id, { agentId: agents.reviewer, decision: 'ACCEPT', reason: ACCEPT_REASON,+ note: 'The generated state records a verified review.', head: submitted.commit, digest: submitted.digest,+ policy: 'any', familyPolicy: 'off', check: 'none' });+ usedEvents += 3;+ }+ }+ const targetHistory = id === longestHistoryItemId ? 168 : index % 100 === 0 ? 37 : index % 10 === 0 ? 18 : 8;+ fillHistory(board, id, seed, builder, targetHistory, usedEvents, id === longestHistoryItemId ? 8 : index % 12 === 0 ? 2 : 0);+ }+ const shoutCount = Math.round(7_289 * size / 605);+ for (let index = 0; index < shoutCount; index += 1) {+ const text = index === 0 ? textOf(seed, 'Longest generated shout', 14_000) : textOf(seed, `Generated board update ${index + 1}`, 410);+ shout(board, { from: agents.writer, to: 'all', text, lanes: LANES });+ }+ const milestoneCount = Math.max(1, Math.round(size * 56 / 605));+ const rowCount = Math.max(milestoneCount, Math.round(size * 384 / 605));+ for (let index = 0, cursor = 0; index < milestoneCount; index += 1) {+ const itemCount = Math.floor(rowCount / milestoneCount) + (index < rowCount % milestoneCount ? 1 : 0);+ const referenced = Array.from({ length: itemCount }, () => ids[cursor++ % ids.length]);+ addMilestone(board, { agentId: 'coordinator', name: `Milestone ${index + 1}`, note: textOf(seed, `Roadmap note ${index + 1}`, 120), items: referenced });+ }+ const snapshot = boardSnapshot(board, seed, source, initialEvent);+ const boardDigest = createHash('sha256').update(JSON.stringify(snapshot)).digest('hex');+ const itemEvents = events(board).filter((event) => event.event_id > initialEvent && event.item_id !== null).length;+ const actualItems = listItems(board, { all: true });+ const statusTotals = Object.fromEntries(STATUS_NAMES.map((name) => [name, actualItems.filter((item) => item.item_status === name).length]));+ const actualLaneTotals = Object.fromEntries(LANES.map((lane) => [lane, actualItems.filter((item) => item.item_lane === lane).length]));+ if (JSON.stringify(statusTotals) !== JSON.stringify(Object.fromEntries(STATUS_NAMES.map((name) => [name, statuses.filter((status) => status === name).length])))) {+ throw new Error('the generated board lifecycle does not match its planned state counts');+ }+ if (JSON.stringify(actualLaneTotals) !== JSON.stringify(laneTotals)) throw new Error('the generated board lanes do not match their planned counts');+ const manifest = { version: 1, seed, size, digest: boardDigest, root, home, machineHome, boardFile, parent: resolve(parent),+ smallItemId, smallItemTitle, longestHistoryItemId, longestHistoryTitle, liveWriter: agents.writer, itemEvents, shoutCount,+ milestoneCount, milestoneRows: rowCount, specRows: Math.max(5, Math.round(size * 250 / 605)), statusTotals, laneTotals: actualLaneTotals,+ agentCount: listAgents(board).length };+ writeFileSync(join(workspace, 'stress-board.json'), `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 });+ keepWorkspace = true;+ return { ...manifest, workspace, env };+ } finally {+ if (board) closeBoard(board);+ if (!keepWorkspace) rmSync(workspace, { recursive: true, force: true });+ }+}++/** Remove only the temporary directory created by generateStressBoard. */+export function removeStressBoard(board) {+ const workspace = typeof board?.workspace === 'string' ? resolve(board.workspace) : '';+ const parent = typeof board?.parent === 'string' ? resolve(board.parent) : resolve(tmpdir());+ if (!workspace || dirname(workspace) !== parent || !basename(workspace).startsWith('pullboard-stress-')) {+ throw new Error('refusing to remove a path that was not created as a stress fixture');+ }+ rmSync(board.workspace, { recursive: true, force: true });+}diff --git a/test/cockpit/perf/run.mjs b/test/cockpit/perf/run.mjsnew file mode 100644index 00000000..bc8749c6--- /dev/null+++ b/test/cockpit/perf/run.mjs@@ -0,0 +1,549 @@+/** Measure each frozen cockpit action on a generated board in an isolated machine and browser profile. */+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { spawn } from 'node:child_process';+import { parseArgs } from 'node:util';+import { fileURLToPath } from 'node:url';+import { performance as nodePerformance } from 'node:perf_hooks';+import { closeBoard, openBoard, shout } from '../../../src/board.js';+import * as gate from '../../../src/gate.js';+import * as resources from '../../../src/resources.js';+import { findChromeExecutable, startChrome } from '../../chrome-fixture.js';+import { press, stableChrome } from '../stable.js';+import { generateStressBoard, removeStressBoard } from './generate.mjs';++const ROOT = resolve(import.meta.dirname, '../../..');+const BIN = join(ROOT, 'bin', 'pullboard.js');+const ACTION_TIMEOUT_MS = 60_000;+const VIEW_START_TIMEOUT_MS = 30_000;+const VIEW_STOP_TIMEOUT_MS = 5_000;+const LANES = ['core', 'view', 'coordinator', 'docs'];+const VIEWER_ACTIONS = [+ ['tab:shouts', 'shouts', '#feed .shout'],+ ['tab:spec', 'spec', '#spec-list .row'],+ ['tab:doctrine', 'doctrine', '#doctrine-list .row'],+ ['tab:activity', 'activity', '#activity > *'],+ ['tab:roadmap', 'roadmap', '#roadmap .milestone'],+ ['tab:items', 'items', '#chain .row'],+];++/** Hold the real shared browser pool for fixture setup, Chrome actions and teardown. */+export async function withPerfSlot(action) {+ if (typeof action !== 'function') throw new TypeError('the performance slot needs an action');+ if (typeof resources.gateSlotEnvironment !== 'function') {+ throw new Error('the browser-capable shared gate API is unavailable; merge the current resource-pool update before running the performance harness');+ }+ return gate.withGateSlot(ROOT, async (lease) => {+ const proofEnvironment = resources.gateSlotEnvironment(lease);+ if (lease.browser !== true || proofEnvironment[resources.BROWSER_SLOT_HELD_ENV] !== '1') {+ throw new Error('the performance harness needs a live browser-capable shared gate slot');+ }+ return action((options) => runPerfHarnessInSlot(options, lease));+ }, { browser: true, item: '606', kind: 'cockpit-performance' });+}++/** Install page-side input timestamps, Long Task observation and safe request-size collection. */+function timingScript() {+ return `(() => {+ const state = window.__pb606 = { active: null, marks: Object.create(null), tasks: [] };+ const mark = eventType => event => {+ if (state.active?.eventType === eventType && state.marks[state.active.name] === null) {+ state.marks[state.active.name] = performance.now();+ }+ };+ addEventListener('mousedown', mark('mousedown'), true);+ addEventListener('keydown', mark('keydown'), true);+ try {+ state.longTaskObserver = new PerformanceObserver(list => state.tasks.push(...list.getEntries().map(entry => ({ startTime: entry.startTime, duration: entry.duration }))));+ state.longTaskObserver.observe({ type: 'longtask', buffered: true });+ state.longTaskObserverStatus = 'available';+ } catch (error) {+ state.longTaskObserverStatus = 'unsupported';+ state.longTaskObserverError = error?.name ?? 'unknown';+ }+ performance.setResourceTimingBufferSize(10000);+ window.__pb606Begin = (name, eventType) => { state.active = { name, eventType }; state.marks[name] = null; };+ window.__pb606Collect = (name, startAt, endAt, stable) => {+ state.tasks.push(...(state.longTaskObserver?.takeRecords() ?? []).map(entry => ({ startTime: entry.startTime, duration: entry.duration })));+ const tasks = state.tasks.filter(entry => entry.startTime < endAt && entry.startTime + entry.duration > startAt && entry.duration > 50)+ .map(entry => ({ startMs: entry.startTime - startAt, durationMs: entry.duration }));+ return { name, stable, startMs: startAt, endMs: endAt, durationMs: endAt - startAt,+ longTaskObserverStatus: state.longTaskObserverStatus,+ longTaskObserverError: state.longTaskObserverError ?? null,+ longTasks: tasks,+ largestLongTaskMs: state.longTaskObserverStatus === 'available' ? Math.max(0, ...tasks.map(entry => entry.durationMs)) : null,+ timeOrigin: performance.timeOrigin,+ longTaskObserverUnavailable: state.longTaskObserverStatus !== 'available' };+ };+ })()`;+}++/** Attach a private CDP observer that retains local request paths and actual encoded response byte counts. */+async function openNetworkCapture(profile, localOrigin) {+ const port = Number(readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0]);+ if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) throw new Error('isolated Chrome did not publish a valid local DevTools port');+ const targetsResponse = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(5_000) });+ if (!targetsResponse.ok) throw new Error('isolated Chrome did not return its local page target');+ const targets = await targetsResponse.json();+ const target = targets.find((entry) => entry.type === 'page' && entry.url === 'about:blank' && typeof entry.webSocketDebuggerUrl === 'string');+ if (!target) throw new Error('isolated Chrome has no blank page target for local network observation');+ const socket = new WebSocket(target.webSocketDebuggerUrl);+ const records = [];+ const active = new Map();+ const commands = new Map();+ let nextCommand = 0;+ let closed = false;+ const opened = new Promise((resolveOpen, rejectOpen) => {+ const timeout = setTimeout(() => rejectOpen(new Error('local Chrome network observer did not connect')), 5_000);+ socket.addEventListener('open', () => { clearTimeout(timeout); resolveOpen(); }, { once: true });+ socket.addEventListener('error', () => { clearTimeout(timeout); rejectOpen(new Error('local Chrome network observer failed to connect')); }, { once: true });+ socket.addEventListener('close', () => { clearTimeout(timeout); rejectOpen(new Error('local Chrome network observer closed before connecting')); }, { once: true });+ });+ socket.addEventListener('message', (event) => {+ let message;+ try { message = JSON.parse(String(event.data)); } catch { return; }+ if (message.id !== undefined) {+ const pending = commands.get(message.id);+ if (!pending) return;+ commands.delete(message.id);+ clearTimeout(pending.timer);+ if (message.error) pending.reject(new Error('local Chrome network observation command failed'));+ else pending.resolve(message.result);+ return;+ }+ const params = message.params ?? {};+ if (message.method === 'Network.requestWillBeSent') {+ if (params.redirectResponse) {+ const redirected = active.get(params.requestId);+ if (redirected) {+ redirected.status = params.redirectResponse.status ?? null;+ redirected.responseBytes = Number.isFinite(params.redirectResponse.encodedDataLength)+ ? params.redirectResponse.encodedDataLength : redirected.receivedBytes;+ redirected.complete = true;+ redirected.redirect = true;+ redirected.finishedWallTimeMs = Number.isFinite(params.timestamp) && Number.isFinite(redirected.startTimestamp)+ ? redirected.startWallTimeMs + (params.timestamp - redirected.startTimestamp) * 1_000 : null;+ }+ }+ let url;+ try { url = new URL(params.request?.url); } catch { active.delete(params.requestId); return; }+ if (url.origin !== localOrigin) { active.delete(params.requestId); return; }+ const request = { path: url.pathname, method: params.request?.method ?? 'OTHER', type: params.type ?? 'Other',+ startWallTimeMs: Number.isFinite(params.wallTime) ? params.wallTime * 1_000 : null,+ startTimestamp: params.timestamp ?? null, status: null, responseBytes: null, receivedBytes: 0,+ chunks: [], complete: false, failed: false };+ records.push(request);+ active.set(params.requestId, request);+ return;+ }+ const request = active.get(params.requestId);+ if (!request) return;+ if (message.method === 'Network.responseReceived') request.status = params.response?.status ?? null;+ if (message.method === 'Network.dataReceived' && Number.isFinite(params.encodedDataLength)) {+ request.receivedBytes += params.encodedDataLength;+ request.chunks.push({ atWallTimeMs: Number.isFinite(params.timestamp) && Number.isFinite(request.startTimestamp)+ ? request.startWallTimeMs + (params.timestamp - request.startTimestamp) * 1_000 : null,+ bytes: params.encodedDataLength });+ }+ if (message.method === 'Network.loadingFinished') {+ request.responseBytes = Number.isFinite(params.encodedDataLength) ? params.encodedDataLength : request.receivedBytes;+ request.complete = true;+ request.finishedWallTimeMs = Number.isFinite(params.timestamp) && Number.isFinite(request.startTimestamp)+ ? request.startWallTimeMs + (params.timestamp - request.startTimestamp) * 1_000 : null;+ request.durationMs = Number.isFinite(params.timestamp) && Number.isFinite(request.startTimestamp)+ ? Math.max(0, (params.timestamp - request.startTimestamp) * 1_000) : null;+ active.delete(params.requestId);+ }+ if (message.method === 'Network.loadingFailed') {+ request.responseBytes = request.receivedBytes;+ request.complete = true;+ request.failed = true;+ request.finishedWallTimeMs = Number.isFinite(params.timestamp) && Number.isFinite(request.startTimestamp)+ ? request.startWallTimeMs + (params.timestamp - request.startTimestamp) * 1_000 : null;+ active.delete(params.requestId);+ }+ });+ const send = (method, params = {}) => new Promise((resolveCommand, rejectCommand) => {+ const id = ++nextCommand;+ const timer = setTimeout(() => {+ commands.delete(id);+ rejectCommand(new Error('local Chrome network observation command timed out'));+ }, 5_000);+ commands.set(id, { resolve: resolveCommand, reject: rejectCommand, timer });+ socket.send(JSON.stringify({ id, method, params }));+ });+ try {+ await opened;+ await send('Network.enable');+ } catch (error) {+ socket.close();+ throw error;+ }+ return {+ snapshot(name, startMs, endMs, timeOrigin) {+ const firstLoad = name === 'firstLoad';+ const requests = records.map((request) => {+ if (!Number.isFinite(request.startWallTimeMs)) return false;+ const relative = request.startWallTimeMs - timeOrigin;+ const beganInAction = (firstLoad ? relative >= -5_000 : relative >= startMs) && relative <= endMs;+ const chunks = request.chunks.filter((chunk) => Number.isFinite(chunk.atWallTimeMs)+ && chunk.atWallTimeMs - timeOrigin >= startMs && chunk.atWallTimeMs - timeOrigin <= endMs);+ if (!beganInAction && !chunks.length) return null;+ const completedDuringAction = Number.isFinite(request.finishedWallTimeMs)+ && request.finishedWallTimeMs - timeOrigin >= startMs && request.finishedWallTimeMs - timeOrigin <= endMs;+ const completedForFirstLoad = firstLoad && request.complete && !request.failed+ && Number.isFinite(request.finishedWallTimeMs) && request.finishedWallTimeMs - timeOrigin <= endMs;+ const responseBytes = completedForFirstLoad || (beganInAction && request.complete && completedDuringAction)+ ? request.responseBytes : chunks.reduce((sum, chunk) => sum + chunk.bytes, 0);+ return { path: request.path, method: request.method, type: request.type, status: request.status,+ responseBytes, complete: request.complete, failed: request.failed,+ startMs: relative - startMs, durationMs: request.durationMs ?? null };+ }).filter(Boolean);+ return { requests, requestBytes: requests.reduce((sum, request) => sum + request.responseBytes, 0),+ incompleteRequests: requests.filter((request) => !request.complete).length };+ },+ close() {+ if (closed) return;+ closed = true;+ for (const pending of commands.values()) {+ clearTimeout(pending.timer);+ pending.reject(new Error('local Chrome network observer closed'));+ }+ commands.clear();+ socket.close();+ },+ };+}++/** Wait for the named target and condition to remain visibly unchanged for two animation frames. */+async function waitPaintedAndStable(raw, network, name, selector, condition, firstLoad = false) {+ const expression = `(() => {+ const name = ${JSON.stringify(name)}, selector = ${JSON.stringify(selector)};+ const startAt = ${firstLoad ? '0' : `window.__pb606?.marks[${JSON.stringify(name)}]`};+ if (!Number.isFinite(startAt)) throw new Error('the measured input event was not observed');+ const deadline = performance.now() + ${ACTION_TIMEOUT_MS};+ return new Promise((resolve, reject) => {+ let previous = '', stableFrames = 0;+ const sample = () => {+ const node = document.querySelector(selector);+ const style = node ? getComputedStyle(node) : null;+ const rect = node?.getBoundingClientRect();+ const ready = !!node && !!rect && !node.closest('[hidden]') && !document.body.classList.contains('switching') && style.display !== 'none'+ && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0 && (${condition});+ const signature = ready ? JSON.stringify([rect.x, rect.y, rect.width, rect.height,+ node.childElementCount, node.textContent.length]) : '';+ stableFrames = signature && signature === previous ? stableFrames + 1 : 0;+ previous = signature;+ if (stableFrames >= 2) {+ const endAt = performance.now();+ resolve(window.__pb606Collect(name, startAt, endAt, true));+ return;+ }+ if (performance.now() >= deadline) { reject(new Error('the named target did not become visibly stable')); return; }+ requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+ });+ })()`;+ const measurement = await raw.evaluate(expression, `measure ${name}`, ACTION_TIMEOUT_MS + 1_000);+ return { ...measurement, ...network.snapshot(name, measurement.startMs, measurement.endMs, measurement.timeOrigin) };+}++/** Give the browser a bounded wait without leaving a timer after the requested idle window. */+function pause(ms) {+ return new Promise((resolvePause) => setTimeout(resolvePause, ms)); // budget: the required idle observation lasts exactly the configured 30000ms by default.+}++/** Start the generated board's foreground view server without exposing its local key in diagnostics. */+async function startView(board) {+ const env = { ...board.env, PULLBOARD_VIEW_FOREGROUND: '1' };+ const child = spawn(process.execPath, [BIN, 'view', '--no-open', '--port', '0'], {+ cwd: board.root, env, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let output = '';+ let stderr = '';+ let spawnError = null;+ let closeResult = null;+ const closed = new Promise((resolveClosed) => child.once('close', (code, signal) => {+ closeResult = { code, signal };+ resolveClosed(closeResult);+ }));+ child.once('error', (error) => { spawnError = error; });+ child.stdout.setEncoding('utf8').on('data', (chunk) => { output = `${output}${chunk}`.slice(-16_384); });+ child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr = `${stderr}${chunk}`.slice(-4_096); });+ const deadline = Date.now() + VIEW_START_TIMEOUT_MS;+ while (Date.now() < deadline && !spawnError && !closeResult) {+ const match = /Pullboard view: (http:\/\/127\.0\.0\.1:\d+\/\?k=[^\s]+)/u.exec(output);+ if (match) return { child, closed, link: new URL(match[1]), stderr: () => stderr };+ await pause(25); // budget: polling bounds discovery of the fixture server URL, not product speed.+ }+ await stopView({ child, closed });+ throw new Error(`the isolated view did not publish a local link within ${VIEW_START_TIMEOUT_MS}ms${spawnError ? '; child could not start' : closeResult ? `; it exited with status ${closeResult.code ?? 'null'}` : ''}`);+}++/** Stop the one view process started by this harness and wait for its direct child to close. */+async function stopView(view) {+ if (view.child.exitCode === null && view.child.signalCode === null) {+ try { view.child.kill('SIGTERM'); } catch { /* The owned CLI process may have exited between the check and signal. */ }+ }+ const waitForClose = async (timeoutMs) => {+ let timer;+ const result = await Promise.race([view.closed.then(() => true), new Promise((resolveClose) => {+ timer = setTimeout(() => resolveClose(false), timeoutMs);+ })]);+ clearTimeout(timer);+ return result;+ };+ const result = await waitForClose(VIEW_STOP_TIMEOUT_MS);+ if (!result) {+ try { view.child.kill('SIGKILL'); } catch { /* The owned CLI process may have exited before escalation. */ }+ const killed = await waitForClose(VIEW_STOP_TIMEOUT_MS);+ if (!killed) throw new Error('the isolated view did not close after bounded cleanup');+ }+}++/** Record one real CDP key event so the search action includes its actual typing cadence. */+async function typeKey(chrome, value) {+ const code = `Key${value.toUpperCase()}`;+ const keyCode = value.toUpperCase().charCodeAt(0);+ await chrome.send('Input.dispatchKeyEvent', { type: 'keyDown', key: value, code, windowsVirtualKeyCode: keyCode, text: value, unmodifiedText: value });+ await chrome.send('Input.dispatchKeyEvent', { type: 'keyUp', key: value, code, windowsVirtualKeyCode: keyCode });+}++/** Begin measuring the next native input of the requested type without including setup waits. */+async function beginAction(raw, name, eventType) {+ await raw.evaluate(`window.__pb606Begin(${JSON.stringify(name)}, ${JSON.stringify(eventType)})`, `arm ${name}`, 2_000);+}++/** Capture one run's first load, six tabs, two item opens, search and live idle interval. */+async function measureRun(board, runIndex, executable, idleMs, liveEveryMs) {+ const profile = join(board.workspace, `chrome-${runIndex + 1}`);+ mkdirSync(profile, { recursive: true, mode: 0o700 });+ let view = null;+ let raw = null;+ let chrome = null;+ let network = null;+ let measurementError = null;+ const actions = [];+ try {+ view = await startView(board);+ raw = await startChrome({ url: 'about:blank', executable, profileDirectory: profile,+ commandTimeoutMs: ACTION_TIMEOUT_MS, taskTimeoutMs: ACTION_TIMEOUT_MS,+ env: { HOME: profile, PATH: process.env.PATH ?? '/usr/bin:/bin', LANG: process.env.LANG ?? 'en_US.UTF-8' } });+ network = await openNetworkCapture(raw.profileDirectory, view.link.origin);+ await raw.send('Network.setCacheDisabled', { cacheDisabled: true }, 'disable the fresh profile cache', ACTION_TIMEOUT_MS);+ await raw.send('Page.addScriptToEvaluateOnNewDocument', { source: timingScript() }, 'install performance observers', ACTION_TIMEOUT_MS);+ const browserVersion = await raw.send('Browser.getVersion', {}, 'pin the isolated browser runtime', ACTION_TIMEOUT_MS);+ chrome = await stableChrome(raw);+ await raw.navigate(view.link.href);+ actions.push(await waitPaintedAndStable(raw, network, 'firstLoad', '#chain .row',+ `document.readyState === 'complete' && !document.body.classList.contains('loading')`, true));++ for (const [name, tab, target] of VIEWER_ACTIONS) {+ await beginAction(raw, name, 'mousedown');+ await press(chrome, `document.querySelector('[data-tab="${tab}"]')`);+ actions.push(await waitPaintedAndStable(raw, network, name, target,+ `document.querySelector('.tab.on')?.dataset.tab === ${JSON.stringify(tab)}`));+ }++ const smallRow = `document.querySelector('#chain .row[data-item="${board.smallItemId}"]')`;+ await beginAction(raw, 'openSmallItem', 'mousedown');+ await press(chrome, smallRow);+ actions.push(await waitPaintedAndStable(raw, network, 'openSmallItem', '#detail .stack',+ `view.item === ${board.smallItemId} && document.querySelector('#detail .stack h2')?.textContent.includes(${JSON.stringify(board.smallItemTitle)})`));++ const longRow = `document.querySelector('#chain .row[data-item="${board.longestHistoryItemId}"]')`;+ await beginAction(raw, 'openLongestHistoryItem', 'mousedown');+ await press(chrome, longRow);+ actions.push(await waitPaintedAndStable(raw, network, 'openLongestHistoryItem', '#detail .stack',+ `view.item === ${board.longestHistoryItemId} && document.querySelector('#detail .stack h2')?.textContent.includes(${JSON.stringify(board.longestHistoryTitle)})`));++ await press(chrome, "document.querySelector('#q')");+ await beginAction(raw, 'search', 'keydown');+ for (const character of 'Small') {+ await typeKey(chrome, character);+ await pause(90); // budget: reproduce the measured person's 90ms key cadence; the search sample starts at the first keydown.+ }+ actions.push(await waitPaintedAndStable(raw, network, 'search', '#find-results [data-find]',+ `document.querySelector('#q').value === 'Small' && !document.querySelector('#find-results').hidden`));++ await beginAction(raw, 'idleSetup', 'mousedown');+ await press(chrome, "document.querySelector('[data-tab=\"shouts\"]')");+ await waitPaintedAndStable(raw, network, 'idleSetup', '#feed .shout',+ `document.querySelector('.tab.on')?.dataset.tab === 'shouts'`);+ const liveMessages = Array.from({ length: Math.ceil(idleMs / liveEveryMs) }, (_, index) =>+ `Live stress update ${index + 1} for seed ${board.seed}, run ${runIndex + 1}.`);+ await raw.evaluate(`(() => {+ const feed = document.querySelector('#feed');+ if (!feed) throw new Error('the shouts feed is unavailable for the live observation');+ window.__pb606IdleExpected = new Map(${JSON.stringify(liveMessages)}.map(text => [text, null]));+ const scan = () => {+ const text = feed.textContent;+ for (const [message, at] of window.__pb606IdleExpected) {+ if (at === null && text.includes(message)) window.__pb606IdleExpected.set(message, performance.now());+ }+ };+ window.__pb606IdleScan = scan;+ window.__pb606IdleObserver = new MutationObserver(scan);+ window.__pb606IdleObserver.observe(feed, { childList: true, subtree: true, characterData: true });+ scan();+ if ([...window.__pb606IdleExpected.values()].some(at => at !== null)) {+ throw new Error('a live update marker was already present before this idle sample');+ }+ })()`, 'observe live feed updates', 2_000);+ let liveBoard = null;+ let liveWrites = 0;+ const idleStart = await raw.evaluate('performance.now()', 'start live idle window', 2_000);+ const wallStart = nodePerformance.now();+ const liveWriteOffsetsMs = [];+ try {+ liveBoard = openBoard(board.boardFile);+ for (let targetMs = 0; targetMs < idleMs; targetMs += liveEveryMs) {+ const delay = wallStart + targetMs - nodePerformance.now();+ if (delay > 0) await pause(delay); // budget: each write remains on a fixed wall-clock cadence inside the 30-second sample.+ const text = liveMessages[liveWrites];+ shout(liveBoard, { from: board.liveWriter, to: 'all', text, lanes: LANES });+ liveWrites += 1;+ liveWriteOffsetsMs.push(nodePerformance.now() - wallStart);+ }+ const remaining = wallStart + idleMs - nodePerformance.now();+ if (remaining > 0) await pause(remaining); // budget: retain the full 30-second idle observation after the sixth write.+ } finally {+ if (liveBoard) closeBoard(liveBoard);+ }+ const idleEnd = await raw.evaluate('performance.now()', 'finish live idle window', 2_000);+ const renderedAtMs = await raw.evaluate(`(() => { window.__pb606IdleScan?.(); return [...(window.__pb606IdleExpected ?? new Map())].map(([text, at]) => ({ text, at })); })()`, 'collect visible live writes', 2_000);+ const renderedWrites = renderedAtMs.filter(({ at }) => Number.isFinite(at) && at <= idleEnd).length;+ const idle = await raw.evaluate(`window.__pb606Collect('idleWithLiveWrites', ${idleStart}, ${idleEnd}, true)`, 'collect live idle metrics', 5_000);+ idle.renderedWrites = renderedWrites;+ idle.liveWriteOffsetsMs = liveWriteOffsetsMs;+ idle.renderedAtMs = renderedAtMs.map(({ at }) => Number.isFinite(at) ? at - idleStart : null);+ Object.assign(idle, network.snapshot('idleWithLiveWrites', idleStart, idleEnd, idle.timeOrigin));+ idle.liveWrites = liveWrites;+ actions.push(idle);+ actions.browserVersion = browserVersion;+ return actions;+ } catch (error) {+ measurementError = error;+ throw error;+ } finally {+ const cleanupErrors = [];+ try { network?.close(); } catch (error) { cleanupErrors.push(`network observer: ${error.message}`); }+ try { if (raw) await raw.close(); } catch (error) { cleanupErrors.push(`Chrome connection: ${error.message}`); }+ try { if (view) await stopView(view); } catch (error) { cleanupErrors.push(`view process: ${error.message}`); }+ if (measurementError || cleanupErrors.length) {+ const failurePath = join(board.workspace, `run-${runIndex + 1}-failure.json`);+ try {+ writeFileSync(failurePath, `${JSON.stringify({ version: 1, run: runIndex + 1,+ error: measurementError?.message ?? 'cleanup failed', cleanupErrors, actions,+ chromeProfile: profile }, null, 2)}\n`, { mode: 0o600 });+ } catch (error) { cleanupErrors.push(`failure record: ${error.message}`); }+ if (measurementError && cleanupErrors.length) measurementError.cleanupErrors = cleanupErrors;+ else if (cleanupErrors.length) throw new AggregateError(cleanupErrors.map((message) => new Error(message)), 'the performance harness cleanup did not finish cleanly');+ }+ }+}++/** Return the median of a nonempty numeric sample. */+function median(values) {+ const ordered = [...values].sort((left, right) => left - right);+ const middle = Math.floor(ordered.length / 2);+ return ordered.length % 2 ? ordered[middle] : (ordered[middle - 1] + ordered[middle]) / 2;+}++/** Summarize action samples without adding any pass/fail latency threshold. */+function summarize(runs) {+ const labels = runs[0].map((entry) => entry.name);+ return labels.map((name) => {+ const samples = runs.map((entries) => entries.find((entry) => entry.name === name));+ const durations = samples.map((entry) => entry.durationMs);+ const statuses = samples.map((entry) => ({ status: entry.longTaskObserverStatus ?? 'unsupported', error: entry.longTaskObserverError ?? null }));+ const allLongTaskSamplesAvailable = statuses.every(({ status }) => status === 'available');+ const longCounts = samples.map((entry, index) => statuses[index].status === 'available' ? entry.longTasks.length : null);+ return { name, medianMs: median(durations), worstMs: Math.max(...durations),+ longTaskStatusPerRun: statuses,+ medianLongTasks: allLongTaskSamplesAvailable ? median(longCounts) : null,+ worstLongTasks: allLongTaskSamplesAvailable ? Math.max(...longCounts) : null,+ largestLongTaskMs: allLongTaskSamplesAvailable ? Math.max(...samples.map((entry) => entry.largestLongTaskMs)) : null,+ requestBytesPerRun: samples.map((entry) => entry.requestBytes),+ requestsPerRun: samples.map((entry) => entry.requests),+ samples };+ });+}++/** Render the same action summaries as a compact Markdown table for the terminal. */+function renderTable(actions) {+ const lines = ['| action | median stable ms | worst stable ms | long tasks / run (median, worst) | largest long task ms | request bytes / run |',+ '|---|---:|---:|---:|---:|---:|'];+ for (const action of actions) {+ const longTaskCount = Number.isFinite(action.medianLongTasks)+ ? `${action.medianLongTasks}, ${action.worstLongTasks}` : 'unavailable';+ const largestLongTask = Number.isFinite(action.largestLongTaskMs) ? action.largestLongTaskMs.toFixed(1) : 'unavailable';+ lines.push(`| ${action.name} | ${action.medianMs.toFixed(1)} | ${action.worstMs.toFixed(1)} | ${longTaskCount} | ${largestLongTask} | ${action.requestBytesPerRun.join(', ')} |`);+ }+ return lines.join('\n');+}++/** Run the user-facing harness with an isolated generated board and headless real Chrome. */+async function runPerfHarnessInSlot({ board, runs = 1, idleMs = 30_000, liveEveryMs = 5_000,+ executable = findChromeExecutable() } = {}, lease) {+ if (!board?.workspace || !board?.boardFile) throw new TypeError('board must come from generateStressBoard');+ if (!Number.isSafeInteger(runs) || runs < 1 || runs > 20) throw new RangeError('runs must be an integer from 1 through 20');+ if (!Number.isSafeInteger(idleMs) || idleMs < 0 || idleMs > 300_000) throw new RangeError('idleMs must be an integer from 0 through 300000');+ if (!Number.isSafeInteger(liveEveryMs) || liveEveryMs < 1_000 || liveEveryMs > 60_000) throw new RangeError('liveEveryMs must be an integer from 1000 through 60000');+ if (!executable) throw new Error('Chrome was not found; install Chrome or set PULLBOARD_CHROME.');+ const capture = async (lease) => {+ const captured = [];+ for (let index = 0; index < runs; index += 1) captured.push(await measureRun(board, index, executable, idleMs, liveEveryMs));+ const actions = summarize(captured);+ const report = { version: 1, seed: board.seed, size: board.size, digest: board.digest,+ gate: { browser: lease.browser === true, waitMs: lease.waitMs },+ boardShape: { statuses: board.statusTotals, lanes: board.laneTotals, agents: board.agentCount,+ itemEvents: board.itemEvents, shouts: board.shoutCount, milestones: board.milestoneCount,+ milestoneRows: board.milestoneRows, specRows: board.specRows }, runs, idleMs, liveEveryMs,+ browser: { input: 'real Chrome through CDP', executable, versions: captured.map(run => run.browserVersion) },+ actions, table: renderTable(actions) };+ writeFileSync(join(board.workspace, 'performance-report.json'), `${JSON.stringify(report, null, 2)}\n`, { mode: 0o600 });+ return report;+ };+ return capture(lease);+}++/** Run the complete browser sample while owning the shared browser-capable slot. */+export async function runPerfHarness(options = {}) {+ return withPerfSlot((run) => run(options));+}++/** Parse and execute the standalone command when this file is the program entry point. */+async function main(argv) {+ const parsed = parseArgs({ args: argv, options: {+ seed: { type: 'string', default: 'pullboard-perf-606' }, size: { type: 'string', default: '3000' },+ runs: { type: 'string', default: '5' }, idle: { type: 'string', default: '30' }, liveEvery: { type: 'string', default: '5' },+ keep: { type: 'boolean', default: false }, help: { type: 'boolean', default: false },+ } });+ if (parsed.values.help) {+ process.stdout.write('Usage: node test/cockpit/perf/run.mjs [--seed text] [--size 3000] [--runs 5] [--idle 30] [--live-every 5] [--keep]\n');+ return;+ }+ let board = null;+ let completed = false;+ try {+ await withPerfSlot(async (run) => {+ board = generateStressBoard({ seed: parsed.values.seed, size: Number(parsed.values.size) });+ try {+ const report = await run({ board, runs: Number(parsed.values.runs), idleMs: Number(parsed.values.idle) * 1_000,+ liveEveryMs: Number(parsed.values.liveEvery) * 1_000 });+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n\n${report.table}\n`);+ if (parsed.values.keep) process.stdout.write(`Generated board kept at ${board.root}\n`);+ completed = true;+ } finally {+ if (!parsed.values.keep && completed) removeStressBoard(board);+ }+ });+ } catch (error) {+ if (board && !completed) process.stderr.write(`Performance evidence retained at ${board.workspace}\n`);+ throw error;+ }+}++if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) await main(process.argv.slice(2));