From 4e5c3cb165eafda107363767fb172ae3b56d6d0d Mon Sep 17 00:00:00 2001 From: Knotty Wyvern Date: Thu, 29 Oct 2026 15:52:19 -0700 Subject: [PATCH] Add the memory and response measurement of native features - scripts/measureFeatures.mjs starts a test build with remote debugging, runs each scenario 3 times, and writes the medians to output/phase-7//. - It records the private bytes and the working set of the process tree, the JS heap, the start time, the first-need time, and long tasks. - It refuses the installed RuneStone and its identifier, and it stops only the process tree that it started. - Plugin mode installs the plugin ZIPs through a local Gitea-format server. Native mode uses the features settings section. --- scripts/measure/app.mjs | 145 +++++++++++ scripts/measure/core.mjs | 157 ++++++++++++ scripts/measure/fixture.mjs | 201 ++++++++++++++++ scripts/measure/giteaServer.mjs | 47 ++++ scripts/measure/pdf.mjs | 45 ++++ scripts/measure/png.mjs | 80 +++++++ scripts/measure/processes.mjs | 25 ++ scripts/measure/scenarios.mjs | 167 +++++++++++++ scripts/measureFeatures.mjs | 264 +++++++++++++++++++++ tests/unit/release/measureFeatures.spec.ts | 167 +++++++++++++ 10 files changed, 1298 insertions(+) create mode 100644 scripts/measure/app.mjs create mode 100644 scripts/measure/core.mjs create mode 100644 scripts/measure/fixture.mjs create mode 100644 scripts/measure/giteaServer.mjs create mode 100644 scripts/measure/pdf.mjs create mode 100644 scripts/measure/png.mjs create mode 100644 scripts/measure/processes.mjs create mode 100644 scripts/measure/scenarios.mjs create mode 100644 scripts/measureFeatures.mjs create mode 100644 tests/unit/release/measureFeatures.spec.ts diff --git a/scripts/measure/app.mjs b/scripts/measure/app.mjs new file mode 100644 index 0000000..081a6f7 --- /dev/null +++ b/scripts/measure/app.mjs @@ -0,0 +1,145 @@ +// Start the test build, attach to its WebView2 through CDP, read the metrics, and stop only the started process tree. +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import path from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import { playwright } from "../../tests/smoke/_harness/index.mjs"; +import { processTree } from "./core.mjs"; +import { listProcesses, stopTree } from "./processes.mjs"; +import { TABLE } from "./scenarios.mjs"; + +const isMainPage = page => { try { const url = new URL(page.url()); return url.pathname === "/" && !url.search && url.protocol.startsWith("http"); } catch { return false; } }; + +async function cdpResponds(port) { + try { + const response = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) }); + return response.ok; + } catch { return false; } +} + +/** Call a Rust command from the page. */ +export function invoke(page, command, args = {}) { + return page.evaluate(([command, args]) => window.__TAURI_INTERNALS__.invoke(command, args), [command, args]); +} + +/** + * Start `exe` with remote debugging on `port` and attach to its main page. + * Refuse when another program already answers on the port, because the tool must not drive a foreign browser. + */ +export async function launch({ exe, port, timeout = 90000 }) { + if (await cdpResponds(port)) throw new Error(`Port ${port} already answers CDP requests. Stop that program or choose another --port.`); + const env = { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}`, NO_PROXY: "127.0.0.1,localhost", no_proxy: "127.0.0.1,localhost" }; + const started = performance.now(); + const startedAt = Date.now(); + const child = spawn(exe, [], { env, cwd: path.dirname(exe), stdio: "ignore", windowsHide: false }); + let exited = null; + child.on("exit", code => { exited = code ?? -1; }); + child.on("error", error => { exited = String(error); }); + await new Promise(resolve => child.once("spawn", resolve).once("error", resolve)); + const app = { child, pid: child.pid, started, startedAt, browser: null, page: null, cdpMs: null }; + if (!app.pid) throw new Error(`Cannot start ${exe}: ${exited}`); + try { + const { chromium } = playwright(); + while (!app.browser) { + if (exited !== null) throw new Error(`The app stopped during the start (exit ${exited}).`); + if (performance.now() - started > timeout) throw new Error("CDP did not answer during the start."); + if (await cdpResponds(port)) app.browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`, { timeout: 10000 }); + else await sleep(50); + } + app.cdpMs = performance.now() - started; + while (!app.page) { + if (performance.now() - started > timeout) throw new Error("The main window page did not open."); + app.page = app.browser.contexts().flatMap(context => context.pages()).find(isMainPage) ?? null; + if (!app.page) await sleep(50); + } + app.page.setDefaultTimeout(30000); + return app; + } catch (error) { + await stop(app); + throw error; + } +} + +/** Wait for the known tree row. Return the start time in milliseconds from the spawn, and page timing values. */ +export async function waitForWorkbench(app, timeout = 60000) { + await app.page.locator(TABLE.knownRow).waitFor({ state: "visible", timeout }); + const startMs = performance.now() - app.started; + const timing = await app.page.evaluate(() => ({ timeOrigin: performance.timeOrigin, domContentLoaded: performance.getEntriesByType("navigation")[0]?.domContentLoadedEventEnd ?? null, tabs: document.querySelectorAll('[role="tab"]').length })); + return { startMs, navigationMs: timing.timeOrigin - app.startedAt, domContentLoadedMs: timing.domContentLoaded === null ? null : timing.timeOrigin + timing.domContentLoaded - app.startedAt, tabsAtStart: timing.tabs }; +} + +/** Start a long task observer in the page. */ +export function observeLongTasks(page) { + return page.evaluate(() => { + const state = { count: 0, max: 0 }; + const record = entries => { for (const entry of entries) { state.count++; state.max = Math.max(state.max, entry.duration); } }; + const observer = new PerformanceObserver(list => record(list.getEntries())); + observer.observe({ type: "longtask" }); + window.__rsLongTasks = { state, observer, record }; + }); +} + +/** Stop the long task observer. Return the count and the longest duration. */ +export function collectLongTasks(page) { + return page.evaluate(() => { + const tasks = window.__rsLongTasks; + if (!tasks) return null; + tasks.record(tasks.observer.takeRecords()); + tasks.observer.disconnect(); + return { count: tasks.state.count, maxMs: Math.round(tasks.state.max) }; + }); +} + +/** Collect garbage in the main page, wait, and read the heap and the process tree. */ +export async function readMemory(app, { settleMs = 5000 } = {}) { + const cdp = await app.page.context().newCDPSession(app.page); + try { + await cdp.send("HeapProfiler.collectGarbage"); + await sleep(settleMs); + const heap = await cdp.send("Runtime.getHeapUsage"); + const tree = processTree(await listProcesses(), app.pid); + return { + heapMB: heap.usedSize / 1048576, + heapTotalMB: heap.totalSize / 1048576, + privateMB: tree.privateBytes / 1048576, + workingSetMB: tree.workingSet / 1048576, + processCount: tree.count, + processNames: tree.names, + processes: tree.processes.map(item => ({ pid: item.ProcessId, parent: item.ParentProcessId, name: item.Name, privateMB: +(item.PrivatePageCount / 1048576).toFixed(1), workingSetMB: +(item.WorkingSetSize / 1048576).toFixed(1), created: item.Created })), + }; + } finally { await cdp.detach().catch(() => {}); } +} + +/** + * Clear the open tabs and the layout in the page storage, so the next start restores no tab and shows the file tree. + * Chromium writes local storage to disk after a delay, so the function waits before it returns. + */ +export async function clearViewState(page, flushMs = 6000) { + await page.evaluate(layout => { + for (const key of Object.keys(localStorage)) if (key.startsWith("runestone.document-session.")) localStorage.removeItem(key); + localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout)); + }, TABLE.layout); + await sleep(flushMs); +} + +/** Stop the started process tree and make sure that none of its processes remain. */ +export async function stop(app) { + if (!app?.pid) return { stopped: false }; + const before = processTree(await listProcesses().catch(() => []), app.pid).processes; + const result = await stopTree(app.pid); + await app.browser?.close().catch(() => {}); + for (let attempt = 0; attempt < 50; attempt++) { + const now = await listProcesses().catch(() => []); + const left = before.filter(item => now.some(other => other.ProcessId === item.ProcessId && other.Created === item.Created)); + if (!left.length) return { ...result, remaining: [] }; + if (attempt === 10) for (const item of left) await stopTree(item.ProcessId); + await sleep(200); + } + throw new Error(`Processes of the stopped app remain: ${before.map(item => item.ProcessId).join(", ")}.`); +} + +/** The WebView2 folder of the test identity. It exists after the first start of a build with that identifier. */ +export function webviewFolder(localData) { + return path.join(localData, "EBWebView"); +} +export const hasWebviewFolder = localData => existsSync(webviewFolder(localData)); diff --git a/scripts/measure/core.mjs b/scripts/measure/core.mjs new file mode 100644 index 0000000..df119cc --- /dev/null +++ b/scripts/measure/core.mjs @@ -0,0 +1,157 @@ +// Pure parts of the feature measurement tool: arguments, safety refusals, statistics, the process tree, and the report table. +import path from "node:path"; + +export const FEATURES = ["git", "background", "terminal", "pdf", "pm"]; +export const MODES = ["plugin", "native"]; +export const SCENARIOS = ["on-idle", "in-use", "after-off"]; +/** The app that the owner installed. The tool never starts it, stops it, or touches its data. */ +export const INSTALLED_EXE = "D:\\Users\\KnottyWyvern\\AppData\\Local\\RuneStone\\runestone.exe"; +export const INSTALLED_IDENTIFIER = "com.runestone.app"; + +export const USAGE = "Usage: node scripts/measureFeatures.mjs --exe --identifier com.runestone. --stage --mode plugin|native --features git,background,terminal,pdf,pm [--runs 3] [--port 9241] [--fresh-fixture] [--only base,:,...] [--skip-base]"; + +/** Read the command line. Throw an error with the usage text for a missing or unknown argument. */ +export function parseArguments(args) { + const options = { exe: undefined, identifier: undefined, stage: undefined, mode: undefined, features: undefined, runs: 3, port: 9241, freshFixture: false, only: undefined, skipBase: false }; + const values = { "--exe": "exe", "--identifier": "identifier", "--stage": "stage", "--mode": "mode", "--features": "features", "--runs": "runs", "--port": "port", "--only": "only" }; + const seen = new Set(); + for (let index = 0; index < args.length; index++) { + const arg = args[index]; + if (arg === "--fresh-fixture") { options.freshFixture = true; continue; } + if (arg === "--skip-base") { options.skipBase = true; continue; } + const key = values[arg]; + if (!key) throw new Error(`Unknown argument ${arg}. ${USAGE}`); + if (seen.has(arg)) throw new Error(`Give ${arg} one time only. ${USAGE}`); + seen.add(arg); + const value = args[++index]; + if (value === undefined || value.startsWith("--")) throw new Error(`${arg} needs a value. ${USAGE}`); + options[key] = value; + } + for (const key of ["exe", "identifier", "stage", "mode", "features"]) if (options[key] === undefined) throw new Error(`--${key} is required. ${USAGE}`); + if (!MODES.includes(options.mode)) throw new Error(`--mode must be plugin or native. ${USAGE}`); + if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(options.stage)) throw new Error("--stage must be a simple folder name."); + const features = options.features.split(",").map(feature => feature.trim()).filter(Boolean); + const unknown = features.filter(feature => !FEATURES.includes(feature)); + if (!features.length || unknown.length) throw new Error(`Unknown feature ${unknown.join(", ") || "(none)"}. Use ${FEATURES.join(", ")}.`); + options.features = [...new Set(features)]; + for (const key of ["runs", "port"]) { + const number = Number(options[key]); + if (typeof options[key] === "string" && !/^\d+$/.test(options[key])) throw new Error(`--${key} must be a whole number.`); + options[key] = number; + } + if (options.runs < 1 || options.runs > 20) throw new Error("--runs must be from 1 to 20."); + if (options.port < 1024 || options.port > 65535) throw new Error("--port must be from 1024 to 65535."); + if (options.only !== undefined) { + options.only = options.only.split(",").map(item => item.trim()).filter(Boolean); + for (const item of options.only) { + const [feature, scenario] = item.split(":"); + if (!(item === "base" || (options.features.includes(feature) && SCENARIOS.includes(scenario)))) throw new Error(`--only takes base or :, not ${item}.`); + } + } + return options; +} + +function samePath(a, b) { + return path.win32.resolve(a).toLowerCase() === path.win32.resolve(b).toLowerCase(); +} + +/** + * Refuse an unsafe target. The executable must not be the installed app or be in its folder. + * The identifier must start with `com.runestone.` and must not be the identifier of the installed app. + * `env` supplies LOCALAPPDATA and APPDATA. Return the two data folders that the tool may reset. + */ +export function checkTarget({ exe, identifier }, env = process.env) { + const installed = [INSTALLED_EXE]; + if (env.LOCALAPPDATA) installed.push(path.win32.join(env.LOCALAPPDATA, "RuneStone", "runestone.exe")); + const resolved = path.win32.resolve(exe); + for (const target of installed) { + if (samePath(resolved, target) || samePath(path.win32.dirname(resolved), path.win32.dirname(target))) + throw new Error(`Refusing to run the installed RuneStone (${target}). Give a copy of a test build.`); + } + if (typeof identifier !== "string" || identifier.toLowerCase() === INSTALLED_IDENTIFIER) + throw new Error(`Refusing the identifier ${identifier}. It belongs to the installed RuneStone.`); + if (!/^com\.runestone\.[a-z0-9][a-z0-9-]*$/.test(identifier)) + throw new Error(`Refusing the identifier ${identifier}. A test identifier starts with com.runestone. and has lowercase letters, digits, and hyphens.`); + if (!env.APPDATA || !env.LOCALAPPDATA) throw new Error("APPDATA and LOCALAPPDATA must be set."); + return { roaming: path.win32.join(env.APPDATA, identifier), local: path.win32.join(env.LOCALAPPDATA, identifier) }; +} + +/** The median of the finite numbers in `values`, or null when there is none. */ +export function median(values) { + const numbers = values.filter(value => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b); + if (!numbers.length) return null; + const middle = Math.floor(numbers.length / 2); + return numbers.length % 2 ? numbers[middle] : (numbers[middle - 1] + numbers[middle]) / 2; +} + +/** + * Walk the descendants of `rootPid` in a process list from Win32_Process. + * A child counts only when it started after its parent, so a reused parent process ID does not add a stranger. + * Return the processes of the tree, with the root first, and the sums of the private bytes and the working sets. + */ +export function processTree(list, rootPid) { + const byParent = new Map(); + for (const item of list) { + if (!byParent.has(item.ParentProcessId)) byParent.set(item.ParentProcessId, []); + byParent.get(item.ParentProcessId).push(item); + } + const root = list.find(item => item.ProcessId === rootPid); + if (!root) return { processes: [], privateBytes: 0, workingSet: 0, count: 0, names: {} }; + const processes = [root]; + const seen = new Set([rootPid]); + for (let index = 0; index < processes.length; index++) { + const parent = processes[index]; + for (const child of byParent.get(parent.ProcessId) ?? []) { + if (seen.has(child.ProcessId)) continue; + if (typeof child.Created === "number" && typeof parent.Created === "number" && child.Created < parent.Created) continue; + seen.add(child.ProcessId); + processes.push(child); + } + } + const names = {}; + for (const item of processes) names[item.Name] = (names[item.Name] ?? 0) + 1; + return { + processes, + privateBytes: processes.reduce((sum, item) => sum + Number(item.PrivatePageCount ?? 0), 0), + workingSet: processes.reduce((sum, item) => sum + Number(item.WorkingSetSize ?? 0), 0), + count: processes.length, + names, + }; +} + +export const METRICS = ["privateMB", "workingSetMB", "heapMB", "startMs", "firstNeedMs", "longTaskCount", "longTaskMaxMs", "processCount"]; + +/** The median of each metric over the samples that did not fail. */ +export function summarize(samples) { + const good = samples.filter(sample => !sample.error); + const result = { runs: samples.length, failed: samples.length - good.length }; + for (const metric of METRICS) result[metric] = median(good.map(sample => sample[metric])); + return result; +} + +const fixed = (value, digits = 1) => value === null || value === undefined ? "–" : Number(value).toFixed(digits); + +/** The Markdown report: one table row for each feature and scenario. */ +export function markdownTable(report) { + const lines = [ + `# Feature memory: ${report.stage}`, + "", + `Build: \`${report.build}\` (${report.identifier}), mode ${report.mode}, ${report.runs} runs for each scenario, ${report.date}.`, + `Machine: ${report.machine.cpu}, ${fixed(report.machine.ramGB)} GB RAM, ${report.machine.windows}.`, + "Each value is the median of the runs. Private and working set are sums over the process tree of the app.", + "", + "| Feature | Scenario | Private MB | Working set MB | JS heap MB | Start ms | First need ms | Long tasks (count / longest ms) |", + "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |", + ]; + for (const row of report.rows) { + const m = row.median; + if (!m || m.runs === m.failed) { + lines.push(`| ${row.feature} | ${row.scenario} | failed | | | | | ${row.reason ? row.reason.replace(/\|/g, "/").slice(0, 160) : ""} |`); + continue; + } + const failed = m.failed ? ` (${m.failed} of ${m.runs} runs failed)` : ""; + lines.push(`| ${row.feature} | ${row.scenario}${failed} | ${fixed(m.privateMB)} | ${fixed(m.workingSetMB)} | ${fixed(m.heapMB)} | ${fixed(m.startMs, 0)} | ${fixed(m.firstNeedMs, 0)} | ${fixed(m.longTaskCount, 0)} / ${fixed(m.longTaskMaxMs, 0)} |`); + } + if (report.notes?.length) lines.push("", "Notes:", "", ...report.notes.map(note => `- ${note}`)); + return lines.join("\n") + "\n"; +} diff --git a/scripts/measure/fixture.mjs b/scripts/measure/fixture.mjs new file mode 100644 index 0000000..bfd2ebd --- /dev/null +++ b/scripts/measure/fixture.mjs @@ -0,0 +1,201 @@ +// The fixture workspace: a Git repository with history and changes, a 50-page PDF, background images, and a Project Management store. +// It lives in the system temporary folder, outside the repository, so the file watcher of the app does not see the worktree. +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { existsSync, realpathSync } from "node:fs"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { encodePng, gradientPixel } from "./png.mjs"; +import { writePdf } from "./pdf.mjs"; + +const run = promisify(execFile); +export const FIXTURE_VERSION = 1; +export const COMMITS = 30; +export const TEXT_FILES = 50; +export const PDF_PAGES = 50; +export const BOARDS = 8; +export const CARDS_PER_BOARD = 50; +export const IMAGES = 5; +export const IMAGE_SIZE = { width: 1920, height: 1080 }; +/** A file at the workspace root that the tree shows at once. The start time waits for its row. */ +export const KNOWN_ROW = "sample.pdf"; + +export const fixtureRoot = () => path.join(tmpdir(), "runestone-phase7-fixture"); + +/** A UUID with the version 4 layout, made from `seed`, so each fixture build has the same IDs. */ +export function seededUuid(seed) { + const hex = createHash("sha256").update(seed).digest("hex"); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-${"89ab"[parseInt(hex[16], 16) % 4]}${hex.slice(17, 20)}-${hex.slice(20, 32)}`; +} + +/** The card file name: the hex of the UTF-8 card ID, then `.md`. */ +export const cardFileName = id => `${Buffer.from(id, "utf8").toString("hex")}.md`; + +/** An order key that sorts in the same order as `index`. */ +const orderKey = index => `a${String.fromCharCode(97 + Math.floor(index / 26))}${String.fromCharCode(97 + (index % 26))}`; + +const textName = index => `note-${String(index + 1).padStart(2, "0")}.txt`; + +function git(cwd, args, env = {}) { + const config = ["-c", "user.name=RuneStone Fixture", "-c", "user.email=fixture@runestone.invalid", "-c", "commit.gpgsign=false", "-c", "core.autocrlf=false", "-c", "init.defaultBranch=main"]; + return run("git", ["-C", cwd, ...config, ...args], { env: { ...process.env, GIT_TERMINAL_PROMPT: "0", ...env }, windowsHide: true, maxBuffer: 16 * 1024 * 1024 }); +} + +const LISTS = [ + { id: "backlog", name: "Backlog", status: null }, + { id: "todo", name: "To do", status: "todo" }, + { id: "doing", name: "In progress", status: "doing" }, + { id: "done", name: "Done", status: "done" }, +]; + +/** The Project Management store: `workspace.json`, the card files, and the two `.gitignore` files. */ +export function pmFiles() { + const files = new Map(); + files.set(".runestone/pm/.gitignore", "# RuneStone PM local data\n*\n"); + files.set(".runestone/pm/cards/.gitignore", "*\n"); + const boards = []; + for (let b = 0; b < BOARDS; b++) { + const id = seededUuid(`board-${b}`); + boards.push({ + name: `Fixture board ${b + 1}`, + value: { + schema: 1, kind: "board", id, + lists: LISTS.map(list => ({ id: list.id, name: list.name, status: list.status, collapsed: false })), + defaults: { todo: "todo", doing: "doing", done: "done" }, + }, + }); + for (let c = 0; c < CARDS_PER_BOARD; c++) { + const cardId = seededUuid(`card-${b}-${c}`); + const list = LISTS[c % LISTS.length]; + const status = list.status ?? "todo"; + const source = [ + "---", + "runestone_pm:", + " schema: 1", + ` id: ${cardId}`, + " kind: task", + ` status: ${status}`, + " tags: []", + " sessions: []", + " archived: false", + ` order: ${orderKey(b * CARDS_PER_BOARD + c)}`, + " placements:", + ` ${id}:`, + ` listId: ${list.id}`, + ` order: ${orderKey(c)}`, + ` title: Fixture card ${c + 1} on board ${b + 1}`, + ` priority: ${["low", "medium", "high"][c % 3]}`, + "---", + "", + `This card is fixture data for the memory measurement. Board ${b + 1}, card ${c + 1}.`, + "", + ].join("\n"); + files.set(`.runestone/pm/cards/${cardFileName(cardId)}`, source); + } + } + files.set(".runestone/pm/workspace.json", JSON.stringify({ schema: 1, boards, deletedBoardIds: [] }, null, 2) + "\n"); + return files; +} + +const COLORS = [ + [[16, 42, 120], [220, 90, 40], 0.3], + [[10, 110, 80], [240, 220, 60], 1.2], + [[120, 20, 90], [40, 200, 230], 2.1], + [[30, 30, 30], [200, 200, 210], 0], + [[200, 40, 40], [20, 60, 160], Math.PI / 2], +]; + +async function writeFiles(root, files) { + for (const [rel, contents] of files) { + const target = path.join(root, ...rel.split("/")); + await mkdir(path.dirname(target), { recursive: true }); + await writeFile(target, contents); + } +} + +/** Build the fixture in `root`. The caller removes an old fixture first. */ +export async function buildFixture(root) { + const workspace = path.join(root, "workspace"); + const backgrounds = path.join(root, "backgrounds"); + await mkdir(workspace, { recursive: true }); + await mkdir(backgrounds, { recursive: true }); + for (const [index, [from, to, angle]] of COLORS.entries()) { + const { width, height } = IMAGE_SIZE; + await writeFile(path.join(backgrounds, `background-${index + 1}.png`), encodePng(width, height, gradientPixel(width, height, from, to, angle))); + } + await git(workspace, ["init", "-q"]); + await writeFile(path.join(workspace, ".gitignore"), ".runestone/\n"); + await writeFile(path.join(workspace, "sample.pdf"), writePdf(Array.from({ length: PDF_PAGES }, (_, index) => `Page ${index + 1}`))); + const line = (file, version) => `Fixture file ${file + 1}, version ${version}.\n`; + const versions = Array(TEXT_FILES).fill(0); + for (let file = 0; file < TEXT_FILES; file++) await writeFile(path.join(workspace, textName(file)), line(file, 0)); + for (let commit = 0; commit < COMMITS; commit++) { + if (commit > 0) { + // Each later commit changes five files, so the graph and the diffs have content. + for (let k = 0; k < 5; k++) { + const file = (commit * 7 + k * 11) % TEXT_FILES; + versions[file]++; + await writeFile(path.join(workspace, textName(file)), Array.from({ length: versions[file] + 1 }, (_, v) => line(file, v)).join("")); + } + } + await git(workspace, ["add", "-A"]); + const date = new Date(Date.UTC(2026, 0, 1 + commit, 12)).toISOString(); + await git(workspace, ["commit", "-q", "--no-verify", "-m", commit === 0 ? "Add the fixture files" : `Change fixture files, step ${commit}`], { GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date }); + } + for (let file = 0; file < TEXT_FILES; file++) { + const target = path.join(workspace, textName(file)); + await writeFile(target, (await readFile(target, "utf8")) + `Changed after the last commit (file ${file + 1}).\n`); + } + await writeFiles(workspace, pmFiles()); + await writeFile(path.join(root, "fixture.json"), JSON.stringify({ version: FIXTURE_VERSION, commits: COMMITS, changes: TEXT_FILES, pages: PDF_PAGES, boards: BOARDS, cards: BOARDS * CARDS_PER_BOARD, images: IMAGES }, null, 2) + "\n"); +} + +/** Check that the fixture in `root` is complete and unchanged. Return a list of problems, empty when it matches. */ +export async function checkFixture(root) { + const problems = []; + const workspace = path.join(root, "workspace"); + try { + const record = JSON.parse(await readFile(path.join(root, "fixture.json"), "utf8")); + if (record.version !== FIXTURE_VERSION) problems.push(`fixture version ${record.version}`); + } catch { problems.push("no fixture.json"); return problems; } + for (let index = 0; index < IMAGES; index++) if (!existsSync(path.join(root, "backgrounds", `background-${index + 1}.png`))) problems.push(`no background ${index + 1}`); + if (!existsSync(path.join(workspace, "sample.pdf"))) problems.push("no sample.pdf"); + try { + const status = (await git(workspace, ["status", "--porcelain"])).stdout.split("\n").filter(Boolean); + if (status.length !== TEXT_FILES || status.some(entry => !entry.startsWith(" M "))) problems.push(`git status shows ${status.length} entries, not ${TEXT_FILES} changed files`); + const count = Number((await git(workspace, ["rev-list", "--count", "HEAD"])).stdout.trim()); + if (count !== COMMITS) problems.push(`${count} commits, not ${COMMITS}`); + } catch (error) { problems.push(`git: ${error.message}`); } + for (const [rel, contents] of pmFiles()) { + const target = path.join(workspace, ...rel.split("/")); + if (!existsSync(target)) { problems.push(`no ${rel}`); break; } + if (rel.endsWith("workspace.json") && (await readFile(target, "utf8")) !== contents) problems.push("workspace.json changed"); + } + return problems; +} + +/** Reuse the fixture when it matches, or build it again. Return the canonical paths. */ +export async function prepareFixture({ fresh = false, root = fixtureRoot(), log = () => {} } = {}) { + let problems = fresh ? ["--fresh-fixture"] : await checkFixture(root); + if (problems.length) { + log(`Building the fixture in ${root} (${problems.join(", ")}).`); + // The fixture folder belongs to this tool. It is in the system temporary folder. + if (path.basename(root) !== "runestone-phase7-fixture") throw new Error(`Refusing to remove ${root}.`); + await rm(root, { recursive: true, force: true }); + await buildFixture(root); + problems = await checkFixture(root); + if (problems.length) throw new Error(`The new fixture does not match: ${problems.join(", ")}.`); + } else log(`Reusing the fixture in ${root}.`); + // The canonical path expands short 8.3 names, so the app and the grants see the same path. + const real = realpathSync.native(root); + return { root: real, workspace: path.join(real, "workspace"), backgrounds: path.join(real, "backgrounds") }; +} + +/** Run the read-only Project Management helper of the skill. Return the number of boards that it lists. */ +export async function inspectPmBoards(workspace, helper = path.join(process.env.USERPROFILE ?? "", ".claude", "skills", "runestone-project-management", "scripts", "inspect.mjs")) { + if (!existsSync(helper)) return { checked: false, reason: `no helper at ${helper}` }; + const { stdout } = await run(process.execPath, [helper, "boards", "--workspace", workspace], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 }); + return { checked: true, output: stdout }; +} diff --git a/scripts/measure/giteaServer.mjs b/scripts/measure/giteaServer.mjs new file mode 100644 index 0000000..1c52e9e --- /dev/null +++ b/scripts/measure/giteaServer.mjs @@ -0,0 +1,47 @@ +// A local fake Gitea release server. The host installs plugin ZIPs through its Gitea path from this server. +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; + +/** + * Serve the releases in `packages`: a list of `{ repo, tag, file }`, with `file` the path of a plugin ZIP. + * The server answers `GET /api/v1/repos/test//releases/tags/` and serves the ZIP at its download link. + * Return the base URL, the repository link of each package, the request log, and `close`. + */ +export async function startGiteaServer(packages, owner = "test") { + const bodies = new Map(); + for (const item of packages) bodies.set(item.repo, { ...item, name: path.basename(item.file), bytes: await readFile(item.file) }); + const requests = []; + const server = createServer((request, response) => { + const url = new URL(request.url, "http://127.0.0.1"); + requests.push(`${request.method} ${url.pathname}`); + const release = /^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/releases\/tags\/([^/]+)$/.exec(url.pathname); + const download = /^\/download\/([^/]+)\/([^/]+)$/.exec(url.pathname); + if (request.method === "GET" && release && release[1] === owner && bodies.get(release[2])?.tag === decodeURIComponent(release[3])) { + const item = bodies.get(release[2]); + const body = JSON.stringify({ + tag_name: item.tag, draft: false, + assets: [{ name: item.name, size: item.bytes.length, browser_download_url: `${base}/download/${item.repo}/${encodeURIComponent(item.name)}` }], + }); + response.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body) }); + response.end(body); + return; + } + if (request.method === "GET" && download && bodies.get(download[1])?.name === decodeURIComponent(download[2])) { + const item = bodies.get(download[1]); + response.writeHead(200, { "content-type": "application/zip", "content-length": item.bytes.length }); + response.end(item.bytes); + return; + } + response.writeHead(404, { "content-type": "text/plain" }); + response.end("not found"); + }); + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + const base = `http://127.0.0.1:${server.address().port}`; + return { + base, + requests, + repository: repo => `${base}/${owner}/${repo}`, + close: () => new Promise(resolve => server.close(() => resolve())), + }; +} diff --git a/scripts/measure/pdf.mjs b/scripts/measure/pdf.mjs new file mode 100644 index 0000000..ba5c93a --- /dev/null +++ b/scripts/measure/pdf.mjs @@ -0,0 +1,45 @@ +// A small PDF writer for the fixture document: one page for each text, in Helvetica, with a correct cross-reference table. + +function escapeText(text) { + return text.replace(/[\\()]/g, match => `\\${match}`); +} + +/** Write a PDF with one US Letter page for each entry of `texts`. Return the bytes. */ +export function writePdf(texts) { + if (!texts.length) throw new Error("A PDF needs at least one page."); + // Object numbers: 1 catalog, 2 page tree, 3 font, then a page and its content stream for each text. + const pageIds = texts.map((_, index) => 4 + index * 2); + const objects = [ + "<< /Type /Catalog /Pages 2 0 R >>", + `<< /Type /Pages /Kids [${pageIds.map(id => `${id} 0 R`).join(" ")}] /Count ${texts.length} >>`, + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>", + ]; + for (const [index, text] of texts.entries()) { + const stream = `BT /F1 48 Tf 72 680 Td (${escapeText(text)}) Tj ET\nBT /F1 14 Tf 72 640 Td (RuneStone measurement fixture, page ${index + 1} of ${texts.length}) Tj ET\n`; + objects.push(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${pageIds[index] + 1} 0 R >>`); + objects.push(`<< /Length ${Buffer.byteLength(stream, "latin1")} >>\nstream\n${stream}endstream`); + } + let body = "%PDF-1.4\n%\xe2\xe3\xcf\xd3\n"; + const offsets = []; + for (const [index, object] of objects.entries()) { + offsets.push(Buffer.byteLength(body, "latin1")); + body += `${index + 1} 0 obj\n${object}\nendobj\n`; + } + const xref = Buffer.byteLength(body, "latin1"); + // Each entry is exactly 20 bytes, with a space and a line feed at the end. + body += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`; + for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n \n`; + body += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; + return Buffer.from(body, "latin1"); +} + +/** Read the cross-reference table of a PDF from `writePdf`. Return `startxref` and the offsets of the objects in use. */ +export function readPdfXref(bytes) { + const text = bytes.toString("latin1"); + const start = Number(/startxref\n(\d+)\n%%EOF\n?$/.exec(text)?.[1]); + if (!Number.isInteger(start) || !text.startsWith("xref\n", start)) throw new Error("The startxref offset does not point to the xref table."); + const lines = text.slice(start).split("\n"); + const [, count] = lines[1].split(" ").map(Number); + const entries = lines.slice(2, 2 + count).map(line => ({ line, offset: Number(line.slice(0, 10)), used: line.slice(17, 18) === "n" })); + return { start, count, entries }; +} diff --git a/scripts/measure/png.mjs b/scripts/measure/png.mjs new file mode 100644 index 0000000..0401d47 --- /dev/null +++ b/scripts/measure/png.mjs @@ -0,0 +1,80 @@ +// A small PNG encoder for the fixture images. It writes 8-bit RGB images without a dependency. +import { deflateSync } from "node:zlib"; + +const CRC_TABLE = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c >>> 0; + } + return table; +})(); + +/** The CRC-32 of `bytes`, as PNG and ZIP use it. */ +export function crc32(bytes) { + let crc = 0xffffffff; + for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8); + return (crc ^ 0xffffffff) >>> 0; +} + +export const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + +function chunk(type, data) { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(type, "ascii"), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(body)); + return Buffer.concat([length, body, crc]); +} + +/** Encode an RGB image. `pixel(x, y)` returns `[r, g, b]` with values from 0 to 255. */ +export function encodePng(width, height, pixel) { + if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new Error("The image size must be positive whole numbers."); + const stride = width * 3 + 1; + const raw = Buffer.alloc(stride * height); + for (let y = 0; y < height; y++) { + const row = y * stride; + raw[row] = 0; // Filter type None. + for (let x = 0; x < width; x++) { + const [r, g, b] = pixel(x, y); + const at = row + 1 + x * 3; + raw[at] = r; raw[at + 1] = g; raw[at + 2] = b; + } + } + const header = Buffer.alloc(13); + header.writeUInt32BE(width, 0); + header.writeUInt32BE(height, 4); + header[8] = 8; // Bit depth. + header[9] = 2; // Color type RGB. + header[10] = 0; header[11] = 0; header[12] = 0; + return Buffer.concat([PNG_SIGNATURE, chunk("IHDR", header), chunk("IDAT", deflateSync(raw, { level: 6 })), chunk("IEND", Buffer.alloc(0))]); +} + +/** Read the chunks of a PNG file. Each chunk has its type, data, stored CRC, and computed CRC. */ +export function readPngChunks(bytes) { + if (!bytes.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("The file has no PNG signature."); + const chunks = []; + let at = 8; + while (at < bytes.length) { + const length = bytes.readUInt32BE(at); + const type = bytes.toString("ascii", at + 4, at + 8); + const data = bytes.subarray(at + 8, at + 8 + length); + const stored = bytes.readUInt32BE(at + 8 + length); + chunks.push({ type, data, stored, computed: crc32(bytes.subarray(at + 4, at + 8 + length)) }); + at += 12 + length; + } + return chunks; +} + +/** A diagonal gradient between two colors. Each fixture image uses a different pair and angle. */ +export function gradientPixel(width, height, from, to, angle) { + const dx = Math.cos(angle), dy = Math.sin(angle); + const span = Math.abs(dx) * width + Math.abs(dy) * height; + const origin = Math.min(0, dx * width) + Math.min(0, dy * height); + return (x, y) => { + const t = (x * dx + y * dy - origin) / span; + return [0, 1, 2].map(i => Math.round(from[i] + (to[i] - from[i]) * t)); + }; +} diff --git a/scripts/measure/processes.mjs b/scripts/measure/processes.mjs new file mode 100644 index 0000000..a00dbc5 --- /dev/null +++ b/scripts/measure/processes.mjs @@ -0,0 +1,25 @@ +// Process sampling and the stop of one process tree. The tool never stops a process by its image name. +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; + +const run = promisify(execFile); + +const LIST = "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,PrivatePageCount,WorkingSetSize,@{n='Created';e={if ($_.CreationDate) { $_.CreationDate.ToFileTimeUtc() } else { $null }}} | ConvertTo-Json -Compress"; + +/** List all processes one time, with the private bytes and the working set of each. */ +export async function listProcesses() { + const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST], { maxBuffer: 64 * 1024 * 1024, windowsHide: true }); + const value = JSON.parse(stdout); + return (Array.isArray(value) ? value : [value]).map(item => ({ ...item, PrivatePageCount: Number(item.PrivatePageCount ?? 0), WorkingSetSize: Number(item.WorkingSetSize ?? 0) })); +} + +/** Stop the process tree of `pid` with taskkill. Errors are returned, not thrown, because the tree can be gone already. */ +export async function stopTree(pid) { + if (!Number.isInteger(pid) || pid <= 4) throw new Error(`Refusing to stop process ID ${pid}.`); + try { + const { stdout } = await run("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }); + return { stopped: true, output: stdout.trim() }; + } catch (error) { + return { stopped: false, output: String(error.stderr || error.message).trim() }; + } +} diff --git a/scripts/measure/scenarios.mjs b/scripts/measure/scenarios.mjs new file mode 100644 index 0000000..e0b2c0a --- /dev/null +++ b/scripts/measure/scenarios.mjs @@ -0,0 +1,167 @@ +// The scenario table: the selectors, names, and feature switches of both modes, and the in-use action of each feature. +// A value with `plugin` and `native` keys differs between the modes. Change the table when a stage changes a name. + +const PLUGIN_RELEASES = "D:/Users/KnottyWyvern/Documents"; + +export const TABLE = { + /** The start time ends when this tree row is visible. */ + knownRow: '[data-tree-rel="sample.pdf"]', + /** The command palette. */ + palette: { shortcut: "Control+Shift+P", input: "Find a command" }, + /** The layout that the cleanup writes, so each start shows the file tree. */ + layout: { leftOpen: true, rightOpen: true, leftWidth: 260, rightWidth: 240, leftView: "files" }, + /** The settings section of the native feature switches. */ + featuresSection: "features", + features: { + git: { + plugin: { id: "runestone.git", repo: "runestone-git", tag: "v0.1.10", zip: `${PLUGIN_RELEASES}/RuneStone_Git/releases/runestone.git-0.1.10.zip` }, + nativeKey: "git", + navigation: "Source control", + changeRow: { plugin: ".rs-git-row", native: ".source-control .row" }, + changeCount: 50, + changeFile: { plugin: ".rs-git-file", native: ".source-control .file" }, + diffTab: "Git diff", + diffText: "Changed after the last commit", + graphCommand: "Show Git graph", + /** Where the command is: `palette`, or `menu:`. Master lists plugin view commands only in the Plug-in views menu. */ + graphCommandIn: { plugin: "menu:Plug-in views", native: "palette" }, + graphTab: "Git graph", + graphText: "Change fixture files, step 29", + }, + background: { + plugin: { id: "runestone.bg-slideshow", repo: "runestone-bg-slideshow", tag: "v0.0.11", zip: `${PLUGIN_RELEASES}/RuneStone_Background_Slideshow/releases/runestone.bg-slideshow-0.0.11.zip` }, + nativeKey: "background", + /** The style property of the body that holds the current background image. The action counts its changes. */ + imageProperty: { plugin: "--rs-background-image", native: "--rs-background-image" }, + changes: 3, + seconds: 10, + }, + terminal: { + plugin: { id: "runestone.terminal", repo: "runestone-terminal", tag: "v0.1.11", zip: `${PLUGIN_RELEASES}/RuneStone_Terminal/releases/runestone.terminal-0.1.11.zip` }, + nativeKey: "terminal", + ribbon: ".plugin-ribbon", + button: "Terminal", + surface: ".xterm", + rows: ".xterm-rows", + prompt: "PS [A-Za-z]:\\\\", + command: '1..10000 | % { "line $_" }', + readyText: "line 10000", + }, + pdf: { + plugin: { id: "runestone.pdf-viewer", repo: "runestone-pdf-viewer", tag: "v0.0.5", zip: `${PLUGIN_RELEASES}/RuneStone_PDF_Viewer/releases/runestone.pdf-viewer-0.0.5.zip` }, + nativeKey: "pdf", + row: '[data-tree-rel="sample.pdf"]', + firstPage: "PDF page 1", + pageInput: "Page number", + target: 25, + targetPage: "PDF page 25", + }, + pm: { + plugin: { id: "runestone.pm", repo: "runestone-pm", tag: "v0.2.49", zip: `${PLUGIN_RELEASES}/RuneStone_Project_Management/releases/runestone.pm-0.2.49.zip` }, + nativeKey: "pm", + /** Where the view opens: `palette`, or `menu:`. */ + openIn: { plugin: "menu:Plug-in views", native: "menu:Plug-in views" }, + title: "Project Management", + card: { plugin: ".pm-card", native: ".pm-card" }, + minCards: 50, + }, + }, +}; + +/** The value of a table entry for `mode`. */ +export const pick = (value, mode) => value && typeof value === "object" && !Array.isArray(value) && ("plugin" in value || "native" in value) ? value[mode] : value; + +const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +const starts = text => new RegExp(`^${escape(text)}`); + +/** Wait until the page has at least `count` elements for `selector`. The predicate is synchronous on purpose. */ +export function waitForCount(page, selector, count, timeout = 60000) { + return page.waitForFunction(([selector, count]) => document.querySelectorAll(selector).length >= count, [selector, count], { timeout, polling: 100 }); +} + +/** Open a command from the command palette by its exact title. */ +export async function runPaletteCommand(page, title) { + await page.keyboard.press(TABLE.palette.shortcut); + const input = page.getByRole("textbox", { name: TABLE.palette.input, exact: true }); + await input.waitFor({ timeout: 10000 }); + await input.fill(title); + await page.getByRole("button", { name: starts(title) }).first().waitFor({ timeout: 10000 }); + await input.press("Enter"); +} + +/** Run a command from the palette or from a ribbon menu. `where` is `palette` or `menu:`. */ +export async function runCommand(page, where, title) { + if (where === "palette") return runPaletteCommand(page, title); + const menu = /^menu:(.+)$/.exec(where)?.[1]; + if (!menu) throw new Error(`Unknown command place ${where}.`); + await page.locator(".plugin-ribbon").getByRole("button", { name: menu, exact: true }).click(); + await page.getByRole("menuitem", { name: starts(title) }).first().click(); +} + +/** + * The in-use action of each feature. Each action returns when its ready condition is true. + * `ctx` has `mode` and `log`. Some actions return details for the sample. + */ +export const ACTIONS = { + async git(page, { mode }) { + const git = TABLE.features.git; + await page.getByRole("button", { name: git.navigation, exact: true }).first().click(); + await waitForCount(page, pick(git.changeRow, mode), git.changeCount); + await page.locator(pick(git.changeFile, mode)).first().click(); + await page.getByRole("tab", { name: starts(git.diffTab) }).first().waitFor({ timeout: 30000 }); + await page.getByText(git.diffText).first().waitFor({ timeout: 30000 }); + await runCommand(page, pick(git.graphCommandIn, mode), git.graphCommand); + await page.getByRole("tab", { name: starts(git.graphTab) }).first().waitFor({ timeout: 30000 }); + await page.getByText(git.graphText, { exact: true }).first().waitFor({ timeout: 30000 }); + return { changeRows: await page.locator(pick(git.changeRow, mode)).count() }; + }, + async background(page, { mode }) { + const background = TABLE.features.background; + const property = pick(background.imageProperty, mode); + const started = Date.now(); + // Count the changes in the page, so a short image does not slip between two Node polls. + await page.evaluate(property => { + const state = { values: [], times: [] }; + const sample = () => { + const value = document.body.style.getPropertyValue(property); + if (value && value !== state.values.at(-1)) { state.values.push(value); state.times.push(performance.now()); } + }; + sample(); + state.timer = setInterval(sample, 100); + window.__rsBackgroundProbe = state; + }, property); + const timeout = (background.changes + 2) * background.seconds * 1000 + 30000; + await page.waitForFunction(changes => (window.__rsBackgroundProbe?.values.length ?? 0) >= changes + 1, background.changes, { timeout, polling: 250 }); + const result = await page.evaluate(() => { + const state = window.__rsBackgroundProbe; + clearInterval(state.timer); + return { images: state.values.length, intervalsMs: state.times.slice(1).map((time, index) => Math.round(time - state.times[index])) }; + }); + return { ...result, waitedMs: Date.now() - started }; + }, + async terminal(page) { + const terminal = TABLE.features.terminal; + await page.locator(terminal.ribbon).getByRole("button", { name: terminal.button, exact: true }).click(); + await page.locator(terminal.surface).first().waitFor({ timeout: 30000 }); + await page.waitForFunction(([rows, prompt]) => new RegExp(prompt).test((document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ")), [terminal.rows, terminal.prompt], { timeout: 60000, polling: 100 }); + await page.locator(terminal.surface).first().click(); + await page.keyboard.type(terminal.command); + await page.keyboard.press("Enter"); + await page.waitForFunction(([rows, text]) => (document.querySelector(rows)?.textContent ?? "").replace(/\u00a0/g, " ").includes(text), [terminal.rows, terminal.readyText], { timeout: 120000, polling: 100 }); + }, + async pdf(page) { + const pdf = TABLE.features.pdf; + await page.locator(pdf.row).click(); + await page.getByRole("img", { name: pdf.firstPage, exact: true }).waitFor({ timeout: 60000 }); + const input = page.getByRole("textbox", { name: pdf.pageInput, exact: true }).or(page.getByRole("spinbutton", { name: pdf.pageInput, exact: true })).first(); + await input.fill(String(pdf.target)); + await input.press("Enter"); + await page.getByRole("img", { name: pdf.targetPage, exact: true }).waitFor({ timeout: 60000 }); + }, + async pm(page, { mode }) { + const pm = TABLE.features.pm; + await runCommand(page, pick(pm.openIn, mode), pm.title); + await waitForCount(page, pick(pm.card, mode), pm.minCards); + return { cards: await page.locator(pick(pm.card, mode)).count() }; + }, +}; diff --git a/scripts/measureFeatures.mjs b/scripts/measureFeatures.mjs new file mode 100644 index 0000000..2cbe706 --- /dev/null +++ b/scripts/measureFeatures.mjs @@ -0,0 +1,264 @@ +#!/usr/bin/env node +// Measure the RAM and the response times of the optional features, each feature off and on. +// The tool starts a test build with an isolated identifier, drives it through CDP, and stops only the process tree that it started. +// Run `node scripts/measureFeatures.mjs --help` for the arguments. The results go to output/phase-7//. +import { existsSync } from "node:fs"; +import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { checkTarget, FEATURES, markdownTable, parseArguments, SCENARIOS, summarize, USAGE } from "./measure/core.mjs"; +import { inspectPmBoards, prepareFixture } from "./measure/fixture.mjs"; +import { startGiteaServer } from "./measure/giteaServer.mjs"; +import { ACTIONS, TABLE } from "./measure/scenarios.mjs"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const IDLE_MS = 15000; +const GC_SETTLE_MS = 5000; +// Plugins load after the workbench shows. Each run waits this long after the start, so the action measures the feature and not the plugin load. +const START_SETTLE_MS = 5000; +const log = message => console.log(`[${new Date().toISOString().slice(11, 19)}] ${message}`); + +async function machine() { + return { cpu: os.cpus()[0]?.model?.trim() ?? "unknown", cores: os.cpus().length, ramGB: os.totalmem() / 1024 ** 3, windows: `${os.version()} ${os.release()}`, node: process.version }; +} + +/** Remove the data folders of the test identity. `checkTarget` made the paths from the test identifier. */ +async function resetData(folders, identifier) { + for (const folder of [folders.roaming, folders.local]) { + if (path.win32.basename(folder) !== identifier) throw new Error(`Refusing to remove ${folder}.`); + for (let attempt = 0; ; attempt++) { + try { await rm(folder, { recursive: true, force: true }); break; } catch (error) { + if (attempt >= 20) throw new Error(`Cannot reset ${folder}: ${error.message}`); + await sleep(500); + } + } + } +} + +/** Write the folder grant and the settings of Background Slideshow before the first start. */ +async function seedBackgroundPlugin(folders, backgrounds) { + const id = TABLE.features.background.plugin.id; + const folder = path.join(folders.roaming, "plugin-data", id); + await mkdir(folder, { recursive: true }); + const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"; + await writeFile(path.join(folder, "folder-grants.json"), JSON.stringify({ schema: 1, grants: [{ id: grant, path: backgrounds }] }, null, 2)); + await writeFile(path.join(folder, "settings.json"), JSON.stringify({ grant, folder: backgrounds, seconds: TABLE.features.background.seconds, order: "name", enabled: true, targets: ["app"], overlay: 0, position: "center", size: "cover" })); +} + +/** The features that are on in the running app. */ +async function readState(app, mode, invoke) { + if (mode === "plugin") { + const snapshot = await invoke(app.page, "plugins_snapshot"); + return new Set(FEATURES.filter(feature => snapshot.plugins.some(row => row.manifest.id === TABLE.features[feature].plugin.id && row.enabled))); + } + const file = await invoke(app.page, "settings_read"); + const section = file?.sections?.[TABLE.featuresSection] ?? {}; + return new Set(FEATURES.filter(feature => section[TABLE.features[feature].nativeKey] === true)); +} + +/** Turn on exactly the features in `enabled`, and turn off the others. */ +async function applyState(app, mode, enabled, invoke) { + if (mode === "plugin") { + const snapshot = await invoke(app.page, "plugins_snapshot"); + for (const row of snapshot.plugins) { + const feature = FEATURES.find(item => TABLE.features[item].plugin.id === row.manifest.id); + const want = feature ? enabled.has(feature) : false; + if (row.enabled !== want) await invoke(app.page, "plugins_set_enabled", { id: row.manifest.id, enabled: want, hash: want ? row.hash : null }); + } + return; + } + const file = await invoke(app.page, "settings_read"); + const value = { ...(file?.sections?.[TABLE.featuresSection] ?? {}) }; + for (const feature of FEATURES) value[TABLE.features[feature].nativeKey] = enabled.has(feature); + await invoke(app.page, "settings_write", { section: TABLE.featuresSection, value }); +} + +const sameSet = (a, b) => a.size === b.size && [...a].every(item => b.has(item)); + +/** Install the plugins of `features` from the fake Gitea server. */ +async function installPlugins(app, features, invoke) { + const packages = features.map(feature => TABLE.features[feature].plugin); + for (const item of packages) if (!existsSync(item.zip)) throw new Error(`No plugin ZIP at ${item.zip}.`); + const server = await startGiteaServer(packages.map(item => ({ repo: item.repo, tag: item.tag, file: item.zip }))); + try { + for (const item of packages) { + const rows = await invoke(app.page, "plugins_from_git", { url: server.repository(item.repo), tag: item.tag, token: null }); + if (rows.length !== 1 || rows[0].error || !rows[0].token) throw new Error(`plugins_from_git for ${item.repo}: ${JSON.stringify(rows)}`); + if (rows[0].manifest?.id !== item.id) throw new Error(`The ZIP of ${item.repo} has the ID ${rows[0].manifest?.id}, not ${item.id}.`); + const results = await invoke(app.page, "plugins_install", { tokens: [rows[0].token], enabled: true }); + if (results.some(result => result.error)) throw new Error(`plugins_install for ${item.id}: ${JSON.stringify(results)}`); + log(`Installed ${item.id} from ${server.repository(item.repo)}.`); + } + } finally { await server.close(); } + const snapshot = await invoke(app.page, "plugins_snapshot"); + const missing = packages.filter(item => !snapshot.plugins.some(row => row.manifest.id === item.id && !row.error)); + if (missing.length) throw new Error(`Plugins missing after the install: ${missing.map(item => item.id).join(", ")}.`); + return snapshot.plugins.map(row => ({ id: row.manifest.id, version: row.manifest.version, hash: row.hash })); +} + +export async function main(argv = process.argv.slice(2)) { + if (argv.includes("--help")) { console.log(USAGE); return; } + const options = parseArguments(argv); + const exe = path.resolve(options.exe); + const folders = checkTarget({ exe, identifier: options.identifier }); + if (!existsSync(exe)) throw new Error(`No executable at ${exe}.`); + // Load the app module after the refusals, so the refusals work without Playwright. + const app = await import("./measure/app.mjs"); + const output = path.join(repoRoot, "output", "phase-7", options.stage); + await mkdir(output, { recursive: true }); + const fixture = await prepareFixture({ fresh: options.freshFixture, log }); + const pm = await inspectPmBoards(fixture.workspace); + if (pm.checked && JSON.parse(pm.output).workspaces[0].boards.length !== 8) throw new Error("The Project Management fixture does not show 8 boards."); + + const reportPath = path.join(output, "memory.json"); + const previous = options.only && existsSync(reportPath) ? JSON.parse(await readFile(reportPath, "utf8")) : null; + const report = { + stage: options.stage, mode: options.mode, build: exe, identifier: options.identifier, date: new Date().toISOString(), runs: options.runs, + machine: await machine(), fixture, method: { + idleMs: IDLE_MS, gcSettleMs: GC_SETTLE_MS, startSettleMs: START_SETTLE_MS, + action: "Each run waits startSettleMs after the start, then starts the action. First need is the time from the start of the action to its ready condition.", + memory: "Win32_Process PrivatePageCount and WorkingSetSize, summed over the descendants of the started process.", + heap: "CDP Runtime.getHeapUsage usedSize of the main page after HeapProfiler.collectGarbage. Workers and other pages are not included.", + start: `From the spawn to the visible tree row ${TABLE.knownRow}.`, + longTasks: "PerformanceObserver longtask in the main page, from the start of the action to its end. For on-idle and base, over the idle wait.", + }, + plugins: previous?.plugins ?? null, setup: {}, rows: previous?.rows ?? [], notes: previous?.notes ?? [], + }; + const save = async () => { + report.date = new Date().toISOString(); + await writeFile(reportPath, JSON.stringify(report, null, 2) + "\n"); + await writeFile(path.join(output, "memory.md"), markdownTable(report)); + }; + const wanted = (feature, scenario) => !options.only || options.only.includes(feature === "base" ? "base" : `${feature}:${scenario}`); + + // The plan: base runs with every feature off, then each feature scenario with only that feature on. + const plan = []; + if (wanted("base") && !options.skipBase) for (let run = 1; run <= options.runs; run++) plan.push({ feature: "base", scenario: "base", run, enabled: new Set() }); + const featurePlan = []; + for (const feature of options.features) for (const scenario of SCENARIOS) if (wanted(feature, scenario)) for (let run = 1; run <= options.runs; run++) featurePlan.push({ feature, scenario, run, enabled: new Set([feature]) }); + + log(`Resetting ${folders.roaming} and ${folders.local}.`); + await resetData(folders, options.identifier); + if (options.mode === "plugin" && options.features.includes("background")) await seedBackgroundPlugin(folders, fixture.backgrounds); + + // The setup start opens the workspace. It also proves the test identity. + let session = await app.launch({ exe, port: options.port }); + try { + if (!app.hasWebviewFolder(folders.local)) throw new Error(`${app.webviewFolder(folders.local)} does not exist. The executable does not use the identifier ${options.identifier}.`); + const snapshot = await app.invoke(session.page, "plugins_snapshot"); + if (!path.resolve(snapshot.root).toLowerCase().startsWith(path.resolve(folders.roaming).toLowerCase())) throw new Error(`The app data folder ${snapshot.root} is not in ${folders.roaming}.`); + report.setup.identity = { webview: app.webviewFolder(folders.local), pluginRoot: snapshot.root }; + await app.invoke(session.page, "workspace_open", { path: fixture.workspace }); + await session.page.evaluate(layout => localStorage.setItem("runestone.workbenchLayout", JSON.stringify(layout)), TABLE.layout); + await session.page.reload(); + await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 }); + if (options.mode === "native") await applyState(session, "native", new Set(), app.invoke); + await app.clearViewState(session.page); + } finally { await app.stop(session); } + log("Setup done: workspace open, identity confirmed."); + + const rowFor = (feature, scenario) => { + let row = report.rows.find(item => item.feature === feature && item.scenario === scenario); + if (!row) { row = { feature, scenario, samples: [], median: null }; report.rows.push(row); } + return row; + }; + for (const item of [...plan, ...featurePlan]) { + const row = rowFor(item.feature, item.scenario); + if (item.run === 1) { row.samples = []; row.median = null; delete row.reason; } + } + // Keep the row order stable: base first, then each feature in the order of FEATURES and SCENARIOS. + const rank = row => row.feature === "base" ? -1 : FEATURES.indexOf(row.feature) * 10 + SCENARIOS.indexOf(row.scenario); + report.rows.sort((a, b) => rank(a) - rank(b)); + await save(); + + let installed = options.mode === "native"; + const runAll = async list => { + for (const [index, item] of list.entries()) { + const next = list[index + 1]; + const row = rowFor(item.feature, item.scenario); + log(`${item.feature} ${item.scenario}, run ${item.run} of ${options.runs}.`); + const sample = await measure(item, next, options.mode).catch(error => ({ run: item.run, error: String(error?.stack ?? error).split("\n").slice(0, 3).join(" | ") })); + if (sample.error) log(` failed: ${sample.error}`); + else log(` private ${sample.privateMB.toFixed(1)} MB, working set ${sample.workingSetMB.toFixed(1)} MB, heap ${sample.heapMB.toFixed(1)} MB, start ${Math.round(sample.startMs)} ms, first need ${sample.firstNeedMs === null ? "–" : Math.round(sample.firstNeedMs)} ms`); + row.samples.push(sample); + row.median = summarize(row.samples); + if (row.median.failed === row.median.runs) row.reason = row.samples.find(item => item.error)?.error; + else delete row.reason; + await save(); + } + }; + + /** One measured run in a new app process. Before the stop, it prepares the feature state of `next`. */ + async function measure(item, next, mode, retry = true) { + const session = await app.launch({ exe, port: options.port }); + const sample = { run: item.run, pid: session.pid, cdpMs: Math.round(session.cdpMs) }; + let prepared = false; + try { + Object.assign(sample, await app.waitForWorkbench(session)); + const state = await readState(session, mode, app.invoke); + if (!sameSet(state, item.enabled)) { + // A failed run can leave another state. Fix it and start again. + if (!retry) throw new Error(`The feature state is ${[...state].join(",") || "none"}, not ${[...item.enabled].join(",") || "none"}.`); + await applyState(session, mode, item.enabled, app.invoke); + await app.clearViewState(session.page); + prepared = true; + await app.stop(session); + return measure(item, next, mode, false); + } + await sleep(START_SETTLE_MS); + await app.observeLongTasks(session.page); + sample.firstNeedMs = null; + if (item.scenario === "in-use" || item.scenario === "after-off") { + const begin = performance.now(); + sample.details = await ACTIONS[item.feature](session.page, { mode, log }) ?? null; + sample.firstNeedMs = performance.now() - begin; + if (item.scenario === "after-off") await applyState(session, mode, new Set(), app.invoke); + const tasks = await app.collectLongTasks(session.page); + await sleep(IDLE_MS); + Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null }); + } else { + await sleep(IDLE_MS); + const tasks = await app.collectLongTasks(session.page); + Object.assign(sample, { longTaskCount: tasks?.count ?? null, longTaskMaxMs: tasks?.maxMs ?? null }); + } + Object.assign(sample, await app.readMemory(session, { settleMs: GC_SETTLE_MS })); + return sample; + } catch (error) { + const shot = path.join(output, `failure-${item.feature}-${item.scenario}-${item.run}.png`); + await session.page.screenshot({ path: shot }).catch(() => {}); + throw error; + } finally { + if (!prepared) { + try { + await applyState(session, mode, next?.enabled ?? new Set(), app.invoke); + await app.clearViewState(session.page); + } catch (error) { log(` cleanup: ${error.message}`); } + await app.stop(session); + } + } + } + + await runAll(plan); + if (featurePlan.length && !installed) { + session = await app.launch({ exe, port: options.port }); + try { + await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 }); + report.plugins = await installPlugins(session, options.features, app.invoke); + await session.page.reload(); + await session.page.locator(TABLE.knownRow).waitFor({ timeout: 60000 }); + await applyState(session, "plugin", featurePlan[0].enabled, app.invoke); + await app.clearViewState(session.page); + } finally { await app.stop(session); } + installed = true; + await save(); + } + await runAll(featurePlan); + await save(); + log(`Wrote ${reportPath} and ${path.join(output, "memory.md")}.`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + main().catch(error => { console.error(error?.stack ?? String(error)); process.exitCode = 1; }); +} diff --git a/tests/unit/release/measureFeatures.spec.ts b/tests/unit/release/measureFeatures.spec.ts new file mode 100644 index 0000000..2692632 --- /dev/null +++ b/tests/unit/release/measureFeatures.spec.ts @@ -0,0 +1,167 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { inflateSync } from 'node:zlib'; +import { checkTarget, INSTALLED_EXE, markdownTable, median, parseArguments, processTree, summarize } from '../../../scripts/measure/core.mjs'; +import { crc32, encodePng, gradientPixel, PNG_SIGNATURE, readPngChunks } from '../../../scripts/measure/png.mjs'; +import { readPdfXref, writePdf } from '../../../scripts/measure/pdf.mjs'; +import { cardFileName, pmFiles, seededUuid } from '../../../scripts/measure/fixture.mjs'; + +const required = ['--exe', 'build/runestone.exe', '--identifier', 'com.runestone.phase7-ram', '--stage', 'reference', '--mode', 'plugin', '--features', 'git,pdf']; +const env = { APPDATA: 'C:\\Users\\Test\\AppData\\Roaming', LOCALAPPDATA: 'C:\\Users\\Test\\AppData\\Local' }; + +test('the measurement tool reads its arguments and their defaults', () => { + const options = parseArguments(required); + assert.equal(options.exe, 'build/runestone.exe'); + assert.equal(options.identifier, 'com.runestone.phase7-ram'); + assert.deepEqual(options.features, ['git', 'pdf']); + assert.equal(options.runs, 3); + assert.equal(options.port, 9241); + assert.equal(options.freshFixture, false); + const custom = parseArguments([...required, '--runs', '5', '--port', '9300', '--fresh-fixture', '--only', 'base,git:in-use']); + assert.equal(custom.runs, 5); + assert.equal(custom.port, 9300); + assert.equal(custom.freshFixture, true); + assert.deepEqual(custom.only, ['base', 'git:in-use']); + assert.deepEqual(parseArguments([...required.slice(0, 8), '--features', 'git,git, pm']).features, ['git', 'pm']); +}); + +test('the measurement tool rejects missing, repeated, and unknown arguments', () => { + for (const args of [ + [], + required.slice(0, -2), + [...required, '--runs'], + [...required, '--runs', 'three'], + [...required, '--runs', '0'], + [...required, '--port', '80'], + [...required, '--mode', 'native'], + [...required, '--force'], + [...required.slice(0, 6), '--mode', 'hybrid', '--features', 'git'], + [...required.slice(0, 8), '--features', 'git,editor'], + [...required.slice(0, 4), '--stage', '../escape', '--mode', 'plugin', '--features', 'git'], + [...required, '--only', 'pm:in-use'], + [...required, '--only', 'git:busy'], + ]) assert.throws(() => parseArguments(args), Error, args.join(' ')); +}); + +test('the measurement tool refuses the installed app and its identifier', () => { + assert.throws(() => checkTarget({ exe: INSTALLED_EXE, identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/); + assert.throws(() => checkTarget({ exe: INSTALLED_EXE.toUpperCase(), identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/); + assert.throws(() => checkTarget({ exe: 'C:\\Users\\Test\\AppData\\Local\\RuneStone\\runestone.exe', identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/); + assert.throws(() => checkTarget({ exe: 'C:\\Users\\Test\\AppData\\Local\\RuneStone\\other.exe', identifier: 'com.runestone.phase7-ram' }, env), /installed RuneStone/); + for (const identifier of ['com.runestone.app', 'COM.RUNESTONE.APP', 'com.example.test', 'com.runestone.', 'com.runestone.../x', 'com.runestone.Test', undefined]) + assert.throws(() => checkTarget({ exe: 'D:\\build\\runestone.exe', identifier }, env), /Refusing the identifier/, String(identifier)); + assert.deepEqual(checkTarget({ exe: 'D:\\build\\runestone.exe', identifier: 'com.runestone.phase7-ram' }, env), { + roaming: 'C:\\Users\\Test\\AppData\\Roaming\\com.runestone.phase7-ram', + local: 'C:\\Users\\Test\\AppData\\Local\\com.runestone.phase7-ram', + }); +}); + +test('the median ignores missing values and averages the two middle values', () => { + assert.equal(median([]), null); + assert.equal(median([null, undefined, Number.NaN]), null); + assert.equal(median([3, 1, 2]), 2); + assert.equal(median([4, 1, 3, 2]), 2.5); + assert.equal(median([5, null, 1]), 3); + const summary: Record = summarize([{ privateMB: 100, startMs: 900 }, { privateMB: 120, startMs: 1100 }, { error: 'failed', privateMB: 999 }]); + assert.equal(summary.runs, 3); + assert.equal(summary.failed, 1); + assert.equal(summary.privateMB, 110); + assert.equal(summary.startMs, 1000); +}); + +test('the process tree walk sums only the descendants of the started process', () => { + const list = [ + { ProcessId: 4, ParentProcessId: 0, Name: 'System', PrivatePageCount: 1, WorkingSetSize: 1, Created: 1 }, + { ProcessId: 100, ParentProcessId: 4, Name: 'runestone.exe', PrivatePageCount: 10, WorkingSetSize: 20, Created: 10 }, + { ProcessId: 101, ParentProcessId: 100, Name: 'msedgewebview2.exe', PrivatePageCount: 30, WorkingSetSize: 40, Created: 11 }, + { ProcessId: 102, ParentProcessId: 101, Name: 'msedgewebview2.exe', PrivatePageCount: 50, WorkingSetSize: 60, Created: 12 }, + { ProcessId: 103, ParentProcessId: 100, Name: 'pwsh.exe', PrivatePageCount: 5, WorkingSetSize: 6, Created: 13 }, + // The installed app, a sibling tree that the walk must not count. + { ProcessId: 200, ParentProcessId: 4, Name: 'runestone.exe', PrivatePageCount: 1000, WorkingSetSize: 1000, Created: 9 }, + { ProcessId: 201, ParentProcessId: 200, Name: 'msedgewebview2.exe', PrivatePageCount: 1000, WorkingSetSize: 1000, Created: 9 }, + // A process whose parent ID was reused: it started before the process with that ID. + { ProcessId: 104, ParentProcessId: 100, Name: 'stale.exe', PrivatePageCount: 7, WorkingSetSize: 7, Created: 5 }, + ]; + const tree = processTree(list, 100); + assert.deepEqual(tree.processes.map(item => item.ProcessId), [100, 101, 103, 102]); + assert.equal(tree.privateBytes, 95); + assert.equal(tree.workingSet, 126); + assert.equal(tree.count, 4); + assert.deepEqual(tree.names, { 'runestone.exe': 1, 'msedgewebview2.exe': 2, 'pwsh.exe': 1 }); + assert.equal(processTree(list, 999).count, 0); + // A cycle in a stale process list does not loop. + assert.equal(processTree([{ ProcessId: 1, ParentProcessId: 2, Name: 'a' }, { ProcessId: 2, ParentProcessId: 1, Name: 'b' }], 1).count, 2); +}); + +test('the PNG writer gives a valid signature, chunk CRCs, and pixel data', () => { + assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926); + const png = encodePng(4, 3, gradientPixel(4, 3, [0, 0, 0], [255, 255, 255], 0)); + assert.ok(png.subarray(0, 8).equals(PNG_SIGNATURE)); + const chunks = readPngChunks(png); + assert.deepEqual(chunks.map(chunk => chunk.type), ['IHDR', 'IDAT', 'IEND']); + for (const chunk of chunks) assert.equal(chunk.stored, chunk.computed, chunk.type); + assert.equal(chunks[0].data.readUInt32BE(0), 4); + assert.equal(chunks[0].data.readUInt32BE(4), 3); + assert.equal(chunks[0].data[8], 8); + assert.equal(chunks[0].data[9], 2); + const raw = inflateSync(chunks[1].data); + assert.equal(raw.length, 3 * (1 + 4 * 3)); + assert.equal(raw[0], 0); + assert.deepEqual([...raw.subarray(1, 4)], [0, 0, 0]); + assert.deepEqual([...raw.subarray(10, 13)], [191, 191, 191]); + assert.throws(() => encodePng(0, 1, () => [0, 0, 0])); +}); + +test('the PDF writer gives a header, a trailer, and xref offsets that point to their objects', () => { + const pdf = writePdf(Array.from({ length: 50 }, (_, index) => `Page ${index + 1}`)); + const text = pdf.toString('latin1'); + assert.ok(text.startsWith('%PDF-1.4\n')); + assert.ok(text.endsWith('%%EOF\n')); + const xref = readPdfXref(pdf); + assert.equal(xref.count, 3 + 50 * 2 + 1); + assert.equal(xref.entries[0].line, '0000000000 65535 f '); + for (const [index, entry] of xref.entries.slice(1).entries()) { + assert.equal(entry.line.length + 1, 20, 'Each xref entry is 20 bytes.'); + assert.ok(entry.used); + assert.ok(text.startsWith(`${index + 1} 0 obj\n`, entry.offset), `Object ${index + 1} is at ${entry.offset}.`); + } + assert.match(text, /\/Type \/Pages \/Kids \[[^\]]+\] \/Count 50 >>/); + assert.match(text, /\(Page 25\) Tj/); + assert.match(text, new RegExp(`/Size ${xref.count} /Root 1 0 R`)); + // Stream lengths match the stream bytes. + for (const match of text.matchAll(/<< \/Length (\d+) >>\nstream\n/g)) { + const start = match.index + match[0].length; + assert.ok(text.startsWith('endstream', start + Number(match[1]))); + } + assert.match(writePdf(['A (b) \\ c']).toString('latin1'), /\(A \\\(b\\\) \\\\ c\) Tj/); +}); + +test('the Project Management fixture uses the card file names and ignore files of the real store', () => { + const files = pmFiles(); + assert.equal(files.get('.runestone/pm/cards/.gitignore'), '*\n'); + assert.match(files.get('.runestone/pm/.gitignore')!, /^\*$/m); + const catalog = JSON.parse(files.get('.runestone/pm/workspace.json')!); + assert.equal(catalog.schema, 1); + assert.equal(catalog.boards.length, 8); + const cards = [...files.keys()].filter(name => name.startsWith('.runestone/pm/cards/') && name.endsWith('.md')); + assert.equal(cards.length, 400); + const id = seededUuid('card-0-0'); + assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + assert.equal(cardFileName(id), `${Buffer.from(id).toString('hex')}.md`); + assert.match(files.get(`.runestone/pm/cards/${cardFileName(id)}`)!, new RegExp(`^---\\nrunestone_pm:\\n schema: 1\\n id: ${id}\\n kind: task\\n`)); +}); + +test('the report table has one row for each scenario and marks failures', () => { + const report = { + stage: 'reference', build: 'x.exe', identifier: 'com.runestone.phase7-ram', mode: 'plugin', runs: 3, date: '2026-10-29', + machine: { cpu: 'CPU', ramGB: 32, windows: 'Windows 11' }, + rows: [ + { feature: 'base', scenario: 'base', median: { runs: 3, failed: 0, privateMB: 200.04, workingSetMB: 300, heapMB: 20, startMs: 1500.4, firstNeedMs: null, longTaskCount: 1, longTaskMaxMs: 80 } }, + { feature: 'pdf', scenario: 'in-use', median: { runs: 3, failed: 3 }, reason: 'timeout | x' }, + ], + }; + const table = markdownTable(report); + assert.match(table, /\| base \| base \| 200\.0 \| 300\.0 \| 20\.0 \| 1500 \| – \| 1 \/ 80 \|/); + assert.match(table, /\| pdf \| in-use \| failed \|/); + assert.doesNotMatch(table, /timeout \| x/); +});