agentlane 0.0.0 → 0.4.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +27 -0
  3. package/README.md +167 -2
  4. package/dist/agents/claude-plugin.js +79 -0
  5. package/dist/agents/cli.js +258 -0
  6. package/dist/agents/detect.js +88 -0
  7. package/dist/agents/init.js +251 -0
  8. package/dist/agents/launcher.js +32 -0
  9. package/dist/agents/package.js +119 -0
  10. package/dist/agents/skills.js +59 -0
  11. package/dist/agents/toml.js +325 -0
  12. package/dist/agents/wiring-check.js +117 -0
  13. package/dist/agents/wiring.js +374 -0
  14. package/dist/bench/host.js +104 -0
  15. package/dist/bench/live.js +511 -0
  16. package/dist/bench/mcp-client.js +91 -0
  17. package/dist/bench/model.js +15 -0
  18. package/dist/bench/report.js +162 -0
  19. package/dist/bench/run.js +121 -0
  20. package/dist/bench/schedule.js +140 -0
  21. package/dist/bench/stats.js +59 -0
  22. package/dist/bench-cli.js +167 -0
  23. package/dist/browser/aria.js +184 -0
  24. package/dist/browser/control.js +203 -0
  25. package/dist/browser/env.js +118 -0
  26. package/dist/browser/evidence.js +44 -0
  27. package/dist/browser/install.js +361 -0
  28. package/dist/browser/kinds.js +10 -0
  29. package/dist/browser/lane-browser.js +224 -0
  30. package/dist/browser/libraries.js +56 -0
  31. package/dist/browser/paths.js +29 -0
  32. package/dist/browser/release.js +121 -0
  33. package/dist/browser/screen.js +19 -0
  34. package/dist/browser/signin.js +154 -0
  35. package/dist/browser/stop.js +163 -0
  36. package/dist/browser/tools.js +25 -0
  37. package/dist/cache/build.js +154 -0
  38. package/dist/cache/config.js +186 -0
  39. package/dist/cache/index.js +4 -0
  40. package/dist/cache/key.js +196 -0
  41. package/dist/cache/store.js +303 -0
  42. package/dist/cli.js +178 -0
  43. package/dist/clock.js +4 -0
  44. package/dist/devices/adb.js +160 -0
  45. package/dist/devices/android.js +214 -0
  46. package/dist/devices/backend.js +7 -0
  47. package/dist/devices/bundler.js +46 -0
  48. package/dist/devices/common.js +51 -0
  49. package/dist/devices/controls.js +65 -0
  50. package/dist/devices/dial.js +56 -0
  51. package/dist/devices/emulator.js +396 -0
  52. package/dist/devices/hygiene.js +202 -0
  53. package/dist/devices/index.js +5 -0
  54. package/dist/devices/launch.js +76 -0
  55. package/dist/devices/simctl.js +119 -0
  56. package/dist/devices/tools.js +1 -0
  57. package/dist/devices/variant.js +99 -0
  58. package/dist/devices/xcrun.js +265 -0
  59. package/dist/driver/absence.js +54 -0
  60. package/dist/driver/caller.js +51 -0
  61. package/dist/driver/client.js +312 -0
  62. package/dist/driver/diff.js +180 -0
  63. package/dist/driver/elements.js +70 -0
  64. package/dist/driver/engine-main.js +13 -0
  65. package/dist/driver/engine.js +499 -0
  66. package/dist/driver/errors.js +11 -0
  67. package/dist/driver/exec.js +66 -0
  68. package/dist/driver/failure.js +156 -0
  69. package/dist/driver/flow.js +94 -0
  70. package/dist/driver/idle.js +100 -0
  71. package/dist/driver/images.js +68 -0
  72. package/dist/driver/install.js +272 -0
  73. package/dist/driver/lock.js +101 -0
  74. package/dist/driver/look.js +223 -0
  75. package/dist/driver/maestro-child.js +194 -0
  76. package/dist/driver/maestro-runs.js +46 -0
  77. package/dist/driver/paths.js +105 -0
  78. package/dist/driver/pixels.js +144 -0
  79. package/dist/driver/plan.js +108 -0
  80. package/dist/driver/release.js +7 -0
  81. package/dist/driver/runner.js +42 -0
  82. package/dist/driver/selector.js +91 -0
  83. package/dist/driver/session.js +474 -0
  84. package/dist/driver/suggest.js +86 -0
  85. package/dist/driver/supervisor.js +251 -0
  86. package/dist/driver/tree.js +426 -0
  87. package/dist/driver-cli.js +865 -0
  88. package/dist/evidence/device.js +177 -0
  89. package/dist/evidence/evidence.js +304 -0
  90. package/dist/evidence/files.js +92 -0
  91. package/dist/hooks/env.js +81 -0
  92. package/dist/hooks/run.js +101 -0
  93. package/dist/mcp/server.js +69 -0
  94. package/dist/mcp/tools.js +246 -0
  95. package/dist/name.js +22 -0
  96. package/dist/plugin/aims.js +465 -0
  97. package/dist/plugin/conventions.js +73 -0
  98. package/dist/plugin/guard.js +163 -0
  99. package/dist/plugin/hook-cli.js +216 -0
  100. package/dist/plugin/session-name.js +28 -0
  101. package/dist/plugin/shell.js +254 -0
  102. package/dist/processes.js +77 -0
  103. package/dist/project/config.js +316 -0
  104. package/dist/project/schema.js +335 -0
  105. package/dist/project/validate.js +224 -0
  106. package/dist/registry/config.js +142 -0
  107. package/dist/registry/format.js +22 -0
  108. package/dist/registry/owner.js +265 -0
  109. package/dist/registry/paths.js +50 -0
  110. package/dist/registry/ports.js +26 -0
  111. package/dist/registry/prune.js +160 -0
  112. package/dist/registry/refusal.js +53 -0
  113. package/dist/registry/registry.js +1027 -0
  114. package/dist/registry/resources.js +117 -0
  115. package/dist/registry/rows.js +115 -0
  116. package/dist/registry/status.js +85 -0
  117. package/dist/registry/store.js +274 -0
  118. package/dist/registry/types.js +1 -0
  119. package/dist/registry-cli.js +544 -0
  120. package/dist/services/services.js +268 -0
  121. package/dist/services/system.js +189 -0
  122. package/dist/up/deps.js +1 -0
  123. package/dist/up/doctor.js +424 -0
  124. package/dist/up/exec.js +133 -0
  125. package/dist/up/lane-files.js +75 -0
  126. package/dist/up/lane-services.js +38 -0
  127. package/dist/up/maestro-env.js +172 -0
  128. package/dist/up/preflight.js +232 -0
  129. package/dist/up/release.js +148 -0
  130. package/dist/up/resources.js +178 -0
  131. package/dist/up/restart.js +87 -0
  132. package/dist/up/setup.js +28 -0
  133. package/dist/up/up.js +610 -0
  134. package/dist/up-cli.js +258 -0
  135. package/dist/usage.js +16 -0
  136. package/package.json +58 -3
  137. package/schema/agentlane.schema.json +675 -0
  138. package/skills/create-verification-skill/LICENSE +21 -0
  139. package/skills/create-verification-skill/SKILL.md +88 -0
  140. package/skills/dev-loop/LICENSE +21 -0
  141. package/skills/dev-loop/SKILL.md +61 -0
  142. package/skills/device/SKILL.md +8 -0
  143. package/skills/drive/SKILL.md +64 -0
  144. package/skills/maintain-verification-skill/LICENSE +21 -0
  145. package/skills/maintain-verification-skill/SKILL.md +42 -0
  146. package/skills/setup/SKILL.md +80 -0
@@ -0,0 +1,162 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { CELLS, OPS } from "./model.js";
4
+ import { median, relativeDifference } from "./stats.js";
5
+ const s = (ms) => (ms / 1000).toFixed(3);
6
+ function loadText(sample) {
7
+ return sample.loadavg.map(x => x.toFixed(1)).join(' ');
8
+ }
9
+ function memoryText(sample) {
10
+ const free = sample.memoryFreePercent === null ? '?' : `${String(sample.memoryFreePercent)}% free`;
11
+ const swap = sample.swapUsedMb === null ? '' : `, swap ${(sample.swapUsedMb / 1024).toFixed(1)} GB`;
12
+ return `${sample.pressure}, ${free}${swap}`;
13
+ }
14
+ export function reportStem(startedAt) {
15
+ return `bench-${startedAt.replace(/:/g, '').replace(/\.\d+Z$/, 'Z')}`;
16
+ }
17
+ function cellOrder(b) {
18
+ return CELLS.indexOf(b.cell) * 100 + OPS.indexOf(b.op) * 10 + b.attempt;
19
+ }
20
+ function row(b) {
21
+ const flag = b.aborted ? `aborted: ${b.aborted}` : b.verdict.high ? `HIGH LOAD: ${b.verdict.reasons.join('; ')}` : '';
22
+ return b.series.map(series => {
23
+ const sum = series.summary;
24
+ const outliers = sum && sum.outliers.length > 0 ? sum.outliers.map(s).join(', ') : '';
25
+ return [
26
+ b.cell,
27
+ b.op,
28
+ series.sim,
29
+ sum ? String(sum.n) : '0',
30
+ sum ? s(sum.median) : '-',
31
+ sum ? s(sum.p90) : '-',
32
+ sum ? `${s(sum.min)}–${s(sum.max)}` : '-',
33
+ String(series.failures),
34
+ outliers,
35
+ `${b.load.start.loadavg[0].toFixed(1)} → ${b.load.end.loadavg[0].toFixed(1)}`,
36
+ flag,
37
+ ].join(' | ');
38
+ });
39
+ }
40
+ function table(batches) {
41
+ return [
42
+ '| cell | op | sim | n | median s | p90 s | min–max s | failed | outliers s | load 1-min start → end | flag |',
43
+ '|---|---|---|---|---|---|---|---|---|---|---|',
44
+ ...[...batches].sort((a, b) => cellOrder(a) - cellOrder(b)).flatMap(b => row(b).map(r => `| ${r} |`)),
45
+ ];
46
+ }
47
+ function phaseMedians(b) {
48
+ const keys = new Set();
49
+ const samples = b.series.flatMap(x => x.samples.filter(sample => sample.ok));
50
+ for (const sample of samples)
51
+ for (const key of Object.keys(sample.phases))
52
+ keys.add(key);
53
+ const parts = [];
54
+ for (const key of keys) {
55
+ const values = samples.map(sample => sample.phases[key]).filter((v) => v !== undefined);
56
+ if (values.length === 0)
57
+ continue;
58
+ parts.push(`${key} ${s(median(values))}`);
59
+ }
60
+ const gates = samples.reduce((sum, sample) => sum + sample.gateReads, 0);
61
+ return `${parts.join(', ')}${gates > 0 ? `; ${String(gates)} gate reads over ${String(samples.length)} samples` : ''}`;
62
+ }
63
+ export function renderMarkdown(result, jsonName) {
64
+ const chosen = result.batches.filter(b => !b.superseded);
65
+ const replaced = result.batches.filter(b => b.superseded);
66
+ const flagged = chosen.filter(b => b.verdict.high);
67
+ const { host, toolkit, maestro } = result;
68
+ const lines = [
69
+ `# agentlane bench, ${result.startedAt.slice(0, 10)}`,
70
+ '',
71
+ `Run ${result.startedAt} → ${result.finishedAt}. Raw timings: \`${jsonName}\`. Method: \`bench/README.md\` in the package.`,
72
+ '',
73
+ '## Conditions',
74
+ '',
75
+ '| | |',
76
+ '|---|---|',
77
+ `| Host | ${host.model}, ${host.chip}, ${String(host.cores)} cores, ${String(host.memoryGb)} GB |`,
78
+ `| macOS | ${host.macos} |`,
79
+ `| Xcode | ${host.xcode} |`,
80
+ `| ${{ ios: 'Simulators', android: 'Emulators', web: 'Browsers' }[result.options.platform ?? 'ios']} | ${result.targets.map(t => `${t.sim}: ${t.deviceName} (${t.deviceType}, ${t.runtime}, ${t.udid})`).join('; ')} |`,
81
+ `| Installed runtimes | ${host.runtimes.join(', ')} |`,
82
+ `| Toolkit | ${toolkit.version}, commit ${toolkit.commit ?? 'unknown'}${toolkit.dirty ? ' (uncommitted changes)' : ''} |`,
83
+ `| Maestro | ${maestro.version}${maestro.override ? ' (AGENTLANE_MAESTRO override)' : ''}, reports \`${maestro.reportedVersion ?? 'unknown'}\`; release zip sha256 ${maestro.releaseSha256}; CLI jar sha256 ${maestro.jarSha256 ?? 'unknown'} |`,
84
+ `| Node | ${host.node} |`,
85
+ `| Samples per cell | ${String(result.options.samples)}; load limit ${result.options.maxLoad.toFixed(1)} (1-min load average) |`,
86
+ '',
87
+ '## Summary',
88
+ '',
89
+ 'Wall-clock seconds the caller waits, from the timer start the method names for each cell to the successful answer. Failed samples are excluded from the figures and counted.',
90
+ '',
91
+ ...table(chosen),
92
+ '',
93
+ ];
94
+ lines.push('## Load and memory per batch', '');
95
+ lines.push('| batch | load start (1/5/15 min) | load end | memory start | memory end | waited for load s |', '|---|---|---|---|---|---|');
96
+ for (const b of [...chosen].sort((x, y) => cellOrder(x) - cellOrder(y))) {
97
+ lines.push(`| ${b.id} | ${loadText(b.load.start)} | ${loadText(b.load.end)} | ${memoryText(b.load.start)} | ${memoryText(b.load.end)} | ${s(b.loadWaitMs)} |`);
98
+ }
99
+ lines.push('', '## Phases (medians of successful samples)', '');
100
+ for (const b of [...chosen].sort((x, y) => cellOrder(x) - cellOrder(y)))
101
+ lines.push(`- ${b.id}: ${phaseMedians(b)}`);
102
+ lines.push('');
103
+ if (flagged.length > 0) {
104
+ lines.push('## Batches run under high load', '', "These ran with the load or memory pressure over the limit, and no rerun got under it. Treat their figures as upper bounds, not as the toolkit's speed.", '', ...flagged.map(b => `- ${b.id}: ${b.verdict.reasons.join('; ')}`), '');
105
+ }
106
+ if (replaced.length > 0) {
107
+ lines.push('## Replaced attempts', '', 'Earlier attempts a rerun replaced in the summary; their samples are in the JSON.', '', ...table(replaced), '');
108
+ }
109
+ if (result.notes.length > 0)
110
+ lines.push('## Notes', '', ...result.notes.map(n => `- ${n}`), '');
111
+ return lines.join('\n');
112
+ }
113
+ export function writeReport(dir, result) {
114
+ fs.mkdirSync(dir, { recursive: true });
115
+ const stem = reportStem(result.startedAt);
116
+ const json = path.join(dir, `${stem}.json`);
117
+ const markdown = path.join(dir, `${stem}.md`);
118
+ fs.writeFileSync(json, `${JSON.stringify(result, null, 2)}\n`);
119
+ fs.writeFileSync(markdown, renderMarkdown(result, path.basename(json)));
120
+ return { markdown, json };
121
+ }
122
+ /** Compares the medians of two runs, cell by cell, against a tolerance (0.2 is the plan's 20%). */
123
+ export function compareRuns(a, b, tolerance, cells = ['warm']) {
124
+ const out = [];
125
+ const pick = (r, cell, op) => r.batches.find(x => x.cell === cell && x.op === op && !x.superseded);
126
+ for (const cell of cells) {
127
+ for (const op of OPS) {
128
+ const left = pick(a, cell, op);
129
+ const right = pick(b, cell, op);
130
+ if (!left || !right)
131
+ continue;
132
+ for (const series of left.series) {
133
+ const other = right.series.find(x => x.sim === series.sim);
134
+ if (!series.summary || !other?.summary)
135
+ continue;
136
+ const difference = relativeDifference(series.summary.median, other.summary.median);
137
+ out.push({
138
+ cell,
139
+ op,
140
+ sim: series.sim,
141
+ a: series.summary.median,
142
+ b: other.summary.median,
143
+ difference,
144
+ within: difference <= tolerance,
145
+ flagged: left.verdict.high || right.verdict.high,
146
+ });
147
+ }
148
+ }
149
+ }
150
+ return out;
151
+ }
152
+ export function renderAgreement(rows, a, b, tolerance) {
153
+ const hours = (Date.parse(b.startedAt) - Date.parse(a.startedAt)) / 3_600_000;
154
+ const lines = [
155
+ `Run A ${a.startedAt} (commit ${a.toolkit.commit ?? '?'}), run B ${b.startedAt} (commit ${b.toolkit.commit ?? '?'}): ${hours.toFixed(1)} h apart.`,
156
+ '',
157
+ `| cell | op | sim | A median s | B median s | difference | within ${String(Math.round(tolerance * 100))}% |`,
158
+ '|---|---|---|---|---|---|---|',
159
+ ...rows.map(r => `| ${r.cell} | ${r.op} | ${r.sim} | ${s(r.a)} | ${s(r.b)} | ${(r.difference * 100).toFixed(1)}% | ${r.within ? 'yes' : 'NO'}${r.flagged ? ' (high load in a run)' : ''} |`),
160
+ ];
161
+ return `${lines.join('\n')}\n`;
162
+ }
@@ -0,0 +1,121 @@
1
+ import path from 'node:path';
2
+ import { systemClock } from "../clock.js";
3
+ import { createXcrunTools } from "../devices/xcrun.js";
4
+ import { CONFIG_FILE, TOOL } from "../name.js";
5
+ import { findProjectConfig, loadProjectConfig } from "../project/config.js";
6
+ import { UsageError } from "../registry/refusal.js";
7
+ import { collectHost, collectMaestro, collectToolkit, sampleLoad } from "./host.js";
8
+ import { closeTarget, openTarget, planFor, releaseFolder, TARGET_APP } from "./live.js";
9
+ import { CELLS, MIN_PUBLISHED_SAMPLES, OPS, PLATFORM_CELLS, PLATFORM_OPS, SCHEMA, } from "./model.js";
10
+ import { writeReport } from "./report.js";
11
+ import { runBatches } from "./schedule.js";
12
+ function requireExampleApp(folder, platform) {
13
+ const file = findProjectConfig(folder);
14
+ if (!file)
15
+ throw new UsageError(`no ${CONFIG_FILE} in ${folder} or above it`, `run ${TOOL} bench in examples/expo-app`);
16
+ const config = loadProjectConfig(file);
17
+ if (platform === 'web' && !config.web) {
18
+ throw new UsageError(`${file} declares no web app`, `run ${TOOL} bench --platform web in examples/expo-app`);
19
+ }
20
+ if (config.app?.bundleId !== TARGET_APP.bundleId) {
21
+ throw new UsageError(`${file} is for ${config.app?.bundleId ?? 'a web app only'}; the bench drives the example app, ${TARGET_APP.bundleId}`, `run ${TOOL} bench in examples/expo-app, or pass --worktree <checkout>/examples/expo-app`);
22
+ }
23
+ }
24
+ export async function runBench(request, deps) {
25
+ for (const folder of request.folders)
26
+ requireExampleApp(folder, request.platform);
27
+ const cells = PLATFORM_CELLS[request.platform];
28
+ const ops = PLATFORM_OPS[request.platform];
29
+ if (request.platform === 'android' && request.cells.includes('cold-cold')) {
30
+ throw new UsageError('cold-cold shuts the device down between samples, and an emulator lane boots its emulator only when it is claimed', `leave out cold-cold on Android: --cells ${cells.join(',')}`);
31
+ }
32
+ const otherCells = request.cells.filter(cell => !cells.includes(cell));
33
+ if (otherCells.length > 0) {
34
+ throw new UsageError(`--platform ${request.platform} has no ${otherCells.join(', ')} cell: a browser lane is measured warm, where the browser and the page are up`, `pass --cells ${cells.join(',')}`);
35
+ }
36
+ const otherOps = request.ops.filter(op => !ops.includes(op));
37
+ if (otherOps.length > 0) {
38
+ throw new UsageError(`--platform ${request.platform} has no ${otherOps.join(', ')} op`, `pick from ${ops.join(',')}`);
39
+ }
40
+ const startedAt = new Date().toISOString();
41
+ const notes = [];
42
+ if (request.samples < MIN_PUBLISHED_SAMPLES)
43
+ notes.push(`${String(request.samples)} samples per cell is below the ${String(MIN_PUBLISHED_SAMPLES)} the method asks for publication.`);
44
+ const noun = request.platform === 'android' ? 'emulator' : request.platform === 'web' ? 'browser' : 'simulator';
45
+ if (request.folders.length < 2)
46
+ notes.push(`One ${noun} only: no --pair folder was given, so the warm cells did not alternate two ${noun}s.`);
47
+ deps.log('collecting the host, toolkit and Maestro details');
48
+ const host = collectHost();
49
+ const toolkit = collectToolkit();
50
+ const maestro = await collectMaestro(deps.env);
51
+ if (toolkit.dirty)
52
+ notes.push('The toolkit checkout had uncommitted changes to tracked files.');
53
+ const live = {
54
+ env: deps.env,
55
+ processes: deps.processes,
56
+ platform: request.platform,
57
+ sim: createXcrunTools(),
58
+ log: deps.log,
59
+ };
60
+ const targets = [];
61
+ let batches;
62
+ try {
63
+ for (const [index, folder] of request.folders.entries()) {
64
+ try {
65
+ targets.push(await openTarget(index === 0 ? 'A' : 'B', path.resolve(folder), live, request.setup));
66
+ }
67
+ catch (error) {
68
+ deps.log(`releasing ${folder} after a failed start: ${await releaseFolder(path.resolve(folder), live)}`);
69
+ throw error;
70
+ }
71
+ }
72
+ const [first] = targets;
73
+ if (!first)
74
+ throw new Error(`no ${noun} was brought up`);
75
+ const plans = CELLS.filter(cell => request.cells.includes(cell)).flatMap(cell => OPS.filter(op => request.ops.includes(op)).map(op => planFor(cell, op, cell === 'warm' ? targets : [first], live)));
76
+ batches = await runBatches(plans, {
77
+ load: sampleLoad,
78
+ clock: systemClock,
79
+ log: deps.log,
80
+ samples: request.samples,
81
+ maxLoad: request.maxLoad,
82
+ loadWaitMs: request.loadWaitMs,
83
+ rerunFlagged: request.rerunFlagged,
84
+ stopped: deps.stopped,
85
+ });
86
+ if (deps.stopped())
87
+ notes.push('Stopped early by a signal; the batches that ran are reported.');
88
+ }
89
+ finally {
90
+ for (const target of targets) {
91
+ try {
92
+ notes.push(...(await closeTarget(target, live)));
93
+ }
94
+ catch (error) {
95
+ notes.push(`${target.info.sim}: cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
96
+ }
97
+ }
98
+ }
99
+ const result = {
100
+ schema: SCHEMA,
101
+ startedAt,
102
+ finishedAt: new Date().toISOString(),
103
+ command: request.command,
104
+ options: {
105
+ platform: request.platform,
106
+ samples: request.samples,
107
+ cells: request.cells,
108
+ ops: request.ops,
109
+ maxLoad: request.maxLoad,
110
+ loadWaitMs: request.loadWaitMs,
111
+ rerunFlagged: request.rerunFlagged,
112
+ },
113
+ host,
114
+ toolkit,
115
+ maestro,
116
+ targets: targets.map(t => t.info),
117
+ batches,
118
+ notes,
119
+ };
120
+ return { result, ...writeReport(request.out, result) };
121
+ }
@@ -0,0 +1,140 @@
1
+ import { judgeLoad, summarize } from "./stats.js";
2
+ export const MAX_CONSECUTIVE_FAILURES = 3;
3
+ async function waitForLoad(deps) {
4
+ const started = deps.clock.now();
5
+ const poll = deps.loadPollMs ?? 5000;
6
+ let logged = false;
7
+ for (;;) {
8
+ const now = deps.load();
9
+ const load1 = now.loadavg[0];
10
+ const pressed = now.pressure === 'warn' || now.pressure === 'critical';
11
+ if (load1 < deps.maxLoad && !pressed)
12
+ return { waitedMs: deps.clock.now() - started, below: true };
13
+ const waited = deps.clock.now() - started;
14
+ if (waited >= deps.loadWaitMs)
15
+ return { waitedMs: waited, below: false };
16
+ if (!logged) {
17
+ const why = pressed
18
+ ? `memory pressure is ${now.pressure}`
19
+ : `load ${load1.toFixed(1)} is at or above ${deps.maxLoad.toFixed(1)}`;
20
+ deps.log(`${why}; waiting up to ${String(Math.round(deps.loadWaitMs / 1000))} s`);
21
+ logged = true;
22
+ }
23
+ if (deps.stopped?.())
24
+ return { waitedMs: waited, below: false };
25
+ await deps.clock.sleep(Math.min(poll, deps.loadWaitMs - waited));
26
+ }
27
+ }
28
+ function messageOf(error) {
29
+ return error instanceof Error ? error.message : String(error);
30
+ }
31
+ function failedSample(clock, error) {
32
+ return { ms: 0, ok: false, startedAt: new Date(clock.now()).toISOString(), phases: {}, gateReads: 0, error: messageOf(error) };
33
+ }
34
+ function seriesOf(sim, samples) {
35
+ const ok = samples.filter(s => s.ok).map(s => s.ms);
36
+ return { sim, samples, summary: summarize(ok), failures: samples.length - ok.length };
37
+ }
38
+ async function runBatch(plan, attempt, deps) {
39
+ const { waitedMs } = await waitForLoad(deps);
40
+ const id = `${plan.cell}/${plan.op}#${String(attempt)}`;
41
+ const samples = new Map(plan.sims.map(sim => [sim, []]));
42
+ let aborted;
43
+ const startedAt = new Date(deps.clock.now()).toISOString();
44
+ try {
45
+ await plan.prepare();
46
+ }
47
+ catch (error) {
48
+ aborted = `preparing the batch failed: ${messageOf(error)}`;
49
+ }
50
+ const start = deps.load();
51
+ const streak = new Map(plan.sims.map(sim => [sim, 0]));
52
+ for (let index = 0; index < deps.samples && !aborted; index++) {
53
+ for (const sim of plan.sims) {
54
+ if (deps.stopped?.()) {
55
+ aborted = 'stopped by a signal';
56
+ break;
57
+ }
58
+ const load1 = deps.load().loadavg[0];
59
+ let sample;
60
+ try {
61
+ sample = await plan.sample(sim, index);
62
+ }
63
+ catch (error) {
64
+ sample = failedSample(deps.clock, error);
65
+ }
66
+ sample.load1 = load1;
67
+ samples.get(sim)?.push(sample);
68
+ const run = sample.ok ? 0 : (streak.get(sim) ?? 0) + 1;
69
+ streak.set(sim, run);
70
+ if (run >= MAX_CONSECUTIVE_FAILURES) {
71
+ aborted = `${String(run)} samples in a row failed on ${sim}; last: ${sample.error ?? 'no error text'}`;
72
+ break;
73
+ }
74
+ }
75
+ }
76
+ const end = deps.load();
77
+ const batch = {
78
+ id,
79
+ cell: plan.cell,
80
+ op: plan.op,
81
+ attempt,
82
+ startedAt,
83
+ finishedAt: new Date(deps.clock.now()).toISOString(),
84
+ loadWaitMs: waitedMs,
85
+ load: { start, end },
86
+ verdict: judgeLoad(start, end, deps.maxLoad, plan.selfLoading),
87
+ superseded: false,
88
+ series: plan.sims.map(sim => seriesOf(sim, samples.get(sim) ?? [])),
89
+ ...(aborted ? { aborted } : {}),
90
+ };
91
+ const medians = batch.series
92
+ .map(s => `${s.sim} ${s.summary ? `${(s.summary.median / 1000).toFixed(3)} s` : 'none'}`)
93
+ .join(', ');
94
+ deps.log(`${id}: median ${medians}; load ${start.loadavg[0].toFixed(1)} → ${end.loadavg[0].toFixed(1)}${batch.verdict.high ? ' (HIGH LOAD)' : ''}${aborted ? `; aborted: ${aborted}` : ''}`);
95
+ return batch;
96
+ }
97
+ /** Marks every attempt but the chosen one per cell and op: the last attempt not under high load, else the last. */
98
+ export function markSuperseded(batches) {
99
+ const groups = new Map();
100
+ for (const b of batches) {
101
+ const key = `${b.cell}/${b.op}`;
102
+ groups.set(key, [...(groups.get(key) ?? []), b]);
103
+ }
104
+ for (const group of groups.values()) {
105
+ const usable = group.filter(b => !b.aborted);
106
+ const chosen = usable.filter(b => !b.verdict.high).at(-1) ?? usable.at(-1) ?? group.at(-1);
107
+ for (const b of group)
108
+ b.superseded = b !== chosen;
109
+ }
110
+ }
111
+ /**
112
+ * Runs each plan as one batch. A batch waits (up to loadWaitMs) for the load to drop below the limit before it starts;
113
+ * a batch that still ran under high load is flagged, and with rerunFlagged it runs once more at the end if the load
114
+ * has dropped by then. Every attempt is kept; the summary uses the chosen one.
115
+ */
116
+ export async function runBatches(plans, deps) {
117
+ const batches = [];
118
+ for (const plan of plans) {
119
+ if (deps.stopped?.())
120
+ break;
121
+ batches.push(await runBatch(plan, 1, deps));
122
+ }
123
+ if (deps.rerunFlagged) {
124
+ for (const plan of plans) {
125
+ if (deps.stopped?.())
126
+ break;
127
+ const first = batches.find(b => b.cell === plan.cell && b.op === plan.op);
128
+ if (!first?.verdict.high)
129
+ continue;
130
+ const { below } = await waitForLoad(deps);
131
+ if (!below) {
132
+ deps.log(`${first.id}: not rerun, the load or memory pressure is still over the limit`);
133
+ continue;
134
+ }
135
+ batches.push(await runBatch(plan, 2, deps));
136
+ }
137
+ }
138
+ markSuperseded(batches);
139
+ return batches;
140
+ }
@@ -0,0 +1,59 @@
1
+ export const OUTLIER_IQR_MULTIPLE = 3;
2
+ /** The p-quantile (0 ≤ p ≤ 1) by linear interpolation between the closest ranks (Hyndman and Fan type 7, numpy's default). */
3
+ export function quantile(values, p) {
4
+ if (values.length === 0)
5
+ throw new Error('no values');
6
+ if (!(p >= 0 && p <= 1))
7
+ throw new Error(`${String(p)} is not a quantile`);
8
+ const sorted = [...values].sort((a, b) => a - b);
9
+ const rank = p * (sorted.length - 1);
10
+ const low = Math.floor(rank);
11
+ const high = Math.ceil(rank);
12
+ const a = sorted[low] ?? 0;
13
+ const b = sorted[high] ?? a;
14
+ return a + (b - a) * (rank - low);
15
+ }
16
+ export function median(values) {
17
+ return quantile(values, 0.5);
18
+ }
19
+ export function summarize(values) {
20
+ if (values.length === 0)
21
+ return null;
22
+ const q1 = quantile(values, 0.25);
23
+ const q3 = quantile(values, 0.75);
24
+ const fence = q3 + OUTLIER_IQR_MULTIPLE * (q3 - q1);
25
+ return {
26
+ n: values.length,
27
+ median: median(values),
28
+ p90: quantile(values, 0.9),
29
+ min: Math.min(...values),
30
+ max: Math.max(...values),
31
+ mean: values.reduce((sum, v) => sum + v, 0) / values.length,
32
+ outliers: values.filter(v => v > fence),
33
+ };
34
+ }
35
+ /**
36
+ * A batch counts as run under high load when the 1-minute load average at its start or its end reached the limit, or
37
+ * the kernel reported memory pressure above normal at either end. A batch that boots simulators itself raises the load
38
+ * it ends with, so for it only the start load counts.
39
+ */
40
+ export function judgeLoad(start, end, maxLoad, selfLoading = false) {
41
+ const reasons = [];
42
+ for (const [when, sample] of [
43
+ ['start', start],
44
+ ['end', end],
45
+ ]) {
46
+ const load1 = sample.loadavg[0];
47
+ if (load1 >= maxLoad && !(selfLoading && when === 'end'))
48
+ reasons.push(`1-min load ${load1.toFixed(1)} at the ${when} (limit ${maxLoad.toFixed(1)})`);
49
+ if (sample.pressure === 'warn' || sample.pressure === 'critical')
50
+ reasons.push(`memory pressure ${sample.pressure} at the ${when}`);
51
+ }
52
+ return { high: reasons.length > 0, reasons };
53
+ }
54
+ /** The agreement check between two runs: |b − a| / a for each median, as a fraction. */
55
+ export function relativeDifference(a, b) {
56
+ if (a === 0)
57
+ return b === 0 ? 0 : Number.POSITIVE_INFINITY;
58
+ return Math.abs(b - a) / a;
59
+ }
@@ -0,0 +1,167 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { parseArgs } from 'node:util';
5
+ import { CELLS, MIN_PUBLISHED_SAMPLES, OPS, PLATFORM_CELLS, PLATFORM_OPS, SCHEMA, } from "./bench/model.js";
6
+ import { compareRuns, renderAgreement } from "./bench/report.js";
7
+ import { runBench } from "./bench/run.js";
8
+ import { TOOL } from "./name.js";
9
+ import { stateDir } from "./registry/paths.js";
10
+ import { NotClaimed, Refusal, UsageError } from "./registry/refusal.js";
11
+ import { groupUsage, helpOf } from "./usage.js";
12
+ export const BENCH_COMMANDS = ['bench'];
13
+ export const BENCH_HELP = {
14
+ title: 'Benchmark (the method: bench/README.md in the package):',
15
+ entries: {
16
+ bench: ` bench Measure the toolkit on examples/expo-app: cold-cold, cold, warm, relaunch and first interaction,
17
+ each with read, screenshot, quick tap, tap and a short flow; on the web app's browser lane, warm
18
+ read, screenshot, click and flow. Writes a dated Markdown report and its JSON.
19
+ --worktree <dir> the example app's folder (default: this folder)
20
+ --platform <name> ios (default), android or web; android has no cold-cold cell, web only warm
21
+ --pair <dir> the example app in a second checkout; the warm cells then alternate two devices
22
+ --samples <n> calls per cell and simulator (default ${String(MIN_PUBLISHED_SAMPLES)})
23
+ --cells <list> some of ${CELLS.join(',')} (default: all the platform has)
24
+ --ops <list> some of ${OPS.join(',')} (default: all the platform has)
25
+ --max-load <n> the 1-min load average that flags a batch (default: the core count)
26
+ --load-wait <s> how long a batch waits for the load to drop under that (default 300)
27
+ --no-rerun keep flagged batches as they are instead of rerunning them once at the end
28
+ --no-setup skip the setup hook in the first up
29
+ --out <dir> where the report goes (default: <state dir>/bench)
30
+ bench compare <a.json> <b.json>: the two runs' medians side by side.
31
+ --tolerance <f> the agreement limit (default 0.2)
32
+ --cells <list> the cells to compare (default warm)
33
+ `,
34
+ },
35
+ };
36
+ export const BENCH_USAGE = groupUsage(BENCH_HELP);
37
+ const EXIT_FAILED = 1;
38
+ const EXIT_USAGE = 2;
39
+ const EXIT_REFUSED = 3;
40
+ function listOf(raw, all, flag) {
41
+ if (raw === undefined)
42
+ return [...all];
43
+ const picked = raw
44
+ .split(',')
45
+ .map(x => x.trim())
46
+ .filter(x => x !== '');
47
+ const unknown = picked.filter(x => !all.includes(x));
48
+ if (unknown.length > 0 || picked.length === 0)
49
+ throw new UsageError(`${flag} ${raw} names ${unknown.join(', ') || 'nothing'}`, `pick from ${all.join(',')}`);
50
+ return picked;
51
+ }
52
+ function positiveNumber(raw, flag, integer) {
53
+ const value = Number(raw);
54
+ if (!Number.isFinite(value) || value <= 0 || (integer && !Number.isInteger(value)))
55
+ throw new UsageError(`${flag} ${raw} is not a positive ${integer ? 'whole number' : 'number'}`, `pass ${flag} ${integer ? '16' : '8'}`);
56
+ return value;
57
+ }
58
+ function readResult(file) {
59
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
60
+ if (parsed.schema !== SCHEMA)
61
+ throw new UsageError(`${file} is not a bench result`, 'pass the .json next to a report');
62
+ return parsed;
63
+ }
64
+ function compare(args, deps) {
65
+ const { values, positionals } = parseArgs({
66
+ args,
67
+ strict: true,
68
+ allowPositionals: true,
69
+ options: { tolerance: { type: 'string', default: '0.2' }, cells: { type: 'string' } },
70
+ });
71
+ const [a, b, ...rest] = positionals;
72
+ if (a === undefined || b === undefined || rest.length > 0)
73
+ throw new UsageError('compare takes two result files', `${TOOL} bench compare <a.json> <b.json>`);
74
+ const tolerance = positiveNumber(values.tolerance, '--tolerance', false);
75
+ const cells = values.cells === undefined ? ['warm'] : listOf(values.cells, CELLS, '--cells');
76
+ const left = readResult(path.resolve(deps.cwd, a));
77
+ const right = readResult(path.resolve(deps.cwd, b));
78
+ const rows = compareRuns(left, right, tolerance, cells);
79
+ deps.stdout(renderAgreement(rows, left, right, tolerance));
80
+ return rows.length > 0 && rows.every(r => r.within) ? 0 : EXIT_FAILED;
81
+ }
82
+ async function bench(args, deps) {
83
+ if (args[0] === 'compare')
84
+ return compare(args.slice(1), deps);
85
+ const { values, positionals } = parseArgs({
86
+ args,
87
+ strict: true,
88
+ allowPositionals: true,
89
+ options: {
90
+ worktree: { type: 'string' },
91
+ pair: { type: 'string' },
92
+ platform: { type: 'string', default: 'ios' },
93
+ samples: { type: 'string', default: String(MIN_PUBLISHED_SAMPLES) },
94
+ cells: { type: 'string' },
95
+ ops: { type: 'string' },
96
+ 'max-load': { type: 'string' },
97
+ 'load-wait': { type: 'string', default: '300' },
98
+ 'no-rerun': { type: 'boolean', default: false },
99
+ 'no-setup': { type: 'boolean', default: false },
100
+ out: { type: 'string' },
101
+ },
102
+ });
103
+ if (positionals.length > 0)
104
+ throw new UsageError(`unexpected ${positionals.join(' ')}`, `${TOOL} bench --help`);
105
+ const platform = values.platform;
106
+ if (platform !== 'ios' && platform !== 'android' && platform !== 'web')
107
+ throw new UsageError(`--platform ${platform} is not a platform`, 'pass --platform ios, android or web');
108
+ const folders = [path.resolve(deps.cwd, values.worktree ?? '.')];
109
+ if (values.pair !== undefined)
110
+ folders.push(path.resolve(deps.cwd, values.pair));
111
+ const signal = { stopped: false };
112
+ const unhook = deps.onSignal?.(() => {
113
+ signal.stopped = true;
114
+ deps.stderr(`${TOOL} bench: stopping after the current sample; the lanes are released and a partial report written\n`);
115
+ });
116
+ try {
117
+ const { result, markdown, json } = await runBench({
118
+ platform,
119
+ folders,
120
+ out: values.out === undefined ? path.join(stateDir(deps.env), 'bench') : path.resolve(deps.cwd, values.out),
121
+ setup: !values['no-setup'],
122
+ command: [TOOL, ...deps.argv].join(' '),
123
+ samples: positiveNumber(values.samples, '--samples', true),
124
+ cells: values.cells === undefined ? [...PLATFORM_CELLS[platform]] : listOf(values.cells, CELLS, '--cells'),
125
+ ops: values.ops === undefined ? [...PLATFORM_OPS[platform]] : listOf(values.ops, OPS, '--ops'),
126
+ maxLoad: values['max-load'] === undefined ? os.cpus().length : positiveNumber(values['max-load'], '--max-load', false),
127
+ loadWaitMs: positiveNumber(values['load-wait'], '--load-wait', false) * 1000,
128
+ rerunFlagged: !values['no-rerun'],
129
+ }, {
130
+ env: deps.env,
131
+ processes: deps.processes,
132
+ log: line => {
133
+ deps.stderr(`${TOOL} bench: ${line}\n`);
134
+ },
135
+ stopped: () => signal.stopped,
136
+ });
137
+ deps.stdout(`${markdown}\n${json}\n`);
138
+ const broken = result.batches.filter(b => !b.superseded && (b.aborted !== undefined || b.series.some(s => s.failures > 0)));
139
+ return broken.length === 0 && !signal.stopped ? 0 : EXIT_FAILED;
140
+ }
141
+ finally {
142
+ unhook?.();
143
+ }
144
+ }
145
+ export async function runBenchCommand(command, args, deps) {
146
+ try {
147
+ if (command !== 'bench')
148
+ throw new UsageError(`'${command}' is not a bench command`, `run ${TOOL} --help`);
149
+ return await bench(args, deps);
150
+ }
151
+ catch (error) {
152
+ if (error instanceof TypeError && error.code?.startsWith('ERR_PARSE_ARGS')) {
153
+ deps.stderr(`${TOOL} ${command}: ${error.message}\n\n${helpOf(BENCH_HELP, command) ?? BENCH_USAGE}`);
154
+ return EXIT_USAGE;
155
+ }
156
+ if (error instanceof UsageError) {
157
+ deps.stderr(`${TOOL}: ${error.message}\n`);
158
+ return EXIT_USAGE;
159
+ }
160
+ if (error instanceof NotClaimed || error instanceof Refusal) {
161
+ deps.stderr(`${TOOL}: ${error.message}\n`);
162
+ return EXIT_REFUSED;
163
+ }
164
+ deps.stderr(`${TOOL} bench: ${error instanceof Error ? error.message : String(error)}\n`);
165
+ return EXIT_FAILED;
166
+ }
167
+ }