@yandy-r/ycc-opencode 6.5.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.
Files changed (62) hide show
  1. package/README.md +11 -4
  2. package/agents/code-finder.md +1 -1
  3. package/agents/planner.md +1 -2
  4. package/agents/pr-evidence-collector.md +99 -0
  5. package/agents/root-cause-analyzer.md +1 -1
  6. package/index.js +9 -0
  7. package/package.json +1 -1
  8. package/registration.json +67 -0
  9. package/shared/references/standalone-dispatch.md +4 -1
  10. package/shared/references/target-capability-matrix.md +170 -30
  11. package/shared/references/worktree-strategy.md +7 -21
  12. package/skills/bundle-author/scripts/scaffold-skill.sh +9 -0
  13. package/skills/bundle-release/scripts/release_versions.py +19 -1
  14. package/skills/code-report/SKILL.md +0 -2
  15. package/skills/code-report/templates/report-structure.md +0 -2
  16. package/skills/compatibility-audit/SKILL.md +8 -4
  17. package/skills/compatibility-audit/scripts/audit-install-assumptions.sh +75 -5
  18. package/skills/compatibility-audit/scripts/audit-target-features.sh +15 -9
  19. package/skills/feature-research/SKILL.md +1 -1
  20. package/skills/feature-research/scripts/validate-spec.sh +0 -4
  21. package/skills/formatters/references/templates/lint-autofix.yml.tmpl +7 -7
  22. package/skills/formatters/references/templates/lint.yml.tmpl +11 -11
  23. package/skills/formatters/scripts/bundle/go-tools.sh +73 -41
  24. package/skills/formatters/scripts/bundle/init-formatters.sh +1 -1
  25. package/skills/formatters/scripts/bundle/lib/modified-files.sh +0 -5
  26. package/skills/git-workflow/SKILL.md +1 -0
  27. package/skills/git-workflow/templates/agent-prompts.md +5 -6
  28. package/skills/git-workflow/templates/documentation-decision.md +1 -3
  29. package/skills/git-workflow/templates/pr-template.md +1 -3
  30. package/skills/go-patterns/references/design-and-tooling.md +16 -13
  31. package/skills/go-testing/references/advanced-testing.md +2 -2
  32. package/skills/implement-plan/references/agent-task-prompt.md +18 -20
  33. package/skills/implement-plan/scripts/parse-dependencies.sh +3 -9
  34. package/skills/init/templates/git/gitignore.tmpl +2 -0
  35. package/skills/init/templates/github/workflows/pr-title.yml.tmpl +1 -1
  36. package/skills/orchestrate/SKILL.md +1 -1
  37. package/skills/orchestrate/references/dispatch-playbook.md +1 -1
  38. package/skills/parallel-plan/SKILL.md +6 -10
  39. package/skills/plan-workflow/SKILL.md +3 -3
  40. package/skills/plan-workflow/references/plan-structure.md +1 -3
  41. package/skills/plan-workflow/scripts/validate-workflow-plan.sh +2 -8
  42. package/skills/pr-evidence/SKILL.md +138 -0
  43. package/skills/pr-evidence/references/perf-evidence.md +119 -0
  44. package/skills/pr-evidence/references/pr-body-and-hosting.md +112 -0
  45. package/skills/pr-evidence/references/ui-evidence.md +152 -0
  46. package/skills/pr-evidence/scripts/bench_report.py +331 -0
  47. package/skills/pr-evidence/scripts/capture-ui.mjs +311 -0
  48. package/skills/pr-evidence/scripts/classify-change.sh +135 -0
  49. package/skills/prp-plan/SKILL.md +4 -5
  50. package/skills/prp-plan/scripts/validate-prp-plan.sh +1 -11
  51. package/skills/prp-pr/SKILL.md +4 -0
  52. package/skills/releaser/references/ci-optimization-checklist.md +1 -1
  53. package/skills/releaser/references/ci-templates/docker-release.yml +8 -8
  54. package/skills/releaser/references/ci-templates/generic-release.yml +5 -5
  55. package/skills/releaser/references/ci-templates/go-release.yml +4 -4
  56. package/skills/releaser/references/ci-templates/node-release.yml +8 -8
  57. package/skills/releaser/references/ci-templates/python-release.yml +8 -8
  58. package/skills/releaser/references/ci-templates/rust-release.yml +10 -10
  59. package/skills/rust-testing/references/advanced-testing.md +1 -1
  60. package/skills/shared-context/SKILL.md +6 -10
  61. package/skills/ts-testing/references/advanced-testing.md +4 -4
  62. package/skills/visual-recap/SKILL.md +3 -4
@@ -0,0 +1,112 @@
1
+ # PR Body Evidence Section and Hosting
2
+
3
+ ## Contents
4
+
5
+ - Evidence section template
6
+ - Skip lines
7
+ - Hosting order
8
+ - Privacy and size
9
+
10
+ ## Evidence section template
11
+
12
+ Place `## Evidence` right after the PR summary (or in the template's closest
13
+ section, such as "Testing" or "Reviewer Notes", when the repo's template has no
14
+ room for a new heading). Reference images by their **local absolute path**; the
15
+ upload step rewrites them to hosted URLs.
16
+
17
+ ```markdown
18
+ ## Evidence
19
+
20
+ **UI** — captured at `<short-sha>` vs merge-base `<short-sha>`, Chromium, light theme.
21
+ Changed: settings form spacing and error state. No other screens moved.
22
+
23
+ | Viewport | Before · After · Diff |
24
+ | --------------- | ----------------------------------------------------------- |
25
+ | Mobile 375×667 | ![Settings, mobile](/abs/path/compare/settings--mobile.png) |
26
+ | Laptop 1366×768 | ![Settings, laptop](/abs/path/compare/settings--laptop.png) |
27
+ | Wide 2560×1440 | ![Settings, wide](/abs/path/compare/settings--wide.png) |
28
+
29
+ Menu opening, after:
30
+
31
+ ![](/abs/path/after/menu-open--mobile--after.webm)
32
+
33
+ <details><summary>Unchanged viewports (0.00% diff)</summary>
34
+
35
+ ![Settings, tablet](/abs/path/compare/settings--tablet.png)
36
+
37
+ </details>
38
+
39
+ **Performance** — 20 runs per side after 3 warm-ups, Linux x86_64, 8 cores, release build.
40
+
41
+ ![Benchmark change vs base](/abs/path/perf/chart.png)
42
+
43
+ | Benchmark | Base (median ± sd) | Head (median ± sd) | Change | 95% CI | Runs | Verdict |
44
+ | ----------- | ------------------ | ------------------ | ------ | --------------- | ----- | ----------- |
45
+ | parse-large | 12.1 ms ± 0.2 ms | 9.9 ms ± 0.3 ms | +18.2% | +16.9% … +19.4% | 20/20 | 🟢 improved |
46
+
47
+ <details><summary>How to reproduce</summary>
48
+
49
+ hyperfine -N --warmup 3 --runs 20 -n base:parse-large '…' -n head:parse-large '…'
50
+
51
+ </details>
52
+ ```
53
+
54
+ Lead with what the reviewer should notice, in one line per kind. Put changed
55
+ viewports first and fold the rest. A video reference must be alone in its
56
+ paragraph or GitHub renders it as a link.
57
+
58
+ ## Skip lines
59
+
60
+ When a kind does not apply, write one line instead of the section:
61
+
62
+ - `Evidence: none needed (docs-only change).`
63
+ - `Evidence: UI not captured — the dashboard needs production credentials; reviewer should check /billing at mobile width.`
64
+ - `Evidence: no visual change expected (internal refactor); spot-check composites show 0.00% diff.`
65
+
66
+ ## Hosting order
67
+
68
+ Never commit evidence to the feature branch: it bloats history and the diff.
69
+
70
+ 1. **gh 2.99 or later on github.com / GHE Cloud** (`gh --version`). Pass every
71
+ referenced file once with `--attach`; gh uploads it and rewrites the matching
72
+ local path in the body. Alt text goes after `#`.
73
+
74
+ ```bash
75
+ gh pr create --title "<title>" --base <base> --body-file body.md \
76
+ --attach '/abs/compare/settings--mobile.png#Settings, mobile' \
77
+ --attach /abs/after/menu-open--mobile--after.webm
78
+ ```
79
+
80
+ For a PR that already exists, or one created through the GitHub MCP tool, use
81
+ `gh pr edit <n> --body-file body.md --attach …`. For evidence captured after
82
+ review, use `gh pr comment <n> --body-file note.md --attach …`. Uploads need
83
+ push access to the repository.
84
+
85
+ 2. **Older gh:** upgrade gh when you can. Otherwise push the files to an orphan
86
+ branch named `pr-evidence` (one directory per PR) and reference them as
87
+ `https://github.com/<owner>/<repo>/blob/<sha>/<path>?raw=true`. Pin to the
88
+ commit SHA, not the branch, so later pushes cannot change what the PR shows.
89
+
90
+ ```bash
91
+ git worktree add --orphan -b pr-evidence "$EVIDENCE/host" # first time only
92
+ # later runs: git worktree add "$EVIDENCE/host" pr-evidence
93
+ ```
94
+
95
+ 3. **Forgejo or Gitea:** upload each file with the issue-attachments API
96
+ (`POST /api/v1/repos/{owner}/{repo}/issues/{index}/assets`, form field
97
+ `attachment`) after the PR exists, then edit the body with the returned
98
+ `browser_download_url`. If that API is unavailable, use the orphan branch.
99
+ 4. **No upload path at all:** keep the files in the evidence directory, list
100
+ their paths in the PR body under Evidence, and tell the user.
101
+
102
+ Do not use public image hosts, gists of a private repository's UI, or release
103
+ assets for PR evidence: they outlive the PR and can leak private work.
104
+
105
+ ## Privacy and size
106
+
107
+ - Check every image for secrets, tokens, personal data and customer content
108
+ before upload. Mask (`maskSelectors`) or use seeded data instead.
109
+ - On a public repository, anything attached is public.
110
+ - Limits: images and GIFs 10 MB; video 10 MB on free plans, 100 MB on paid.
111
+ `capture-ui.mjs compose` falls back to JPEG above 9.5 MB. Shorten or scale
112
+ videos that exceed the limit.
@@ -0,0 +1,152 @@
1
+ # UI Evidence
2
+
3
+ ## Contents
4
+
5
+ - Goal
6
+ - Pick what to show
7
+ - Run base and branch
8
+ - Capture spec
9
+ - Shoot and compose
10
+ - Determinism checklist
11
+ - Motion and interaction
12
+ - Non-web interfaces
13
+ - Manifest
14
+
15
+ ## Goal
16
+
17
+ The reviewer checks alignment, spacing, overflow and responsiveness at a glance.
18
+ Every changed screen appears at small, medium and large sizes, base next to branch,
19
+ with the pixels that changed highlighted.
20
+
21
+ ## Pick what to show
22
+
23
+ Read the diff and list the screens and states the change affects: the page that
24
+ renders a changed component, plus the states that exercise it (empty, loading,
25
+ error, long text, hover, open menu, dark mode when themes changed). Prefer three
26
+ to six well-chosen states over every route in the app. Add one unaffected
27
+ neighbour screen when the change touches shared styles, to show nothing else moved.
28
+
29
+ ## Run base and branch
30
+
31
+ Build and serve each checkout the same way, one after the other on the **same
32
+ port** so origin-dependent behaviour matches:
33
+
34
+ 1. Install and start the base worktree (`npm ci && npm run build && npm run preview`,
35
+ `npm run dev`, Storybook, or the project's own command). Wait until it answers.
36
+ 2. Shoot with `--label before`, then stop the server.
37
+ 3. Start the branch the same way, shoot with `--label after`, stop it.
38
+
39
+ Use production builds when the project has them; dev overlays and hot-reload
40
+ banners add noise. Seed the same data on both sides. Use the project's test
41
+ login or `storageState` file, never a real user's session.
42
+
43
+ ## Capture spec
44
+
45
+ `capture-ui.mjs` reads a JSON spec:
46
+
47
+ ```json
48
+ {
49
+ "routes": [
50
+ { "name": "settings", "path": "/settings", "waitFor": "[data-testid=settings-form]" },
51
+ {
52
+ "name": "settings-error",
53
+ "path": "/settings",
54
+ "actions": [
55
+ { "fill": "#email", "value": "not-an-email" },
56
+ { "click": "button[type=submit]" },
57
+ { "waitFor": ".field-error" }
58
+ ]
59
+ },
60
+ {
61
+ "name": "menu-open",
62
+ "path": "/",
63
+ "record": true,
64
+ "viewports": ["mobile", "desktop"],
65
+ "actions": [{ "click": "[aria-label=Menu]" }, { "wait": 400 }]
66
+ }
67
+ ],
68
+ "maskSelectors": ["[data-testid=avatar]", ".timestamp"],
69
+ "hideSelectors": ["#intercom-container"],
70
+ "colorScheme": "light",
71
+ "freezeTime": "2024-01-01T12:00:00Z"
72
+ }
73
+ ```
74
+
75
+ Actions: `click`, `hover`, `fill` + `value`, `press`, `waitFor`, `scroll`, `wait`
76
+ (milliseconds, last resort). Omit `viewports` to use the defaults:
77
+
78
+ | Name | Size | Why |
79
+ | ------- | ----------- | ----------------------------------- |
80
+ | mobile | 375 x 667 | small phone, touch, 2x density |
81
+ | tablet | 768 x 1024 | breakpoint edge, touch, 2x density |
82
+ | laptop | 1366 x 768 | common low-resolution laptop |
83
+ | desktop | 1920 x 1080 | standard monitor |
84
+ | wide | 2560 x 1440 | large screen, max-width and stretch |
85
+
86
+ Override `viewports` in the spec when the project defines its own breakpoints
87
+ (test one pixel each side of a breakpoint that the change touches). Add a dark
88
+ `colorScheme` run when theme tokens changed.
89
+
90
+ ## Shoot and compose
91
+
92
+ ```bash
93
+ node capture-ui.mjs shoot --url http://localhost:3000 --spec spec.json --label before --out "$EVIDENCE/ui/before"
94
+ node capture-ui.mjs shoot --url http://localhost:3000 --spec spec.json --label after --out "$EVIDENCE/ui/after"
95
+ node capture-ui.mjs compose --before "$EVIDENCE/ui/before" --after "$EVIDENCE/ui/after" --out "$EVIDENCE/ui/compare"
96
+ ```
97
+
98
+ `compose` writes one image per route and viewport with three panels (Before,
99
+ After, Diff in red) and `summary.json` with the share of changed pixels. Attach
100
+ the composites, not the raw shots. Playwright resolves from the project first;
101
+ if missing, install it in a scratch directory, not the project's manifest.
102
+
103
+ Before handing back, open every composite and check:
104
+
105
+ - The change is visible where expected, and nothing unexpected moved.
106
+ - Nothing overflows, truncates, overlaps or wraps badly at mobile and tablet.
107
+ - Content does not stretch awkwardly or leave empty gutters at wide.
108
+ - Masks cover only dynamic content (they show as magenta).
109
+
110
+ Report any layout bug you see in the summary; that is the point of the evidence.
111
+
112
+ ## Determinism checklist
113
+
114
+ The script already freezes the clock, pins locale and timezone, reduces motion,
115
+ disables CSS animations and transitions, hides the caret, waits for network idle
116
+ and fonts. Two runs of the same build should give a 0% diff. When they do not:
117
+
118
+ - Mask or hide what still changes: timestamps, avatars, ads, maps, charts with
119
+ live data, random IDs, carousels, third-party widgets.
120
+ - Wait for the real ready signal (`waitFor`) instead of adding `wait`.
121
+ - Stub or seed network data; never point both runs at a live API whose data moves.
122
+ - Use the same machine and browser build for both runs; fonts and antialiasing
123
+ differ across operating systems.
124
+
125
+ ## Motion and interaction
126
+
127
+ Use a recording when the change is an animation, transition, drag, scroll effect,
128
+ loading sequence or multi-step flow. Set `"record": true` on the route; the script
129
+ saves `<route>--<viewport>--before.webm` and `--after.webm` with reduced motion
130
+ off. Keep each clip under 10 seconds. GitHub renders `.webm` and `.mp4` inline
131
+ (10 MB on free plans, 100 MB on paid). For a looping preview, convert to GIF and
132
+ keep it under 10 MB:
133
+
134
+ ```bash
135
+ ffmpeg -y -i in.webm -vf "fps=12,scale=800:-1:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse" out.gif
136
+ ```
137
+
138
+ ## Non-web interfaces
139
+
140
+ - **Terminal output (CLI, TUI):** record with `vhs` (a `.tape` file per state) or
141
+ capture the before/after output as text in a fenced block.
142
+ - **Native or mobile apps:** use the platform's simulator screenshot command
143
+ (`xcrun simctl io booted screenshot`, `adb exec-out screencap -p`) at the same
144
+ device profile for both builds, then `compose` the PNGs.
145
+ - **Email or PDF output:** render to PNG and compose the same way.
146
+
147
+ ## Manifest
148
+
149
+ Write `$EVIDENCE/ui/manifest.json` (contract in the skill) and
150
+ `$EVIDENCE/ui/evidence-section.md`: the UI part of the Evidence section, with
151
+ image references as absolute local paths, changed viewports first and unchanged
152
+ ones inside `<details>`. Return only the manifest path and a two-sentence summary.
@@ -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())