glitchless-playtest 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +76 -2
- package/bin/glitchless-playtest.js +63 -0
- package/package.json +49 -4
- package/src/compare.js +76 -0
- package/src/config.js +70 -0
- package/src/index.js +92 -0
- package/src/report.js +70 -0
- package/src/run.js +141 -0
- package/src/runs.js +33 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 The Glitchless authors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,77 @@
|
|
|
1
|
-
#
|
|
1
|
+
# glitchless-playtest
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Playtest every change. Autoplay bots play your web game on a saved baseline and on the current code,
|
|
4
|
+
and [Glitchless](https://github.com/glitchless-gg/glitchless) compares the two runs: slow frames,
|
|
5
|
+
render time, draw calls, hitches, errors, deaths and level completion. A regression exits with code 1,
|
|
6
|
+
so it can gate a pull request.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npx glitchless-playtest --save baseline # before changing the code
|
|
10
|
+
npx glitchless-playtest # after: compares with "baseline"
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## What it needs
|
|
14
|
+
|
|
15
|
+
- **Your game running**, by default at `http://localhost:5173/`, with the Glitchless SDK
|
|
16
|
+
([`glitchless`](https://www.npmjs.com/package/glitchless)) reporting to a Glitchless server.
|
|
17
|
+
- **An autoplay mode in the game.** Each scenario opens the game with URL parameters such as
|
|
18
|
+
`?autoplay=1&seed=7&skill=0.95&level=1`. A fixed seed makes the bot play the same way on both builds,
|
|
19
|
+
so the only thing that changes is the code. The bot's sessions should use `sessionType: 'synthetic'`,
|
|
20
|
+
so they stay out of player numbers.
|
|
21
|
+
- **A Glitchless server**, by default `$GLITCHLESS_URL` or `http://localhost:7777`.
|
|
22
|
+
- **Playwright** installed in the game project (`npm install -D playwright`). It uses your installed
|
|
23
|
+
Chrome by default, so frame times come from your real GPU.
|
|
24
|
+
|
|
25
|
+
A run ends after `max_s` seconds, or as soon as the page sets `window.__GLITCHLESS_PLAYTEST_DONE__ = true`.
|
|
26
|
+
|
|
27
|
+
## Options
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
--save NAME save this run as NAME (e.g. baseline)
|
|
31
|
+
--compare NAME compare with the saved run NAME (default: baseline, if saved)
|
|
32
|
+
--compare-only A B compare two saved runs without playing
|
|
33
|
+
--baseline-url URL play another running build as the baseline first (for CI)
|
|
34
|
+
--game URL game to play (default http://localhost:5173/)
|
|
35
|
+
--server URL Glitchless server (default $GLITCHLESS_URL or http://localhost:7777)
|
|
36
|
+
--service NAME game service name (default: read from the page)
|
|
37
|
+
--api-key KEY Glitchless API key (default $GLITCHLESS_API_KEY)
|
|
38
|
+
--quick play only the first scenario
|
|
39
|
+
--max SECONDS cap each run
|
|
40
|
+
--channel NAME browser: chrome (default) or chromium
|
|
41
|
+
--headed show the browser windows
|
|
42
|
+
--json print the full result as JSON instead of markdown
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Saved runs go in `.glitchless/playtest/` (add it to `.gitignore`).
|
|
46
|
+
|
|
47
|
+
## Configuration
|
|
48
|
+
|
|
49
|
+
A `glitchless.playtest.json` in the project root can set any default: `game`, `server`, `scenarios`,
|
|
50
|
+
`thresholds`, `done_when` (a JavaScript expression that ends a run when it's true), `viewport` and
|
|
51
|
+
`runs_dir`.
|
|
52
|
+
|
|
53
|
+
```json
|
|
54
|
+
{
|
|
55
|
+
"game": "http://localhost:3000/",
|
|
56
|
+
"scenarios": [
|
|
57
|
+
{ "name": "speedrun", "params": { "autoplay": 1, "seed": 3, "skill": 0.95 }, "max_s": 60 }
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
A metric only counts as worse when it's worse by both its relative and its absolute margin, so noise
|
|
63
|
+
on a fast machine doesn't fail a build.
|
|
64
|
+
|
|
65
|
+
## From code or an agent
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
import { playtest } from 'glitchless-playtest';
|
|
69
|
+
const result = await playtest({ saveAs: 'baseline' }); // later: playtest({ compareTo: 'baseline' })
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The [glitchless-mcp](https://www.npmjs.com/package/glitchless-mcp) server exposes the same thing to
|
|
73
|
+
coding agents as the `glitchless_playtest` tool.
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// glitchless-playtest: autoplay bots play your game, and Glitchless compares the result with a baseline.
|
|
3
|
+
//
|
|
4
|
+
// glitchless-playtest --save baseline # before changing the code
|
|
5
|
+
// glitchless-playtest # after: compares with "baseline", exits 1 on a regression
|
|
6
|
+
// glitchless-playtest --compare-only baseline latest
|
|
7
|
+
// glitchless-playtest --baseline-url http://localhost:5174/ # CI: main build vs this branch's build
|
|
8
|
+
//
|
|
9
|
+
// Needs the game and a Glitchless server running, and Playwright installed in the game project.
|
|
10
|
+
|
|
11
|
+
import { playtest, compareSaved } from '../src/index.js';
|
|
12
|
+
|
|
13
|
+
const HELP = `Usage: glitchless-playtest [options]
|
|
14
|
+
|
|
15
|
+
--save NAME save this run as NAME (e.g. baseline)
|
|
16
|
+
--compare NAME compare with the saved run NAME (default: baseline, if saved)
|
|
17
|
+
--compare-only A B compare two saved runs without playing
|
|
18
|
+
--baseline-url URL play another running build as the baseline first (for CI)
|
|
19
|
+
--game URL game to play (default http://localhost:5173/)
|
|
20
|
+
--server URL Glitchless server (default $GLITCHLESS_URL or http://localhost:7777)
|
|
21
|
+
--service NAME game service name (default: read from the page)
|
|
22
|
+
--api-key KEY Glitchless API key (default $GLITCHLESS_API_KEY)
|
|
23
|
+
--quick play only the first scenario
|
|
24
|
+
--max SECONDS cap each run
|
|
25
|
+
--channel NAME browser: chrome (default, uses your real GPU) or chromium
|
|
26
|
+
--headed show the browser windows
|
|
27
|
+
--json print the full result as JSON instead of markdown
|
|
28
|
+
|
|
29
|
+
Scenarios, thresholds and URLs can also be set in glitchless.playtest.json.
|
|
30
|
+
Exit code: 0 pass (or nothing to compare), 1 regression, 2 error.`;
|
|
31
|
+
|
|
32
|
+
const argv = process.argv.slice(2);
|
|
33
|
+
const has = (f) => argv.includes(`--${f}`);
|
|
34
|
+
const val = (f) => {
|
|
35
|
+
const i = argv.indexOf(`--${f}`);
|
|
36
|
+
return i >= 0 && argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[i + 1] : undefined;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
if (has('help') || has('h')) {
|
|
40
|
+
console.log(HELP);
|
|
41
|
+
process.exit(0);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const log = (msg) => process.stderr.write(`${msg}\n`);
|
|
45
|
+
const config = { game: val('game'), server: val('server'), service: val('service'), api_key: val('api-key'), channel: val('channel'), headed: has('headed') || undefined };
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
let result;
|
|
49
|
+
const only = argv.indexOf('--compare-only');
|
|
50
|
+
if (only >= 0) {
|
|
51
|
+
const [a, b] = argv.slice(only + 1, only + 3);
|
|
52
|
+
if (!a || !b) throw new Error('--compare-only needs two saved run names, e.g. --compare-only baseline latest');
|
|
53
|
+
result = compareSaved(a, b, { config });
|
|
54
|
+
} else {
|
|
55
|
+
result = await playtest({ saveAs: val('save'), compareTo: val('compare'), baselineUrl: val('baseline-url'), quick: has('quick'), maxSeconds: val('max') ? Number(val('max')) : undefined, config, log });
|
|
56
|
+
}
|
|
57
|
+
if (has('json')) console.log(JSON.stringify(result, null, 2));
|
|
58
|
+
else console.log(result.report);
|
|
59
|
+
process.exit(result.verdict === 'fail' ? 1 : 0);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
log(`glitchless-playtest: ${err.message}`);
|
|
62
|
+
process.exit(2);
|
|
63
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "glitchless-playtest",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Playtest every change: autoplay bots play your web game on the current code and on a saved baseline, and Glitchless flags what got slower or started breaking.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"gamedev",
|
|
7
|
+
"playtest",
|
|
8
|
+
"bots",
|
|
9
|
+
"performance",
|
|
10
|
+
"regression",
|
|
11
|
+
"playwright",
|
|
12
|
+
"threejs"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/glitchless-gg/glitchless/tree/main/packages/playtest#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/glitchless-gg/glitchless/issues"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/glitchless-gg/glitchless.git",
|
|
21
|
+
"directory": "packages/playtest"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"type": "module",
|
|
25
|
+
"main": "./src/index.js",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": "./src/index.js"
|
|
28
|
+
},
|
|
29
|
+
"bin": {
|
|
30
|
+
"glitchless-playtest": "bin/glitchless-playtest.js"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"bin",
|
|
34
|
+
"src"
|
|
35
|
+
],
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=20"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"test": "node --test test/*.test.js",
|
|
41
|
+
"prepublishOnly": "npm test"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"playwright": ">=1.40"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"playwright": {
|
|
48
|
+
"optional": true
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/compare.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Compares two playtest runs metric by metric. Every check reports one of:
|
|
2
|
+
// regression (fails the change), warning (reported, still passes), improvement, same.
|
|
3
|
+
|
|
4
|
+
import { DEFAULT_THRESHOLDS } from './config.js';
|
|
5
|
+
|
|
6
|
+
const OVERALL = ['pct_frames_over_budget', 'frame_p95', 'render_cpu_ms', 'draw_calls', 'hitches_per_min', 'errors_per_session', 'deaths_per_session', 'level_completion_pct', 'geometries_growth_per_level_load'];
|
|
7
|
+
const PER_LEVEL = ['pct_frames_over_budget', 'frame_p95', 'render_cpu_ms', 'draw_calls'];
|
|
8
|
+
|
|
9
|
+
export function judge(before, after, t) {
|
|
10
|
+
if (before == null || after == null || !t) return null;
|
|
11
|
+
const diff = after - before;
|
|
12
|
+
const changePct = before ? (diff / Math.abs(before)) * 100 : diff ? Infinity : 0;
|
|
13
|
+
// Worse or better only when the change clears BOTH margins.
|
|
14
|
+
const significant = Math.abs(diff) >= (t.abs ?? 0) && Math.abs(changePct) >= (t.pct ?? 0) && diff !== 0;
|
|
15
|
+
const worse = t.higher === false ? diff < 0 : diff > 0;
|
|
16
|
+
const status = !significant ? 'same' : !worse ? 'improvement' : t.severity === 'fail' ? 'regression' : 'warning';
|
|
17
|
+
return { before, after, change_pct: Number.isFinite(changePct) ? Math.round(changePct) : null, status };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function compareRuns(baseline, candidate, thresholds = DEFAULT_THRESHOLDS) {
|
|
21
|
+
const t = { ...DEFAULT_THRESHOLDS, ...thresholds };
|
|
22
|
+
const b = baseline.summary || {};
|
|
23
|
+
const c = candidate.summary || {};
|
|
24
|
+
const checks = [];
|
|
25
|
+
|
|
26
|
+
for (const key of OVERALL) {
|
|
27
|
+
const r = judge(b[key], c[key], t[key]);
|
|
28
|
+
if (r) checks.push({ id: key, label: t[key].label, scope: 'all levels', ...r });
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const levels = [...new Set([...Object.keys(b.levels || {}), ...Object.keys(c.levels || {})])].sort((x, y) => x.localeCompare(y, undefined, { numeric: true }));
|
|
32
|
+
for (const level of levels) {
|
|
33
|
+
const bl = b.levels?.[level];
|
|
34
|
+
const cl = c.levels?.[level];
|
|
35
|
+
if (bl && !cl) {
|
|
36
|
+
checks.push({ id: `level.reached.${level}`, label: 'Level reached', scope: level, before: 'yes', after: 'no', change_pct: null, status: 'warning' });
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!bl || !cl) continue;
|
|
40
|
+
for (const key of PER_LEVEL) {
|
|
41
|
+
const r = judge(bl[key], cl[key], t[`level.${key}`]);
|
|
42
|
+
if (r) checks.push({ id: `level.${key}.${level}`, label: t[`level.${key}`].label, scope: level, ...r });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const baseErrors = new Map((b.errors || []).map((e) => [e.fingerprint, e]));
|
|
47
|
+
const candErrors = new Map((c.errors || []).map((e) => [e.fingerprint, e]));
|
|
48
|
+
const newErrors = [...candErrors.values()].filter((e) => !baseErrors.has(e.fingerprint));
|
|
49
|
+
const fixedErrors = [...baseErrors.values()].filter((e) => !candErrors.has(e.fingerprint));
|
|
50
|
+
if (newErrors.length) checks.push({ id: 'new_errors', label: t.new_errors.label, scope: 'all levels', before: 0, after: newErrors.length, change_pct: null, status: t.new_errors.severity === 'fail' ? 'regression' : 'warning' });
|
|
51
|
+
if (fixedErrors.length) checks.push({ id: 'fixed_errors', label: 'Error types gone', scope: 'all levels', before: fixedErrors.length, after: 0, change_pct: null, status: 'improvement' });
|
|
52
|
+
|
|
53
|
+
const bc = b.crashes || 0;
|
|
54
|
+
const cc = c.crashes || 0;
|
|
55
|
+
if (cc !== bc) checks.push({ id: 'crashes', label: t.new_crashes.label, scope: 'all levels', before: bc, after: cc, change_pct: null, status: cc > bc ? (t.new_crashes.severity === 'fail' ? 'regression' : 'warning') : 'improvement' });
|
|
56
|
+
|
|
57
|
+
// Comparisons are only fair when the same bots played the same scenarios on the same machine.
|
|
58
|
+
const notes = [];
|
|
59
|
+
const sig = (run) => JSON.stringify((run.scenarios || []).map((s) => s.params));
|
|
60
|
+
if (sig(baseline) !== sig(candidate)) notes.push('The two runs used different scenarios, so differences may come from the bots rather than the code.');
|
|
61
|
+
if (baseline.machine?.gpu && candidate.machine?.gpu && baseline.machine.gpu !== candidate.machine.gpu) notes.push(`Different GPUs (${baseline.machine.gpu} vs ${candidate.machine.gpu}): frame times are not comparable across machines.`);
|
|
62
|
+
const capped = (candidate.scenarios || []).filter((s) => !s.finished).length;
|
|
63
|
+
if (capped) notes.push(`${capped} candidate run(s) hit the time cap before finishing.`);
|
|
64
|
+
|
|
65
|
+
const regressions = checks.filter((x) => x.status === 'regression');
|
|
66
|
+
return {
|
|
67
|
+
verdict: regressions.length ? 'fail' : 'pass',
|
|
68
|
+
regressions,
|
|
69
|
+
warnings: checks.filter((x) => x.status === 'warning'),
|
|
70
|
+
improvements: checks.filter((x) => x.status === 'improvement'),
|
|
71
|
+
checks,
|
|
72
|
+
new_errors: newErrors,
|
|
73
|
+
fixed_errors: fixedErrors,
|
|
74
|
+
notes,
|
|
75
|
+
};
|
|
76
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Playtest settings: defaults suit Zoomies, and a glitchless.playtest.json in the project root can
|
|
2
|
+
// override any of them (scenarios, thresholds, URLs, how to tell a run is finished).
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
// Each scenario is one autoplay run. Fixed seeds make the bot play the same way on both builds, so
|
|
8
|
+
// the only thing that changes between baseline and candidate is the code.
|
|
9
|
+
export const DEFAULT_SCENARIOS = [
|
|
10
|
+
{ name: 'expert from level 1', params: { autoplay: 1, seed: 7, skill: 0.95, level: 1 }, max_s: 90 },
|
|
11
|
+
{ name: 'average from level 1', params: { autoplay: 1, seed: 21, skill: 0.8, level: 1 }, max_s: 90 },
|
|
12
|
+
{ name: 'novice from level 2', params: { autoplay: 1, seed: 42, skill: 0.6, level: 2 }, max_s: 90 },
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
// A change regresses a metric only when it is worse by BOTH the relative and the absolute margin,
|
|
16
|
+
// so small numbers (0.3 → 0.4 ms) and noise on fast machines don't fail a build.
|
|
17
|
+
// higher: whether a higher value is worse (true) or better (false)
|
|
18
|
+
// severity: 'fail' blocks the change, 'warn' is reported but passes
|
|
19
|
+
// Frame time is judged on the share of slow frames. p95 is only a warning: with vsync, frame times
|
|
20
|
+
// cluster at 16.7 and 33.3 ms, so p95 flips between them when about 5% of frames are slow.
|
|
21
|
+
export const DEFAULT_THRESHOLDS = {
|
|
22
|
+
pct_frames_over_budget: { label: 'Slow frames (% over budget)', higher: true, pct: 50, abs: 2, severity: 'fail' },
|
|
23
|
+
frame_p95: { label: 'Frame time p95 (ms)', higher: true, pct: 15, abs: 2, severity: 'warn' },
|
|
24
|
+
render_cpu_ms: { label: 'Render CPU per frame (ms)', higher: true, pct: 30, abs: 1, severity: 'fail' },
|
|
25
|
+
draw_calls: { label: 'Draw calls per frame', higher: true, pct: 25, abs: 50, severity: 'fail' },
|
|
26
|
+
hitches_per_min: { label: 'Hitches per minute', higher: true, pct: 50, abs: 1, severity: 'warn' },
|
|
27
|
+
errors_per_session: { label: 'Errors per run', higher: true, pct: 50, abs: 1, severity: 'warn' },
|
|
28
|
+
deaths_per_session: { label: 'Deaths per run', higher: true, pct: 50, abs: 2, severity: 'warn' },
|
|
29
|
+
level_completion_pct: { label: 'Level completion (%)', higher: false, pct: 0, abs: 25, severity: 'warn' },
|
|
30
|
+
geometries_growth_per_level_load: { label: 'Geometry growth per level load', higher: true, pct: 50, abs: 200, severity: 'warn' },
|
|
31
|
+
// Per-level versions of the renderer metrics catch a regression the whole-run average dilutes.
|
|
32
|
+
'level.pct_frames_over_budget': { label: 'Slow frames (% over budget)', higher: true, pct: 50, abs: 2, severity: 'fail' },
|
|
33
|
+
'level.frame_p95': { label: 'Frame time p95 (ms)', higher: true, pct: 15, abs: 2, severity: 'warn' },
|
|
34
|
+
'level.render_cpu_ms': { label: 'Render CPU per frame (ms)', higher: true, pct: 30, abs: 1, severity: 'fail' },
|
|
35
|
+
'level.draw_calls': { label: 'Draw calls per frame', higher: true, pct: 25, abs: 50, severity: 'fail' },
|
|
36
|
+
new_errors: { label: 'New error types', severity: 'fail' },
|
|
37
|
+
new_crashes: { label: 'Crashed runs', severity: 'fail' },
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const DEFAULTS = {
|
|
41
|
+
game: 'http://localhost:5173/',
|
|
42
|
+
server: process.env.GLITCHLESS_URL || 'http://localhost:7777',
|
|
43
|
+
service: process.env.GLITCHLESS_SERVICE || null,
|
|
44
|
+
api_key: process.env.GLITCHLESS_API_KEY || null,
|
|
45
|
+
channel: 'chrome',
|
|
46
|
+
env: 'playtest',
|
|
47
|
+
// JS expression evaluated in the page; the run ends early once it is truthy.
|
|
48
|
+
done_when: 'window.__GLITCHLESS_PLAYTEST_DONE__ || window.zoomies?.halted || window.zoomies?.won || window.zoomies?.quit',
|
|
49
|
+
viewport: { width: 1280, height: 720 },
|
|
50
|
+
runs_dir: '.glitchless/playtest',
|
|
51
|
+
scenarios: DEFAULT_SCENARIOS,
|
|
52
|
+
thresholds: DEFAULT_THRESHOLDS,
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export function loadConfig(cwd = process.cwd(), overrides = {}) {
|
|
56
|
+
const file = path.join(cwd, 'glitchless.playtest.json');
|
|
57
|
+
let fromFile = {};
|
|
58
|
+
if (fs.existsSync(file)) {
|
|
59
|
+
try {
|
|
60
|
+
fromFile = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
61
|
+
} catch (err) {
|
|
62
|
+
throw new Error(`glitchless.playtest.json is not valid JSON: ${err.message}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const clean = Object.fromEntries(Object.entries(overrides).filter(([, v]) => v != null));
|
|
66
|
+
const cfg = { ...DEFAULTS, ...fromFile, ...clean };
|
|
67
|
+
cfg.thresholds = { ...DEFAULT_THRESHOLDS, ...(fromFile.thresholds || {}) };
|
|
68
|
+
cfg.runs_dir = path.resolve(cwd, cfg.runs_dir);
|
|
69
|
+
return cfg;
|
|
70
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// Glitchless playtest: autoplay bots play the game on the current code, and the result is compared with
|
|
2
|
+
// a saved baseline. Used by the glitchless-playtest CLI and the glitchless_playtest MCP tool.
|
|
3
|
+
//
|
|
4
|
+
// await playtest({ saveAs: 'baseline' }) // before a change
|
|
5
|
+
// await playtest({ compareTo: 'baseline' }) // after it → { verdict, report, ... }
|
|
6
|
+
|
|
7
|
+
import { loadConfig } from './config.js';
|
|
8
|
+
import { playtestRun, fetchSummary } from './run.js';
|
|
9
|
+
import { compareRuns } from './compare.js';
|
|
10
|
+
import { comparisonReport, runReport } from './report.js';
|
|
11
|
+
import { saveRun, loadRun, listRuns } from './runs.js';
|
|
12
|
+
|
|
13
|
+
export { loadConfig, DEFAULT_SCENARIOS, DEFAULT_THRESHOLDS } from './config.js';
|
|
14
|
+
export { compareRuns, judge } from './compare.js';
|
|
15
|
+
export { comparisonReport, runReport } from './report.js';
|
|
16
|
+
export { saveRun, loadRun, listRuns } from './runs.js';
|
|
17
|
+
export { playtestRun, loadPlaywright } from './run.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} o
|
|
21
|
+
* @param {string} [o.saveAs] save this run under a name (e.g. "baseline")
|
|
22
|
+
* @param {string} [o.compareTo] compare with a saved run (default "baseline" when it exists and we're not saving over it)
|
|
23
|
+
* @param {string} [o.baselineUrl] play a baseline against another running build first, then compare
|
|
24
|
+
* @param {boolean} [o.quick] first scenario only
|
|
25
|
+
* @param {number} [o.maxSeconds] cap each run
|
|
26
|
+
* @param {object} [o.config] overrides for glitchless.playtest.json / defaults (game, server, service, channel, headed, api_key)
|
|
27
|
+
* @param {(msg: string) => void} [o.log]
|
|
28
|
+
*/
|
|
29
|
+
export async function playtest({ saveAs, compareTo, baselineUrl, quick = false, maxSeconds, config = {}, cwd = process.cwd(), log = () => {} } = {}) {
|
|
30
|
+
const cfg = loadConfig(cwd, config);
|
|
31
|
+
let scenarios = quick ? cfg.scenarios.slice(0, 1) : cfg.scenarios;
|
|
32
|
+
if (maxSeconds) scenarios = scenarios.map((s) => ({ ...s, max_s: maxSeconds }));
|
|
33
|
+
|
|
34
|
+
let baseline = null;
|
|
35
|
+
if (baselineUrl) {
|
|
36
|
+
log(`Baseline: playing ${baselineUrl}`);
|
|
37
|
+
baseline = { ...(await playtestRun(cfg, { game: baselineUrl, scenarios, log })), name: 'baseline-url' };
|
|
38
|
+
} else {
|
|
39
|
+
const target = compareTo ?? (saveAs === 'baseline' ? null : 'baseline');
|
|
40
|
+
if (target) {
|
|
41
|
+
baseline = loadRun(cfg.runs_dir, target);
|
|
42
|
+
if (!baseline && compareTo) throw new Error(`No saved playtest run named "${compareTo}" in ${cfg.runs_dir}. Saved runs: ${listRuns(cfg.runs_dir).join(', ') || 'none'}. Save one first with --save ${compareTo}.`);
|
|
43
|
+
if (baseline?.scenarios && !quick && baseline.scenarios.length === 1 && scenarios.length > 1) {
|
|
44
|
+
scenarios = scenarios.slice(0, 1); // the baseline was a quick run; play the same scenario
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
log(`Candidate: playing ${cfg.game}`);
|
|
50
|
+
const candidate = await playtestRun(cfg, { scenarios, log });
|
|
51
|
+
const files = { latest: saveRun(cfg.runs_dir, 'latest', candidate) };
|
|
52
|
+
if (saveAs) files[saveAs] = saveRun(cfg.runs_dir, saveAs, candidate);
|
|
53
|
+
candidate.name = saveAs || 'latest';
|
|
54
|
+
|
|
55
|
+
if (!baseline) {
|
|
56
|
+
const report = `${runReport(candidate)}\n\n${saveAs ? `Saved as \`${saveAs}\`.` : 'No baseline to compare with. Save one before changing the code with `--save baseline`.'}`;
|
|
57
|
+
return { verdict: 'none', report, candidate, files };
|
|
58
|
+
}
|
|
59
|
+
baseline = await matchingBaseline(cfg, baseline, candidate, log);
|
|
60
|
+
const comparison = compareRuns(baseline, candidate, cfg.thresholds);
|
|
61
|
+
return { verdict: comparison.verdict, report: comparisonReport(baseline, candidate, comparison), comparison, baseline, candidate, files };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// A quick run plays fewer scenarios than a full baseline. Comparing it with the baseline's totals
|
|
65
|
+
// would mix in runs the candidate never played, so ask the server for just the matching baseline
|
|
66
|
+
// sessions. If the server no longer has them, keep the full baseline (compareRuns notes the mismatch).
|
|
67
|
+
async function matchingBaseline(cfg, baseline, candidate, log) {
|
|
68
|
+
const key = (s) => JSON.stringify(s.params);
|
|
69
|
+
const wanted = new Set((candidate.scenarios || []).map(key));
|
|
70
|
+
const have = baseline.scenarios || [];
|
|
71
|
+
const subset = have.filter((s) => wanted.has(key(s)) && s.session_id);
|
|
72
|
+
if (subset.length === have.length || subset.length !== wanted.size) return baseline;
|
|
73
|
+
try {
|
|
74
|
+
const created = Date.parse(baseline.created);
|
|
75
|
+
log(`Comparing with the ${subset.length} matching baseline run(s) only`);
|
|
76
|
+
const summary = await fetchSummary(cfg, baseline.service, subset.map((s) => s.session_id), created - 2 * 3600e3, { log, timeoutMs: 0 });
|
|
77
|
+
if (!summary?.sessions) return baseline;
|
|
78
|
+
return { ...baseline, scenarios: subset, summary, name: `${baseline.name} (matching runs)` };
|
|
79
|
+
} catch {
|
|
80
|
+
return baseline;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Compare two saved runs without playing anything.
|
|
85
|
+
export function compareSaved(a, b, { cwd = process.cwd(), config = {} } = {}) {
|
|
86
|
+
const cfg = loadConfig(cwd, config);
|
|
87
|
+
const baseline = loadRun(cfg.runs_dir, a);
|
|
88
|
+
const candidate = loadRun(cfg.runs_dir, b);
|
|
89
|
+
if (!baseline || !candidate) throw new Error(`Saved runs needed: ${[!baseline && a, !candidate && b].filter(Boolean).join(', ')} not found in ${cfg.runs_dir}.`);
|
|
90
|
+
const comparison = compareRuns(baseline, candidate, cfg.thresholds);
|
|
91
|
+
return { verdict: comparison.verdict, report: comparisonReport(baseline, candidate, comparison), comparison, baseline, candidate };
|
|
92
|
+
}
|
package/src/report.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Markdown reports for a terminal, an agent, or a pull-request comment.
|
|
2
|
+
|
|
3
|
+
const fmt = (v) => (v == null ? '–' : typeof v === 'number' ? (Number.isInteger(v) ? v.toLocaleString('en-US') : v.toLocaleString('en-US', { maximumFractionDigits: 2 })) : String(v));
|
|
4
|
+
const change = (c) => (c.change_pct == null ? '' : `${c.change_pct > 0 ? '+' : ''}${c.change_pct}%`);
|
|
5
|
+
const runs = (n) => `${n} autoplay run${n === 1 ? '' : 's'}`;
|
|
6
|
+
const where = (c) => (c.scope === 'all levels' ? c.label : `${c.label}, ${c.scope}`);
|
|
7
|
+
|
|
8
|
+
function describeRun(run) {
|
|
9
|
+
const git = run.git ? `${run.git.sha}${run.git.dirty ? ' + uncommitted changes' : ''}` : 'no git info';
|
|
10
|
+
return `\`${run.name || 'this run'}\` (${git}, ${run.created?.slice(0, 16).replace('T', ' ')} UTC)`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function table(rows) {
|
|
14
|
+
if (!rows.length) return '';
|
|
15
|
+
return ['| Metric | Baseline | Candidate | Change |', '| --- | ---: | ---: | ---: |', ...rows.map((c) => `| ${where(c)} | ${fmt(c.before)} | ${fmt(c.after)} | ${change(c)} |`)].join('\n');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function comparisonReport(baseline, candidate, cmp) {
|
|
19
|
+
const out = [];
|
|
20
|
+
const n = cmp.regressions.length;
|
|
21
|
+
out.push(`## Glitchless playtest: ${cmp.verdict === 'fail' ? `FAIL, ${n} regression${n === 1 ? '' : 's'}` : 'PASS'}`);
|
|
22
|
+
out.push('');
|
|
23
|
+
out.push(`Baseline ${describeRun(baseline)} vs candidate ${describeRun(candidate)}.`);
|
|
24
|
+
const m = candidate.machine || {};
|
|
25
|
+
out.push(`${runs((candidate.scenarios || []).length)} each · ${candidate.service} · ${[m.browser, m.gpu].filter(Boolean).join(' · ')}`);
|
|
26
|
+
for (const note of cmp.notes) out.push(`\n> ${note}`);
|
|
27
|
+
if (n) out.push('', '### Regressions', '', table(cmp.regressions));
|
|
28
|
+
if (cmp.new_errors.length) {
|
|
29
|
+
out.push('', '### New errors', '');
|
|
30
|
+
for (const e of cmp.new_errors) out.push(`- \`${e.message}\` at ${e.location || 'unknown location'}: ${e.count}× in ${e.sessions} run(s) (fingerprint \`${e.fingerprint}\`)`);
|
|
31
|
+
}
|
|
32
|
+
if (cmp.warnings.length) out.push('', '### Warnings', '', table(cmp.warnings));
|
|
33
|
+
if (cmp.improvements.length) out.push('', '### Improvements', '', table(cmp.improvements));
|
|
34
|
+
if (cmp.fixed_errors.length) {
|
|
35
|
+
out.push('', '### Errors that no longer happen', '');
|
|
36
|
+
for (const e of cmp.fixed_errors) out.push(`- \`${e.message}\` at ${e.location || 'unknown location'}`);
|
|
37
|
+
}
|
|
38
|
+
const same = cmp.checks.filter((c) => c.status === 'same');
|
|
39
|
+
if (same.length) out.push('', '<details><summary>Unchanged metrics</summary>', '', table(same), '', '</details>');
|
|
40
|
+
return out.join('\n');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function runReport(run) {
|
|
44
|
+
const s = run.summary || {};
|
|
45
|
+
const out = [`## Glitchless playtest run ${describeRun(run)}`, ''];
|
|
46
|
+
out.push(`${runs((run.scenarios || []).length)} · ${run.service} · ${[run.machine?.browser, run.machine?.gpu].filter(Boolean).join(' · ')}`, '');
|
|
47
|
+
out.push('| Metric | Value |', '| --- | ---: |');
|
|
48
|
+
const rows = [
|
|
49
|
+
['Slow frames (% over budget)', s.pct_frames_over_budget],
|
|
50
|
+
['Frame time p95 (ms)', s.frame_p95],
|
|
51
|
+
['Render CPU per frame (ms)', s.render_cpu_ms],
|
|
52
|
+
['Draw calls per frame', s.draw_calls],
|
|
53
|
+
['Hitches per minute', s.hitches_per_min],
|
|
54
|
+
['Errors per run', s.errors_per_session],
|
|
55
|
+
['Crashed runs', s.crashes],
|
|
56
|
+
['Deaths per run', s.deaths_per_session],
|
|
57
|
+
['Level completion (%)', s.level_completion_pct],
|
|
58
|
+
];
|
|
59
|
+
for (const [k, v] of rows) out.push(`| ${k} | ${fmt(v)} |`);
|
|
60
|
+
const levels = Object.entries(s.levels || {});
|
|
61
|
+
if (levels.length) {
|
|
62
|
+
out.push('', '| Level | Slow frames (%) | Frame p95 (ms) | Draw calls | Render CPU (ms) |', '| --- | ---: | ---: | ---: | ---: |');
|
|
63
|
+
for (const [l, v] of levels) out.push(`| ${l} | ${fmt(v.pct_frames_over_budget)} | ${fmt(v.frame_p95)} | ${fmt(v.draw_calls)} | ${fmt(v.render_cpu_ms)} |`);
|
|
64
|
+
}
|
|
65
|
+
if (s.errors?.length) {
|
|
66
|
+
out.push('', 'Errors:');
|
|
67
|
+
for (const e of s.errors) out.push(`- \`${e.message}\` at ${e.location || 'unknown location'}: ${e.count}×`);
|
|
68
|
+
}
|
|
69
|
+
return out.join('\n');
|
|
70
|
+
}
|
package/src/run.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Plays the configured scenarios in real Chrome with the game's autoplay bot, one at a time, then
|
|
2
|
+
// asks the Glitchless server for one summary of exactly the sessions this run produced.
|
|
3
|
+
// Bots run sequentially on purpose: parallel browsers fight over the GPU and wreck frame times.
|
|
4
|
+
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { createRequire } from 'node:module';
|
|
9
|
+
import { pathToFileURL } from 'node:url';
|
|
10
|
+
|
|
11
|
+
// Real GPU (Metal via ANGLE on macOS) and no background throttling, same as scripts/bots.js.
|
|
12
|
+
const CHROME_ARGS = ['--use-angle=metal', '--enable-gpu', '--ignore-gpu-blocklist', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'];
|
|
13
|
+
|
|
14
|
+
// Resolve Playwright from the game project first (where people install it), then from here.
|
|
15
|
+
export async function loadPlaywright(cwd = process.cwd()) {
|
|
16
|
+
// Loaded by path, Playwright's CommonJS entry arrives wrapped in `default`.
|
|
17
|
+
const unwrap = (mod) => (mod?.chromium ? mod : mod?.default);
|
|
18
|
+
try {
|
|
19
|
+
const req = createRequire(path.join(cwd, 'noop.js'));
|
|
20
|
+
const pw = unwrap(await import(pathToFileURL(req.resolve('playwright')).href));
|
|
21
|
+
if (pw?.chromium) return pw;
|
|
22
|
+
} catch {}
|
|
23
|
+
try {
|
|
24
|
+
const pw = unwrap(await import('playwright'));
|
|
25
|
+
if (pw?.chromium) return pw;
|
|
26
|
+
throw new Error('no chromium export');
|
|
27
|
+
} catch {
|
|
28
|
+
throw new Error('Glitchless playtest needs Playwright to drive the browser. In your game project run: npm install -D playwright && npx playwright install chromium');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function runScenarios(cfg, { scenarios = cfg.scenarios, game = cfg.game, log = () => {} } = {}) {
|
|
33
|
+
const { chromium } = await loadPlaywright();
|
|
34
|
+
const channel = cfg.channel === 'chromium' ? undefined : cfg.channel;
|
|
35
|
+
const browser = await chromium.launch({ headless: !cfg.headed, channel, args: CHROME_ARGS }).catch(async (err) => {
|
|
36
|
+
if (!channel) throw err;
|
|
37
|
+
log(`Could not launch ${channel} (${err.message.split('\n')[0]}); falling back to Playwright's Chromium.`);
|
|
38
|
+
return chromium.launch({ headless: !cfg.headed, args: CHROME_ARGS });
|
|
39
|
+
});
|
|
40
|
+
const started = Date.now();
|
|
41
|
+
const results = [];
|
|
42
|
+
let service = cfg.service;
|
|
43
|
+
try {
|
|
44
|
+
for (const [i, sc] of scenarios.entries()) {
|
|
45
|
+
const qs = new URLSearchParams({ mute: '1', env: cfg.env, intake: cfg.server.replace(/\/$/, ''), ...Object.fromEntries(Object.entries(sc.params || {}).map(([k, v]) => [k, String(v)])) });
|
|
46
|
+
const url = `${game}${game.includes('?') ? '&' : '?'}${qs}`;
|
|
47
|
+
const ctx = await browser.newContext({ viewport: cfg.viewport });
|
|
48
|
+
const page = await ctx.newPage();
|
|
49
|
+
const t0 = Date.now();
|
|
50
|
+
log(`run ${i + 1}/${scenarios.length}: ${sc.name || JSON.stringify(sc.params)} …`);
|
|
51
|
+
await page.goto(url, { waitUntil: 'load' });
|
|
52
|
+
const ready = await page.waitForFunction(() => window.__GLITCHLESS__?.sessionId, null, { timeout: 20_000 }).catch(() => null);
|
|
53
|
+
if (!ready) {
|
|
54
|
+
await ctx.close();
|
|
55
|
+
throw new Error(`Glitchless never started on ${url}. Is the game running, and does it call Glitchless.init()?`);
|
|
56
|
+
}
|
|
57
|
+
const maxMs = (sc.max_s || 90) * 1000;
|
|
58
|
+
let finished = false;
|
|
59
|
+
while (Date.now() - t0 < maxMs) {
|
|
60
|
+
await page.waitForTimeout(1000);
|
|
61
|
+
finished = await page.evaluate((expr) => !!new Function(`return (${expr})`)(), cfg.done_when).catch(() => true);
|
|
62
|
+
if (finished) break;
|
|
63
|
+
}
|
|
64
|
+
const info = await page.evaluate(() => ({
|
|
65
|
+
session: window.__GLITCHLESS__?.sessionId,
|
|
66
|
+
service: window.__GLITCHLESS__?.opts?.service,
|
|
67
|
+
version: window.__GLITCHLESS__?.opts?.version,
|
|
68
|
+
sent: window.__GLITCHLESS__?.stats?.sent,
|
|
69
|
+
failed: window.__GLITCHLESS__?.stats?.failed,
|
|
70
|
+
}));
|
|
71
|
+
// Ending the page makes the SDK send session_end and flush whatever is still queued.
|
|
72
|
+
await page.evaluate(() => window.dispatchEvent(new Event('pagehide'))).catch(() => {});
|
|
73
|
+
await page.waitForTimeout(1000);
|
|
74
|
+
await ctx.close();
|
|
75
|
+
service ||= info.service;
|
|
76
|
+
const seconds = Math.round((Date.now() - t0) / 1000);
|
|
77
|
+
results.push({ scenario: sc.name || null, params: sc.params, session_id: info.session, game_version: info.version, seconds, finished, events_failed: info.failed || 0 });
|
|
78
|
+
log(` → ${info.session} · ${seconds}s${finished ? '' : ' (hit the time cap)'}${info.failed ? ` · ${info.failed} events failed to send` : ''}`);
|
|
79
|
+
}
|
|
80
|
+
} finally {
|
|
81
|
+
await browser.close();
|
|
82
|
+
}
|
|
83
|
+
return { started, service, results };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// The SDK sends on a timer and on pagehide, so give the server a moment to have every session.
|
|
87
|
+
export async function fetchSummary(cfg, service, sessionIds, started, { log = () => {}, timeoutMs = 20_000 } = {}) {
|
|
88
|
+
const base = cfg.server.replace(/\/$/, '');
|
|
89
|
+
const qs = new URLSearchParams({ service, sessions: sessionIds.join(','), from: String(started - 60_000), to: String(Date.now() + 60_000) });
|
|
90
|
+
const headers = { 'x-glitchless-client': 'playtest', ...(cfg.api_key ? { 'x-glitchless-api-key': cfg.api_key } : {}) };
|
|
91
|
+
const deadline = Date.now() + timeoutMs;
|
|
92
|
+
let last;
|
|
93
|
+
while (true) {
|
|
94
|
+
const res = await fetch(`${base}/v1/query/playtest?${qs}`, { headers });
|
|
95
|
+
if (!res.ok) throw new Error(`Glitchless server ${base} answered HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
|
|
96
|
+
const body = await res.json();
|
|
97
|
+
if (body.error) throw new Error(`Glitchless server: ${body.error}`);
|
|
98
|
+
last = body.summary;
|
|
99
|
+
const seen = new Set((last?.runs || []).filter((r) => r.ended).map((r) => r.session_id));
|
|
100
|
+
if (sessionIds.every((id) => seen.has(id))) return last;
|
|
101
|
+
if (Date.now() > deadline) {
|
|
102
|
+
log(` ${sessionIds.filter((id) => !seen.has(id)).length} session(s) never reported an end; using what arrived.`);
|
|
103
|
+
return last;
|
|
104
|
+
}
|
|
105
|
+
await new Promise((r) => setTimeout(r, 1500));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function gitInfo(cwd = process.cwd()) {
|
|
110
|
+
try {
|
|
111
|
+
const sha = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
|
|
112
|
+
const dirty = execFileSync('git', ['status', '--porcelain'], { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim().length > 0;
|
|
113
|
+
return { sha, dirty };
|
|
114
|
+
} catch {
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function machineInfo(summary, channel) {
|
|
120
|
+
const gpu = summary?.runs?.find((r) => r.gpu)?.gpu || null;
|
|
121
|
+
return { os: `${os.type()} ${os.release()}`, cpu: os.cpus()[0]?.model || null, gpu, browser: summary?.runs?.find((r) => r.browser)?.browser || channel };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Play every scenario and return a run record ready to save or compare.
|
|
125
|
+
export async function playtestRun(cfg, { game = cfg.game, scenarios = cfg.scenarios, log = () => {} } = {}) {
|
|
126
|
+
const { started, service, results } = await runScenarios(cfg, { game, scenarios, log });
|
|
127
|
+
if (!service) throw new Error('Could not tell which game this is. Pass --service or set "service" in glitchless.playtest.json.');
|
|
128
|
+
const ids = results.map((r) => r.session_id).filter(Boolean);
|
|
129
|
+
log(`collecting results for ${ids.length} session(s) from ${cfg.server} …`);
|
|
130
|
+
const summary = await fetchSummary(cfg, service, ids, started, { log });
|
|
131
|
+
return {
|
|
132
|
+
created: new Date().toISOString(),
|
|
133
|
+
game,
|
|
134
|
+
server: cfg.server,
|
|
135
|
+
service,
|
|
136
|
+
git: gitInfo(),
|
|
137
|
+
machine: machineInfo(summary, cfg.channel),
|
|
138
|
+
scenarios: results,
|
|
139
|
+
summary,
|
|
140
|
+
};
|
|
141
|
+
}
|
package/src/runs.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Saved playtest runs live in .glitchless/playtest/<name>.json so a baseline can be compared later,
|
|
2
|
+
// by a person, an agent or CI.
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const NAME = /^[A-Za-z0-9._-]{1,64}$/;
|
|
8
|
+
|
|
9
|
+
export function runPath(dir, name) {
|
|
10
|
+
if (!NAME.test(name)) throw new Error(`Run name "${name}" must be 1–64 letters, digits, dots, dashes or underscores.`);
|
|
11
|
+
return path.join(dir, `${name}.json`);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function saveRun(dir, name, run) {
|
|
15
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
16
|
+
const file = runPath(dir, name);
|
|
17
|
+
fs.writeFileSync(file, JSON.stringify({ ...run, name }, null, 2));
|
|
18
|
+
return file;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function loadRun(dir, nameOrFile) {
|
|
22
|
+
const file = nameOrFile.endsWith('.json') ? path.resolve(nameOrFile) : runPath(dir, nameOrFile);
|
|
23
|
+
if (!fs.existsSync(file)) return null;
|
|
24
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function listRuns(dir) {
|
|
28
|
+
if (!fs.existsSync(dir)) return [];
|
|
29
|
+
return fs
|
|
30
|
+
.readdirSync(dir)
|
|
31
|
+
.filter((f) => f.endsWith('.json'))
|
|
32
|
+
.map((f) => f.slice(0, -5));
|
|
33
|
+
}
|