@yandy-r/ycc-opencode 6.4.0 → 6.6.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/README.md +11 -4
- package/agents/code-finder.md +1 -1
- package/agents/planner.md +1 -2
- package/agents/pr-evidence-collector.md +99 -0
- package/agents/root-cause-analyzer.md +1 -1
- package/index.js +9 -0
- package/package.json +1 -1
- package/registration.json +67 -0
- package/shared/references/branching-model.md +2 -1
- package/shared/references/standalone-dispatch.md +4 -1
- package/shared/references/target-capability-matrix.md +170 -30
- package/shared/references/worktree-strategy.md +9 -31
- package/shared/scripts/lib/ci-classify.sh +2 -2
- package/shared/scripts/release-feature-sets.sh +18 -0
- package/shared/scripts/release_feature_sets.py +232 -0
- package/shared/scripts/setup-worktree.sh +2 -69
- package/skills/bundle-author/references/surface-map.md +1 -1
- package/skills/bundle-author/references/when-not-to-scaffold.md +1 -1
- package/skills/bundle-author/scripts/scaffold-skill.sh +9 -0
- package/skills/bundle-release/SKILL.md +22 -5
- package/skills/bundle-release/references/release-checklist.md +9 -1
- package/skills/bundle-release/references/version-policy.md +11 -4
- package/skills/bundle-release/scripts/release_versions.py +19 -1
- package/skills/code-report/SKILL.md +0 -2
- package/skills/code-report/templates/report-structure.md +0 -2
- package/skills/compatibility-audit/SKILL.md +8 -4
- package/skills/compatibility-audit/scripts/audit-install-assumptions.sh +75 -5
- package/skills/compatibility-audit/scripts/audit-target-features.sh +15 -9
- package/skills/feature-research/SKILL.md +1 -1
- package/skills/feature-research/scripts/validate-spec.sh +0 -4
- package/skills/formatters/SKILL.md +2 -1
- package/skills/formatters/references/flag-reference.md +8 -4
- package/skills/formatters/references/templates/lint-autofix.yml.tmpl +189 -23
- package/skills/formatters/references/templates/lint.yml.tmpl +11 -11
- package/skills/formatters/references/templates/readme-section.md.tmpl +1 -1
- package/skills/formatters/scripts/bundle/go-tools.sh +73 -41
- package/skills/formatters/scripts/bundle/init-formatters.sh +1 -1
- package/skills/formatters/scripts/bundle/lib/modified-files.sh +0 -5
- package/skills/formatters/scripts/bundle/style.sh +2 -2
- package/skills/git-cleanup/SKILL.md +4 -5
- package/skills/git-workflow/SKILL.md +1 -0
- package/skills/git-workflow/templates/agent-prompts.md +5 -6
- package/skills/git-workflow/templates/documentation-decision.md +1 -3
- package/skills/git-workflow/templates/pr-template.md +1 -3
- package/skills/go-patterns/references/design-and-tooling.md +16 -13
- package/skills/go-testing/references/advanced-testing.md +2 -2
- package/skills/implement-plan/references/agent-task-prompt.md +18 -20
- package/skills/implement-plan/scripts/parse-dependencies.sh +3 -9
- package/skills/init/references/conventional-commits.md +8 -1
- package/skills/init/references/template-library.md +1 -1
- package/skills/init/templates/git/gitignore.tmpl +2 -0
- package/skills/init/templates/git/gitmessage.tmpl +2 -1
- package/skills/init/templates/github/workflows/pr-title.yml.tmpl +1 -1
- package/skills/orchestrate/SKILL.md +1 -1
- package/skills/orchestrate/references/dispatch-playbook.md +1 -1
- package/skills/parallel-plan/SKILL.md +6 -10
- package/skills/plan-workflow/SKILL.md +3 -3
- package/skills/plan-workflow/references/plan-structure.md +1 -3
- package/skills/plan-workflow/scripts/validate-workflow-plan.sh +2 -8
- package/skills/pr-evidence/SKILL.md +138 -0
- package/skills/pr-evidence/references/perf-evidence.md +119 -0
- package/skills/pr-evidence/references/pr-body-and-hosting.md +112 -0
- package/skills/pr-evidence/references/ui-evidence.md +152 -0
- package/skills/pr-evidence/scripts/bench_report.py +331 -0
- package/skills/pr-evidence/scripts/capture-ui.mjs +311 -0
- package/skills/pr-evidence/scripts/classify-change.sh +135 -0
- package/skills/prp-plan/SKILL.md +4 -5
- package/skills/prp-plan/scripts/validate-prp-plan.sh +1 -11
- package/skills/prp-pr/SKILL.md +4 -0
- package/skills/release-model/templates/RELEASING.md.tmpl +2 -1
- package/skills/releaser/SKILL.md +5 -1
- package/skills/releaser/references/ci-optimization-checklist.md +1 -1
- package/skills/releaser/references/ci-templates/docker-release.yml +8 -8
- package/skills/releaser/references/ci-templates/generic-release.yml +5 -5
- package/skills/releaser/references/ci-templates/go-release.yml +4 -4
- package/skills/releaser/references/ci-templates/node-release.yml +8 -8
- package/skills/releaser/references/ci-templates/python-release.yml +8 -8
- package/skills/releaser/references/ci-templates/rust-release.yml +10 -10
- package/skills/releaser/references/release-preparation.md +34 -15
- package/skills/rust-testing/references/advanced-testing.md +1 -1
- package/skills/shared-context/SKILL.md +6 -10
- package/skills/ts-testing/references/advanced-testing.md +4 -4
- package/skills/visual-recap/SKILL.md +3 -4
- package/shared/scripts/merge-children.sh +0 -82
- package/skills/write-docs/templates/docs-readme.md +0 -34
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Compare base vs head benchmark samples and render PR evidence.
|
|
3
|
+
|
|
4
|
+
Reads benchmark samples, computes per-benchmark statistics, a bootstrap 95%
|
|
5
|
+
confidence interval for the change, and a verdict (improved / regressed /
|
|
6
|
+
no change / noisy). Writes a Markdown table, a JSON summary and an SVG chart
|
|
7
|
+
that shows what improved and what regressed. Standard library only.
|
|
8
|
+
|
|
9
|
+
Inputs (repeatable, mixable):
|
|
10
|
+
--hyperfine FILE hyperfine --export-json output. Commands must be named
|
|
11
|
+
"base:<bench>" and "head:<bench>" (hyperfine -n).
|
|
12
|
+
--samples FILE JSON: {"benchmarks": [{"name": str, "unit": str,
|
|
13
|
+
"lower_is_better": bool, "base": [float], "head": [float]}]}
|
|
14
|
+
|
|
15
|
+
Outputs:
|
|
16
|
+
--md FILE Markdown table (default: stdout)
|
|
17
|
+
--json FILE machine-readable summary
|
|
18
|
+
--svg FILE chart (render to PNG with capture-ui.mjs render)
|
|
19
|
+
--noise-floor PCT smallest change treated as real (default 2.0)
|
|
20
|
+
|
|
21
|
+
Exit codes: 0 success, 1 usage or input error.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import json
|
|
28
|
+
import random
|
|
29
|
+
import statistics
|
|
30
|
+
import sys
|
|
31
|
+
from dataclasses import asdict, dataclass
|
|
32
|
+
from html import escape
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
BOOTSTRAP_ROUNDS = 2000
|
|
37
|
+
NOISY_CV = 0.10 # coefficient of variation above which a sample is flagged noisy
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Bench:
|
|
42
|
+
name: str
|
|
43
|
+
unit: str
|
|
44
|
+
lower_is_better: bool
|
|
45
|
+
base: list[float]
|
|
46
|
+
head: list[float]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass
|
|
50
|
+
class Result:
|
|
51
|
+
name: str
|
|
52
|
+
unit: str
|
|
53
|
+
lower_is_better: bool
|
|
54
|
+
n_base: int
|
|
55
|
+
n_head: int
|
|
56
|
+
base_median: float
|
|
57
|
+
head_median: float
|
|
58
|
+
base_mean: float
|
|
59
|
+
head_mean: float
|
|
60
|
+
base_stdev: float
|
|
61
|
+
head_stdev: float
|
|
62
|
+
base_cv: float
|
|
63
|
+
head_cv: float
|
|
64
|
+
change_pct: float # signed so that positive always means "better"
|
|
65
|
+
ci_low_pct: float
|
|
66
|
+
ci_high_pct: float
|
|
67
|
+
verdict: str
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def fail(msg: str) -> None:
|
|
71
|
+
print(f"bench-report.py: error: {msg}", file=sys.stderr)
|
|
72
|
+
raise SystemExit(1)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def hyperfine_series(result: dict[str, Any]) -> dict[str, list[float]]:
|
|
76
|
+
"""Wall-time samples (hyperfine 1.x 'times', 2.x 'measurements') plus peak RSS when present."""
|
|
77
|
+
series: dict[str, list[float]] = {}
|
|
78
|
+
if isinstance(result.get("times"), list):
|
|
79
|
+
series["s"] = [float(t) for t in result["times"]]
|
|
80
|
+
measurements = result.get("measurements")
|
|
81
|
+
if isinstance(measurements, list) and measurements:
|
|
82
|
+
series["s"] = [float(m["time_wall_clock"]["value"]) for m in measurements if "time_wall_clock" in m]
|
|
83
|
+
rss = [float(m["memory_peak_resident"]["value"]) for m in measurements if "memory_peak_resident" in m]
|
|
84
|
+
if rss:
|
|
85
|
+
series["B"] = rss
|
|
86
|
+
return series
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def load_hyperfine(path: Path) -> list[Bench]:
|
|
90
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
91
|
+
pairs: dict[tuple[str, str], dict[str, list[float]]] = {}
|
|
92
|
+
for result in data.get("results", []):
|
|
93
|
+
label = str(result.get("name") or result.get("command", ""))
|
|
94
|
+
side, sep, name = label.partition(":")
|
|
95
|
+
if not sep or side not in ("base", "head") or not name:
|
|
96
|
+
fail(f"{path}: command {label!r} must be named base:<bench> or head:<bench> (hyperfine -n)")
|
|
97
|
+
series = hyperfine_series(result)
|
|
98
|
+
if not series.get("s"):
|
|
99
|
+
fail(f"{path}: {label!r} has no timing samples; rerun hyperfine with --export-json")
|
|
100
|
+
for unit, samples in series.items():
|
|
101
|
+
pairs.setdefault((name, unit), {})[side] = samples
|
|
102
|
+
benches = []
|
|
103
|
+
for (name, unit), sides in pairs.items():
|
|
104
|
+
if set(sides) != {"base", "head"}:
|
|
105
|
+
fail(f"{path}: benchmark {name!r} needs both base: and head: commands")
|
|
106
|
+
label = name if unit == "s" else f"{name} (peak memory)"
|
|
107
|
+
benches.append(Bench(label, unit, True, sides["base"], sides["head"]))
|
|
108
|
+
return benches
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def load_samples(path: Path) -> list[Bench]:
|
|
112
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
113
|
+
benches = []
|
|
114
|
+
for item in data.get("benchmarks", []):
|
|
115
|
+
try:
|
|
116
|
+
bench = Bench(
|
|
117
|
+
name=str(item["name"]),
|
|
118
|
+
unit=str(item.get("unit", "")),
|
|
119
|
+
lower_is_better=bool(item.get("lower_is_better", True)),
|
|
120
|
+
base=[float(v) for v in item["base"]],
|
|
121
|
+
head=[float(v) for v in item["head"]],
|
|
122
|
+
)
|
|
123
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
124
|
+
fail(f"{path}: malformed benchmark entry {item!r}: {exc}")
|
|
125
|
+
benches.append(bench)
|
|
126
|
+
return benches
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def signed_change(base: float, head: float, lower_is_better: bool) -> float:
|
|
130
|
+
"""Percent change where positive means better."""
|
|
131
|
+
if base == 0:
|
|
132
|
+
return 0.0
|
|
133
|
+
raw = (head - base) / base * 100.0
|
|
134
|
+
return -raw if lower_is_better else raw
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def analyse(bench: Bench, noise_floor: float, rng: random.Random) -> Result:
|
|
138
|
+
if len(bench.base) < 2 or len(bench.head) < 2:
|
|
139
|
+
fail(f"{bench.name}: need at least 2 samples per side (use 10+ for real evidence)")
|
|
140
|
+
b_med, h_med = statistics.median(bench.base), statistics.median(bench.head)
|
|
141
|
+
b_mean, h_mean = statistics.fmean(bench.base), statistics.fmean(bench.head)
|
|
142
|
+
b_sd, h_sd = statistics.stdev(bench.base), statistics.stdev(bench.head)
|
|
143
|
+
b_cv = b_sd / b_mean if b_mean else 0.0
|
|
144
|
+
h_cv = h_sd / h_mean if h_mean else 0.0
|
|
145
|
+
boots = sorted(
|
|
146
|
+
signed_change(
|
|
147
|
+
statistics.median(rng.choices(bench.base, k=len(bench.base))),
|
|
148
|
+
statistics.median(rng.choices(bench.head, k=len(bench.head))),
|
|
149
|
+
bench.lower_is_better,
|
|
150
|
+
)
|
|
151
|
+
for _ in range(BOOTSTRAP_ROUNDS)
|
|
152
|
+
)
|
|
153
|
+
lo = boots[int(0.025 * BOOTSTRAP_ROUNDS)]
|
|
154
|
+
hi = boots[int(0.975 * BOOTSTRAP_ROUNDS) - 1]
|
|
155
|
+
change = signed_change(b_med, h_med, bench.lower_is_better)
|
|
156
|
+
if lo > 0 and change >= noise_floor:
|
|
157
|
+
verdict = "improved"
|
|
158
|
+
elif hi < 0 and change <= -noise_floor:
|
|
159
|
+
verdict = "regressed"
|
|
160
|
+
elif max(b_cv, h_cv) > NOISY_CV:
|
|
161
|
+
verdict = "noisy"
|
|
162
|
+
else:
|
|
163
|
+
verdict = "no change"
|
|
164
|
+
return Result(
|
|
165
|
+
bench.name,
|
|
166
|
+
bench.unit,
|
|
167
|
+
bench.lower_is_better,
|
|
168
|
+
len(bench.base),
|
|
169
|
+
len(bench.head),
|
|
170
|
+
b_med,
|
|
171
|
+
h_med,
|
|
172
|
+
b_mean,
|
|
173
|
+
h_mean,
|
|
174
|
+
b_sd,
|
|
175
|
+
h_sd,
|
|
176
|
+
b_cv,
|
|
177
|
+
h_cv,
|
|
178
|
+
change,
|
|
179
|
+
lo,
|
|
180
|
+
hi,
|
|
181
|
+
verdict,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def fmt(value: float, unit: str) -> str:
|
|
186
|
+
if unit == "s":
|
|
187
|
+
for scale, label in ((1.0, "s"), (1e-3, "ms"), (1e-6, "µs"), (1e-9, "ns")):
|
|
188
|
+
if abs(value) >= scale or label == "ns":
|
|
189
|
+
return f"{value / scale:.3g} {label}"
|
|
190
|
+
if unit == "B":
|
|
191
|
+
for scale, label in ((1 << 30, "GiB"), (1 << 20, "MiB"), (1 << 10, "KiB"), (1, "B")):
|
|
192
|
+
if abs(value) >= scale or label == "B":
|
|
193
|
+
return f"{value / scale:.3g} {label}"
|
|
194
|
+
return f"{value:.4g} {unit}".strip()
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
ICON = {"improved": "🟢 improved", "regressed": "🔴 regressed", "no change": "⚪ no change", "noisy": "🟡 noisy"}
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def markdown(results: list[Result], noise_floor: float) -> str:
|
|
201
|
+
lines = [
|
|
202
|
+
"| Benchmark | Base (median ± sd) | Head (median ± sd) | Change | 95% CI | Runs | Verdict |",
|
|
203
|
+
"| --- | --- | --- | --- | --- | --- | --- |",
|
|
204
|
+
]
|
|
205
|
+
for r in results:
|
|
206
|
+
lines.append(
|
|
207
|
+
f"| {r.name} | {fmt(r.base_median, r.unit)} ± {fmt(r.base_stdev, r.unit)} "
|
|
208
|
+
f"| {fmt(r.head_median, r.unit)} ± {fmt(r.head_stdev, r.unit)} "
|
|
209
|
+
f"| {r.change_pct:+.1f}% | {r.ci_low_pct:+.1f}% … {r.ci_high_pct:+.1f}% "
|
|
210
|
+
f"| {r.n_base}/{r.n_head} | {ICON[r.verdict]} |"
|
|
211
|
+
)
|
|
212
|
+
lines.append("")
|
|
213
|
+
lines.append(
|
|
214
|
+
f"Change is signed so **positive = better** (faster, less memory, or higher throughput). "
|
|
215
|
+
f"Verdicts need the 95% bootstrap CI to exclude 0 and |change| ≥ {noise_floor:g}%; "
|
|
216
|
+
f"🟡 marks samples with CV > {NOISY_CV:.0%}."
|
|
217
|
+
)
|
|
218
|
+
return "\n".join(lines) + "\n"
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
COLORS = {"improved": "#0aac23", "regressed": "#dc3c3d", "no change": "#c2c2c2", "noisy": "#fbb315"}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def svg_chart(results: list[Result], title: str) -> str:
|
|
225
|
+
"""Diverging horizontal bars of % change (right = better) with CI whiskers."""
|
|
226
|
+
width, label_w, value_w, row_h, top, bottom = 1100, 240, 330, 40, 70, 56
|
|
227
|
+
plot_w = width - label_w - value_w - 40
|
|
228
|
+
height = top + row_h * len(results) + bottom
|
|
229
|
+
extent = max([5.0] + [max(abs(r.ci_low_pct), abs(r.ci_high_pct), abs(r.change_pct)) for r in results])
|
|
230
|
+
step = next((s for s in (1, 2, 5, 10, 20, 25, 50, 100, 200, 500, 1000) if s * 2 >= extent), 5000)
|
|
231
|
+
extent = step * 2.2
|
|
232
|
+
ticks = [-2 * step, -step, 0, step, 2 * step]
|
|
233
|
+
x0 = label_w + plot_w / 2
|
|
234
|
+
|
|
235
|
+
def x(pct: float) -> float:
|
|
236
|
+
return x0 + pct / extent * (plot_w / 2)
|
|
237
|
+
|
|
238
|
+
out = [
|
|
239
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" '
|
|
240
|
+
f'viewBox="0 0 {width} {height}" font-family="-apple-system,Segoe UI,Helvetica,Arial,sans-serif">',
|
|
241
|
+
f'<rect width="{width}" height="{height}" fill="#ffffff"/>',
|
|
242
|
+
f'<text x="20" y="30" font-size="18" font-weight="600" fill="#191919">{escape(title)}</text>',
|
|
243
|
+
'<text x="20" y="52" font-size="13" fill="#666666">Median change vs base, 95% bootstrap CI. '
|
|
244
|
+
"Right of 0 = better, left = worse.</text>",
|
|
245
|
+
]
|
|
246
|
+
for tick in ticks:
|
|
247
|
+
tx = x(tick)
|
|
248
|
+
color = "#c2c2c2" if tick == 0 else "#e7e7e7"
|
|
249
|
+
out.append(
|
|
250
|
+
f'<line x1="{tx:.1f}" y1="{top - 6}" x2="{tx:.1f}" y2="{height - bottom + 6}" '
|
|
251
|
+
f'stroke="{color}" stroke-width="1"/>'
|
|
252
|
+
)
|
|
253
|
+
out.append(
|
|
254
|
+
f'<text x="{tx:.1f}" y="{height - bottom + 24}" font-size="12" fill="#666666" '
|
|
255
|
+
f'text-anchor="middle">{tick:+.0f}%</text>'
|
|
256
|
+
)
|
|
257
|
+
out.append(
|
|
258
|
+
f'<text x="{x(-2 * step):.1f}" y="{height - 10}" font-size="12" fill="#666666">◀ worse</text>'
|
|
259
|
+
f'<text x="{x(2 * step):.1f}" y="{height - 10}" font-size="12" fill="#666666" '
|
|
260
|
+
f'text-anchor="end">better ▶</text>'
|
|
261
|
+
)
|
|
262
|
+
for i, r in enumerate(results):
|
|
263
|
+
cy = top + i * row_h + row_h / 2
|
|
264
|
+
bar_h = 16
|
|
265
|
+
left, right = sorted((x(0), x(r.change_pct)))
|
|
266
|
+
out.append(
|
|
267
|
+
f'<text x="{label_w - 12}" y="{cy + 4:.1f}" font-size="13" fill="#191919" '
|
|
268
|
+
f'text-anchor="end">{escape(r.name[:34])}</text>'
|
|
269
|
+
)
|
|
270
|
+
out.append(
|
|
271
|
+
f'<rect x="{left:.1f}" y="{cy - bar_h / 2:.1f}" width="{max(right - left, 2):.1f}" '
|
|
272
|
+
f'height="{bar_h}" rx="4" fill="{COLORS[r.verdict]}"/>'
|
|
273
|
+
)
|
|
274
|
+
out.append(
|
|
275
|
+
f'<line x1="{x(r.ci_low_pct):.1f}" y1="{cy:.1f}" x2="{x(r.ci_high_pct):.1f}" y2="{cy:.1f}" '
|
|
276
|
+
f'stroke="#191919" stroke-width="2"/>'
|
|
277
|
+
)
|
|
278
|
+
for edge in (r.ci_low_pct, r.ci_high_pct):
|
|
279
|
+
out.append(
|
|
280
|
+
f'<line x1="{x(edge):.1f}" y1="{cy - 6:.1f}" x2="{x(edge):.1f}" y2="{cy + 6:.1f}" '
|
|
281
|
+
f'stroke="#191919" stroke-width="2"/>'
|
|
282
|
+
)
|
|
283
|
+
summary = f"{r.change_pct:+.1f}% {fmt(r.base_median, r.unit)} → {fmt(r.head_median, r.unit)} {r.verdict}"
|
|
284
|
+
out.append(
|
|
285
|
+
f'<text x="{label_w + plot_w + 16}" y="{cy + 4:.1f}" font-size="12" fill="#191919">{escape(summary)}</text>'
|
|
286
|
+
)
|
|
287
|
+
out.append("</svg>")
|
|
288
|
+
return "\n".join(out) + "\n"
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def main(argv: list[str] | None = None) -> int:
|
|
292
|
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
293
|
+
parser.add_argument("--hyperfine", action="append", default=[], type=Path)
|
|
294
|
+
parser.add_argument("--samples", action="append", default=[], type=Path)
|
|
295
|
+
parser.add_argument("--md", type=Path)
|
|
296
|
+
parser.add_argument("--json", type=Path)
|
|
297
|
+
parser.add_argument("--svg", type=Path)
|
|
298
|
+
parser.add_argument("--title", default="Benchmarks: this branch vs base")
|
|
299
|
+
parser.add_argument("--noise-floor", type=float, default=2.0)
|
|
300
|
+
parser.add_argument("--seed", type=int, default=1)
|
|
301
|
+
args = parser.parse_args(argv)
|
|
302
|
+
|
|
303
|
+
benches: list[Bench] = []
|
|
304
|
+
for path in args.hyperfine:
|
|
305
|
+
if not path.is_file():
|
|
306
|
+
fail(f"no such file: {path}")
|
|
307
|
+
benches.extend(load_hyperfine(path))
|
|
308
|
+
for path in args.samples:
|
|
309
|
+
if not path.is_file():
|
|
310
|
+
fail(f"no such file: {path}")
|
|
311
|
+
benches.extend(load_samples(path))
|
|
312
|
+
if not benches:
|
|
313
|
+
fail("no benchmarks; pass --hyperfine or --samples")
|
|
314
|
+
|
|
315
|
+
rng = random.Random(args.seed)
|
|
316
|
+
results = [analyse(b, args.noise_floor, rng) for b in benches]
|
|
317
|
+
table = markdown(results, args.noise_floor)
|
|
318
|
+
if args.md:
|
|
319
|
+
args.md.write_text(table, encoding="utf-8")
|
|
320
|
+
else:
|
|
321
|
+
sys.stdout.write(table)
|
|
322
|
+
if args.json:
|
|
323
|
+
payload: dict[str, Any] = {"noise_floor_pct": args.noise_floor, "results": [asdict(r) for r in results]}
|
|
324
|
+
args.json.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
|
325
|
+
if args.svg:
|
|
326
|
+
args.svg.write_text(svg_chart(results, args.title), encoding="utf-8")
|
|
327
|
+
return 0
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
if __name__ == "__main__":
|
|
331
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// capture-ui.mjs — deterministic before/after UI evidence for pull requests.
|
|
3
|
+
//
|
|
4
|
+
// Subcommands:
|
|
5
|
+
// shoot --url <origin> --spec <spec.json> --label <before|after> --out <dir>
|
|
6
|
+
// Screenshot every route x viewport in the spec (and record videos
|
|
7
|
+
// for routes with "record": true) against one running app.
|
|
8
|
+
// compose --before <dir> --after <dir> --out <dir> [--threshold <0-255>]
|
|
9
|
+
// Pair same-named PNGs into one "Before | After | Diff" image each and
|
|
10
|
+
// write summary.json with the changed-pixel ratio per pair.
|
|
11
|
+
// render --input <file.svg|file.html> --out <file.png> [--width <px>]
|
|
12
|
+
// Render a local SVG/HTML file (e.g. a benchmark chart) to PNG.
|
|
13
|
+
//
|
|
14
|
+
// Playwright is resolved from the current project first, then globally.
|
|
15
|
+
// Exit codes: 0 success, 1 usage or runtime error.
|
|
16
|
+
|
|
17
|
+
import { createRequire } from 'node:module';
|
|
18
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
19
|
+
import { basename, extname, join, resolve } from 'node:path';
|
|
20
|
+
import { pathToFileURL } from 'node:url';
|
|
21
|
+
|
|
22
|
+
const DEFAULT_VIEWPORTS = [
|
|
23
|
+
{ name: 'mobile', width: 375, height: 667, deviceScaleFactor: 2, isMobile: true, hasTouch: true },
|
|
24
|
+
{ name: 'tablet', width: 768, height: 1024, deviceScaleFactor: 2, isMobile: true, hasTouch: true },
|
|
25
|
+
{ name: 'laptop', width: 1366, height: 768 },
|
|
26
|
+
{ name: 'desktop', width: 1920, height: 1080 },
|
|
27
|
+
{ name: 'wide', width: 2560, height: 1440 },
|
|
28
|
+
];
|
|
29
|
+
const MAX_IMAGE_BYTES = 9.5 * 1024 * 1024; // GitHub attachments cap images at 10 MB.
|
|
30
|
+
const PANEL_CSS_WIDTH = 900; // each panel in a composite, before downscaling.
|
|
31
|
+
|
|
32
|
+
function die(msg) {
|
|
33
|
+
process.stderr.write(`capture-ui.mjs: error: ${msg}\n`);
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function parseArgs(argv) {
|
|
38
|
+
const [cmd, ...rest] = argv;
|
|
39
|
+
const opts = {};
|
|
40
|
+
for (let i = 0; i < rest.length; i += 1) {
|
|
41
|
+
const key = rest[i];
|
|
42
|
+
if (!key.startsWith('--')) die(`unexpected argument: ${key}`);
|
|
43
|
+
const value = rest[i + 1];
|
|
44
|
+
if (value === undefined || value.startsWith('--')) die(`${key} needs a value`);
|
|
45
|
+
opts[key.slice(2)] = value;
|
|
46
|
+
i += 1;
|
|
47
|
+
}
|
|
48
|
+
return { cmd, opts };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function need(opts, ...keys) {
|
|
52
|
+
for (const k of keys) if (!opts[k]) die(`missing --${k}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function loadPlaywright() {
|
|
56
|
+
const attempts = [
|
|
57
|
+
() => createRequire(join(process.cwd(), 'package.json'))('playwright'),
|
|
58
|
+
() => createRequire(join(process.cwd(), 'package.json'))('@playwright/test'),
|
|
59
|
+
() => createRequire(import.meta.url)('playwright'),
|
|
60
|
+
];
|
|
61
|
+
for (const attempt of attempts) {
|
|
62
|
+
try {
|
|
63
|
+
return attempt();
|
|
64
|
+
} catch {
|
|
65
|
+
// try the next resolution strategy
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
return await import('playwright');
|
|
70
|
+
} catch {
|
|
71
|
+
die('Playwright not found. Install it in the project (npm i -D playwright && npx playwright install chromium) or globally.');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function slug(text) {
|
|
76
|
+
return String(text).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'root';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function runActions(page, actions = []) {
|
|
80
|
+
for (const a of actions) {
|
|
81
|
+
if (a.click) await page.locator(a.click).first().click();
|
|
82
|
+
else if (a.hover) await page.locator(a.hover).first().hover();
|
|
83
|
+
else if (a.fill) await page.locator(a.fill).first().fill(String(a.value ?? ''));
|
|
84
|
+
else if (a.press) await page.keyboard.press(a.press);
|
|
85
|
+
else if (a.waitFor) await page.locator(a.waitFor).first().waitFor({ state: 'visible' });
|
|
86
|
+
else if (a.scroll) await page.locator(a.scroll).first().scrollIntoViewIfNeeded();
|
|
87
|
+
else if (a.wait) await page.waitForTimeout(Number(a.wait));
|
|
88
|
+
else die(`unknown action: ${JSON.stringify(a)}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function settle(page, route) {
|
|
93
|
+
try {
|
|
94
|
+
await page.waitForLoadState('networkidle', { timeout: 15000 });
|
|
95
|
+
} catch {
|
|
96
|
+
// long-polling apps never go idle; the load event already fired
|
|
97
|
+
}
|
|
98
|
+
if (route.waitFor) await page.locator(route.waitFor).first().waitFor({ state: 'visible' });
|
|
99
|
+
await page.evaluate(() => document.fonts && document.fonts.ready);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function shoot(opts) {
|
|
103
|
+
need(opts, 'url', 'spec', 'label', 'out');
|
|
104
|
+
const spec = JSON.parse(readFileSync(opts.spec, 'utf8'));
|
|
105
|
+
if (!Array.isArray(spec.routes) || spec.routes.length === 0) die('spec.routes must be a non-empty array');
|
|
106
|
+
const viewports = spec.viewports ?? DEFAULT_VIEWPORTS;
|
|
107
|
+
const outDir = resolve(opts.out);
|
|
108
|
+
mkdirSync(outDir, { recursive: true });
|
|
109
|
+
const { chromium } = await loadPlaywright();
|
|
110
|
+
const browser = await chromium.launch();
|
|
111
|
+
const written = [];
|
|
112
|
+
try {
|
|
113
|
+
for (const route of spec.routes) {
|
|
114
|
+
const name = slug(route.name ?? route.path);
|
|
115
|
+
for (const vp of route.viewports ? viewports.filter((v) => route.viewports.includes(v.name)) : viewports) {
|
|
116
|
+
const record = Boolean(route.record);
|
|
117
|
+
const context = await browser.newContext({
|
|
118
|
+
viewport: { width: vp.width, height: vp.height },
|
|
119
|
+
deviceScaleFactor: vp.deviceScaleFactor ?? 1,
|
|
120
|
+
isMobile: vp.isMobile ?? false,
|
|
121
|
+
hasTouch: vp.hasTouch ?? false,
|
|
122
|
+
colorScheme: spec.colorScheme ?? 'light',
|
|
123
|
+
locale: spec.locale ?? 'en-US',
|
|
124
|
+
timezoneId: spec.timezoneId ?? 'UTC',
|
|
125
|
+
// Recordings exist to show motion, so only stills reduce it.
|
|
126
|
+
reducedMotion: record ? 'no-preference' : 'reduce',
|
|
127
|
+
storageState: spec.storageState,
|
|
128
|
+
recordVideo: record ? { dir: outDir, size: { width: vp.width, height: vp.height } } : undefined,
|
|
129
|
+
});
|
|
130
|
+
const page = await context.newPage();
|
|
131
|
+
if (spec.freezeTime !== false) await page.clock.setFixedTime(new Date(spec.freezeTime ?? '2024-01-01T12:00:00Z'));
|
|
132
|
+
await page.goto(new URL(route.path, opts.url).toString(), { waitUntil: 'load' });
|
|
133
|
+
await settle(page, route);
|
|
134
|
+
if (record) {
|
|
135
|
+
await page.waitForTimeout(500);
|
|
136
|
+
await runActions(page, route.actions);
|
|
137
|
+
await page.waitForTimeout(Number(route.tail ?? 800));
|
|
138
|
+
} else {
|
|
139
|
+
await runActions(page, route.actions);
|
|
140
|
+
const css = spec.hideSelectors?.length
|
|
141
|
+
? `${spec.hideSelectors.join(',')}{visibility:hidden !important}`
|
|
142
|
+
: undefined;
|
|
143
|
+
const file = join(outDir, `${name}--${vp.name}.png`);
|
|
144
|
+
await page.screenshot({
|
|
145
|
+
path: file,
|
|
146
|
+
fullPage: route.fullPage ?? spec.fullPage ?? true,
|
|
147
|
+
animations: 'disabled',
|
|
148
|
+
caret: 'hide',
|
|
149
|
+
scale: 'device',
|
|
150
|
+
mask: (spec.maskSelectors ?? []).map((s) => page.locator(s)),
|
|
151
|
+
maskColor: '#FF00FF',
|
|
152
|
+
style: css,
|
|
153
|
+
});
|
|
154
|
+
written.push(file);
|
|
155
|
+
}
|
|
156
|
+
const video = page.video();
|
|
157
|
+
await context.close();
|
|
158
|
+
if (video) {
|
|
159
|
+
const target = join(outDir, `${name}--${vp.name}--${opts.label}.webm`);
|
|
160
|
+
renameSync(await video.path(), target);
|
|
161
|
+
written.push(target);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
} finally {
|
|
166
|
+
await browser.close();
|
|
167
|
+
}
|
|
168
|
+
process.stdout.write(`${JSON.stringify({ label: opts.label, files: written }, null, 2)}\n`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function composeHtml() {
|
|
172
|
+
return `<!doctype html><html><head><meta charset="utf-8"><style>
|
|
173
|
+
body{margin:0;background:#f9f9f9;font:14px/1.4 -apple-system,Segoe UI,Helvetica,Arial,sans-serif;color:#191919}
|
|
174
|
+
#wrap{display:inline-flex;gap:16px;padding:16px;background:#f9f9f9}
|
|
175
|
+
figure{margin:0;background:#fff;border:1px solid rgba(11,11,11,.1);border-radius:6px;padding:8px}
|
|
176
|
+
figcaption{font-weight:600;margin:0 0 6px;color:#666}
|
|
177
|
+
canvas{display:block}
|
|
178
|
+
</style></head><body><div id="wrap"></div></body></html>`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function composePair(page, beforeFile, afterFile, threshold) {
|
|
182
|
+
const toData = (f) => `data:image/png;base64,${readFileSync(f).toString('base64')}`;
|
|
183
|
+
return page.evaluate(
|
|
184
|
+
async ({ a, b, threshold: t, panelWidth }) => {
|
|
185
|
+
const load = (src) =>
|
|
186
|
+
new Promise((ok, fail) => {
|
|
187
|
+
const img = new Image();
|
|
188
|
+
img.onload = () => ok(img);
|
|
189
|
+
img.onerror = fail;
|
|
190
|
+
img.src = src;
|
|
191
|
+
});
|
|
192
|
+
const [imgA, imgB] = await Promise.all([load(a), load(b)]);
|
|
193
|
+
const w = Math.max(imgA.width, imgB.width);
|
|
194
|
+
const h = Math.max(imgA.height, imgB.height);
|
|
195
|
+
const pixels = (img) => {
|
|
196
|
+
const c = document.createElement('canvas');
|
|
197
|
+
c.width = w;
|
|
198
|
+
c.height = h;
|
|
199
|
+
const ctx = c.getContext('2d');
|
|
200
|
+
ctx.fillStyle = '#ffffff';
|
|
201
|
+
ctx.fillRect(0, 0, w, h);
|
|
202
|
+
ctx.drawImage(img, 0, 0);
|
|
203
|
+
return { c, data: ctx.getImageData(0, 0, w, h).data };
|
|
204
|
+
};
|
|
205
|
+
const A = pixels(imgA);
|
|
206
|
+
const B = pixels(imgB);
|
|
207
|
+
const diff = document.createElement('canvas');
|
|
208
|
+
diff.width = w;
|
|
209
|
+
diff.height = h;
|
|
210
|
+
const dctx = diff.getContext('2d');
|
|
211
|
+
const out = dctx.createImageData(w, h);
|
|
212
|
+
let changed = 0;
|
|
213
|
+
for (let y = 0; y < h; y += 1) {
|
|
214
|
+
for (let x = 0; x < w; x += 1) {
|
|
215
|
+
const i = (y * w + x) * 4;
|
|
216
|
+
const outside = x >= imgA.width || y >= imgA.height || x >= imgB.width || y >= imgB.height;
|
|
217
|
+
const delta = Math.max(
|
|
218
|
+
Math.abs(A.data[i] - B.data[i]),
|
|
219
|
+
Math.abs(A.data[i + 1] - B.data[i + 1]),
|
|
220
|
+
Math.abs(A.data[i + 2] - B.data[i + 2]),
|
|
221
|
+
);
|
|
222
|
+
if (outside || delta > t) {
|
|
223
|
+
changed += 1;
|
|
224
|
+
out.data.set([220, 60, 61, 255], i); // changed pixel
|
|
225
|
+
} else {
|
|
226
|
+
const g = 200 + Math.round((B.data[i] + B.data[i + 1] + B.data[i + 2]) / 3 / 255 * 55);
|
|
227
|
+
out.data.set([g, g, g, 255], i); // unchanged, faded
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
dctx.putImageData(out, 0, 0);
|
|
232
|
+
const ratio = changed / (w * h);
|
|
233
|
+
const wrap = document.getElementById('wrap');
|
|
234
|
+
wrap.innerHTML = '';
|
|
235
|
+
const scale = Math.min(1, panelWidth / w);
|
|
236
|
+
for (const [label, canvas] of [
|
|
237
|
+
['Before (base)', A.c],
|
|
238
|
+
['After (this branch)', B.c],
|
|
239
|
+
[`Diff: ${(ratio * 100).toFixed(2)}% of pixels changed`, diff],
|
|
240
|
+
]) {
|
|
241
|
+
const fig = document.createElement('figure');
|
|
242
|
+
const cap = document.createElement('figcaption');
|
|
243
|
+
cap.textContent = label;
|
|
244
|
+
canvas.style.width = `${Math.round(w * scale)}px`;
|
|
245
|
+
canvas.style.height = `${Math.round(h * scale)}px`;
|
|
246
|
+
fig.append(cap, canvas);
|
|
247
|
+
wrap.append(fig);
|
|
248
|
+
}
|
|
249
|
+
return { width: w, height: h, changedPixels: changed, changedRatio: ratio };
|
|
250
|
+
},
|
|
251
|
+
{ a: toData(beforeFile), b: toData(afterFile), threshold, panelWidth: PANEL_CSS_WIDTH },
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function compose(opts) {
|
|
256
|
+
need(opts, 'before', 'after', 'out');
|
|
257
|
+
const threshold = Number(opts.threshold ?? 16);
|
|
258
|
+
const outDir = resolve(opts.out);
|
|
259
|
+
mkdirSync(outDir, { recursive: true });
|
|
260
|
+
const pngs = (d) => new Set(readdirSync(d).filter((f) => extname(f) === '.png'));
|
|
261
|
+
const before = pngs(opts.before);
|
|
262
|
+
const after = pngs(opts.after);
|
|
263
|
+
const names = [...new Set([...before, ...after])].sort();
|
|
264
|
+
const { chromium } = await loadPlaywright();
|
|
265
|
+
const browser = await chromium.launch();
|
|
266
|
+
const summary = [];
|
|
267
|
+
try {
|
|
268
|
+
const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
|
|
269
|
+
await page.setContent(composeHtml());
|
|
270
|
+
for (const name of names) {
|
|
271
|
+
if (!before.has(name) || !after.has(name)) {
|
|
272
|
+
summary.push({ name, status: before.has(name) ? 'removed' : 'added' });
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
const stats = await composePair(page, join(opts.before, name), join(opts.after, name), threshold);
|
|
276
|
+
let file = join(outDir, name);
|
|
277
|
+
await page.locator('#wrap').screenshot({ path: file });
|
|
278
|
+
if (statSync(file).size > MAX_IMAGE_BYTES) {
|
|
279
|
+
file = join(outDir, `${basename(name, '.png')}.jpg`);
|
|
280
|
+
await page.locator('#wrap').screenshot({ path: file, type: 'jpeg', quality: 80 });
|
|
281
|
+
}
|
|
282
|
+
summary.push({ name, status: stats.changedPixels === 0 ? 'unchanged' : 'changed', composite: file, ...stats });
|
|
283
|
+
}
|
|
284
|
+
} finally {
|
|
285
|
+
await browser.close();
|
|
286
|
+
}
|
|
287
|
+
writeFileSync(join(outDir, 'summary.json'), `${JSON.stringify(summary, null, 2)}\n`);
|
|
288
|
+
process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function render(opts) {
|
|
292
|
+
need(opts, 'input', 'out');
|
|
293
|
+
const input = resolve(opts.input);
|
|
294
|
+
if (!existsSync(input)) die(`no such file: ${input}`);
|
|
295
|
+
const { chromium } = await loadPlaywright();
|
|
296
|
+
const browser = await chromium.launch();
|
|
297
|
+
try {
|
|
298
|
+
const page = await browser.newPage({ viewport: { width: Number(opts.width ?? 1000), height: 600 }, deviceScaleFactor: 2 });
|
|
299
|
+
await page.goto(pathToFileURL(input).toString());
|
|
300
|
+
const target = extname(input) === '.svg' ? page.locator('svg').first() : page.locator('body');
|
|
301
|
+
await target.screenshot({ path: resolve(opts.out) });
|
|
302
|
+
} finally {
|
|
303
|
+
await browser.close();
|
|
304
|
+
}
|
|
305
|
+
process.stdout.write(`${resolve(opts.out)}\n`);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const { cmd, opts } = parseArgs(process.argv.slice(2));
|
|
309
|
+
const commands = { shoot, compose, render };
|
|
310
|
+
if (!commands[cmd]) die('usage: capture-ui.mjs <shoot|compose|render> [--options]; see the header of this file');
|
|
311
|
+
commands[cmd](opts).catch((err) => die(err?.stack ?? String(err)));
|