@jesdi/skills 0.0.84 → 0.0.86

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 (31) hide show
  1. package/package.json +1 -1
  2. package/skills/implement-spec/ARCHITECTURE.md +9 -2
  3. package/skills/implement-spec/README.md +2 -2
  4. package/skills/implement-spec/driver.py +34 -8
  5. package/skills/implement-spec/driver_agents.py +41 -13
  6. package/skills/implement-spec/driver_final.py +21 -2
  7. package/skills/implement-spec/driver_fixloop.py +4 -3
  8. package/skills/implement-spec/prompts/pr-body.md +1 -0
  9. package/skills/implement-spec/tests/test_agents.py +20 -3
  10. package/skills/implement-spec/tests/test_driver.py +17 -10
  11. package/skills/implement-spec/tests/test_landing.py +2 -2
  12. package/skills/implement-spec/tests/test_lenses.py +31 -0
  13. package/skills/implement-spec/tests/test_tidy.py +2 -0
  14. package/skills/implement-spec/tests/test_walk.py +2 -2
  15. package/skills/test-weigh-in/dashboard.html +185 -27
  16. package/skills/test-weigh-in/rules.toml +18 -0
  17. package/skills/test-weigh-in/tests/browser_driver.py +161 -0
  18. package/skills/test-weigh-in/tests/conftest.py +8 -1
  19. package/skills/test-weigh-in/tests/latency_probe.py +96 -0
  20. package/skills/test-weigh-in/tests/layout_page.py +37 -0
  21. package/skills/test-weigh-in/tests/metric_page.py +56 -0
  22. package/skills/test-weigh-in/tests/overlap_page.py +60 -0
  23. package/skills/test-weigh-in/tests/rules_fixture.py +3 -1
  24. package/skills/test-weigh-in/tests/sorted_map_page.py +35 -0
  25. package/skills/test-weigh-in/tests/test_brittleness.py +5 -0
  26. package/skills/test-weigh-in/tests/test_dashboard_layout.py +103 -0
  27. package/skills/test-weigh-in/tests/test_scoring.py +10 -0
  28. package/skills/test-weigh-in/weigh.py +25 -15
  29. package/skills/test-weigh-in/weigh_dashboard.py +9 -1
  30. package/skills/test-weigh-in/weigh_rules.py +3 -0
  31. package/skills-manifest.json +5 -5
@@ -0,0 +1,96 @@
1
+ """Ticket 03 latency evidence (R3, design.md "Latency evidence"): `uv run --with playwright python latency_probe.py <out-dir>`.
2
+
3
+ Writes a 2,172-dot map (test_hub has 148 neighbours) through weigh_dashboard.write_dashboard, opens it from disk in Chrome
4
+ with no CPU throttling, and prints one JSON document: machine, OS, browser version, fixture, the cold map opening (Map tab
5
+ click to the first frame painted with every dot) and 20 alternating selections (dot click to the first frame painted with
6
+ the new name, highlights and neighbours). It asserts nothing: the 200 ms claim needs the benchmark machine the operator agrees.
7
+ """
8
+ import json
9
+ import platform
10
+ import random
11
+ import subprocess
12
+ import sys
13
+ from pathlib import Path
14
+ from urllib.parse import quote
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
17
+
18
+ import map_fixture
19
+ from playwright.sync_api import sync_playwright
20
+
21
+ N, NEAR = 2172, 148
22
+ HUB, OTHER = "tests/hub/test_hub.py::test_hub", "tests/scale/test_module_0005.py::test_case_0005"
23
+ FIXTURE = f"{N} dots, {HUB} with {NEAR} neighbours, alternating with {OTHER}"
24
+
25
+ FRAME = "() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)))"
26
+ COLD = """async () => {
27
+ const t0 = performance.now();
28
+ [...document.querySelectorAll('[data-testid=details] button')].find((b) => b.textContent.trim() === 'Map').click();
29
+ await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)));
30
+ return {ms: performance.now() - t0, dots: document.querySelectorAll('[data-testid=map-dot]').length};
31
+ }"""
32
+ SELECT = """async ([hub, other]) => {
33
+ const out = [];
34
+ for (let i = 0; i < 20; i++) {
35
+ const target = i % 2 === 0 ? hub : other;
36
+ const dot = document.querySelector(`[data-testid=map-dot][data-test="${target}"]`);
37
+ const t0 = performance.now();
38
+ dot.dispatchEvent(new MouseEvent('click', {bubbles: true}));
39
+ await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done)));
40
+ const ms = performance.now() - t0;
41
+ const shown = document.querySelector('[data-testid=map-picked]').textContent.endsWith(target);
42
+ out.push({target, ms, shown, neighbours: document.querySelectorAll('[data-testid=map-similar-item]').length});
43
+ }
44
+ return out;
45
+ }"""
46
+
47
+
48
+ def page(out):
49
+ map_fixture.build(out) # a write_dashboard page whose map is replaced by the scaled one
50
+ html = out / "dashboard.html"
51
+ text = html.read_text()
52
+ head, rest = text.split("const data = ", 1)
53
+ end = rest.index(";\n")
54
+ data = json.loads(rest[:end])
55
+ names = [HUB] + [f"tests/scale/test_module_{i:04d}.py::test_case_{i:04d}" for i in range(1, N)]
56
+ similar = {n: [] for n in names}
57
+ for k in range(1, NEAR + 1):
58
+ s = 0.7 + (k * 7 % 19) / 100
59
+ similar[HUB].append([names[k], s])
60
+ similar[names[k]].append([HUB, s])
61
+ rnd = random.Random(7)
62
+ data["map"] = [{"test": n, "x": rnd.random(), "y": rnd.random(), "runtime": 0.01, "unique": 0, "similar": similar[n]} for n in names]
63
+ html.write_text(head + "const data = " + json.dumps(data).replace("</", "<\\/") + rest[end:])
64
+ return html
65
+
66
+
67
+ def machine():
68
+ if sys.platform == "darwin":
69
+ return subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True).stdout.strip()
70
+ return platform.processor() or platform.machine()
71
+
72
+
73
+ def main(out):
74
+ html = page(out)
75
+ with sync_playwright() as p:
76
+ try:
77
+ browser = p.chromium.launch(channel="chrome")
78
+ except Exception:
79
+ browser = p.chromium.launch()
80
+ tab = browser.new_page(viewport={"width": 1440, "height": 900})
81
+ tab.goto("file://" + quote(str(html.resolve())))
82
+ tab.locator("[data-testid=gauge]").filter(has_text="Economy").first.click()
83
+ tab.evaluate(FRAME)
84
+ cold = tab.evaluate(COLD)
85
+ selections = tab.evaluate(SELECT, [HUB, OTHER])
86
+ result = {"machine": machine(), "os": platform.platform(), "browser": f"{browser.browser_type.name} {browser.version}",
87
+ "fixture": FIXTURE, "cold_map_opening_ms": round(cold["ms"]), "dots": cold["dots"],
88
+ "selections_ms": [round(s["ms"], 1) for s in selections], "max_selection_ms": round(max(s["ms"] for s in selections), 1),
89
+ "all_shown": all(s["shown"] for s in selections),
90
+ "neighbours": sorted({s["neighbours"] for s in selections})}
91
+ browser.close()
92
+ print(json.dumps(result, indent=1))
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main(Path(sys.argv[1]))
@@ -0,0 +1,37 @@
1
+ """Ticket 04 fixture, no repo run: `layout_page.py <out-dir>` writes <out-dir>/dashboard.html through
2
+ weigh_dashboard.write_dashboard and prints its path. The real-suite shape of the spec: 2,172 tests (all drawn on the
3
+ Map), 3,196 cases, 6,757 overlap pairs with 200-character ids.
4
+ Fast feedback is fully measured, Resistance to refactoring has 0 of its 4 metrics measured (reasons recorded).
5
+ """
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
+
11
+ import overlap_page
12
+ from weigh_dashboard import write_dashboard
13
+ from weigh_rules import load
14
+ from weigh_score import feedback_values, score
15
+
16
+ FIXTURE = "2172 tests, 3196 cases, 6757 pairs"
17
+ NOT_MEASURED = ("brittle_test_files", "private_access", "mock_heavy", "interaction_only")
18
+
19
+
20
+ def build(out):
21
+ out.mkdir(parents=True, exist_ok=True)
22
+ rules = load()
23
+ tests = {}
24
+ for i in range(overlap_page.N_TESTS):
25
+ lo = (i % 300) * 10 + 1
26
+ tests[overlap_page.name(i)] = {"outcome": "passed", "duration": 0.01 + (i % 9) / 100, "coverage": {"src/m.py": list(range(lo, lo + 6 + i % 3))},
27
+ "unique_coverage": 0, "flaky": False, "smells": [], "lines": 2}
28
+ values = {**feedback_values(tests, 1.0), "no_unique_coverage": 100.0, "branch_coverage": 80.0, "hollow_tests": 1.0}
29
+ metrics, pillars = score(rules, values)
30
+ data = {"commit": "abc1234", "dirty": False, "inventory": {"tests": overlap_page.N_TESTS, "cases": 3196, "test_files": 44, "test_lines": 9000, "source_lines": 9000, "runtime_seconds": 64.2},
31
+ "metrics": metrics, "pillars": pillars, "tests": tests, "overlaps": overlap_page.pairs(),
32
+ "unmeasured": {m: "no git history" for m in NOT_MEASURED}}
33
+ return write_dashboard(out, data, rules)
34
+
35
+
36
+ if __name__ == "__main__":
37
+ print(build(Path(sys.argv[1])))
@@ -0,0 +1,56 @@
1
+ """Ticket 01 fixtures, no repo run: `metric_page.py <out-dir> <scenario>` writes <out-dir>/dashboard.html through
2
+ weigh_dashboard.write_dashboard and prints its path.
3
+
4
+ Interface the acceptance tests pin (the spec leaves the snapshot key open): snapshot["unmeasured"] = {metric id: reason}
5
+ records why a metric was not measured; a snapshot without it (older data) or without the metric's entry has no recorded cause.
6
+ Scenarios:
7
+ values total_runtime 64.16 and branch_coverage 94.84, rules with non-default total_runtime anchors (30 / 300)
8
+ zero refactoring has 0 of 4 metrics measured (all four have reasons); feedback has tests_over_10s measured at 0 and
9
+ p95_duration missing with no recorded cause
10
+ scores metric scores 0.2, 100 and (zero tests over 10 s) 90
11
+ default the default-run shape: regression lacks mutation_score and pseudo_tested_functions, with the recorded reason
12
+ """
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
18
+
19
+ import rules_fixture
20
+ from weigh_dashboard import write_dashboard
21
+ from weigh_rules import load
22
+ from weigh_score import score
23
+
24
+ TIER = "the mutation tier did not run"
25
+ VALUES = {
26
+ "values": {"total_runtime": 64.16, "branch_coverage": 94.84},
27
+ "zero": {"tests_over_10s": 0, "total_runtime": 5.0, "slowest_decile_share": 50.0},
28
+ "scores": {"smelly_tests": 20.0, "long_tests": 1.0, "tests_over_10s": 0},
29
+ "default": {"branch_coverage": 80.0, "hollow_tests": 1.0},
30
+ }
31
+ UNMEASURED = {
32
+ "zero": {"brittle_test_files": "no git history", "private_access": "no ruff", "mock_heavy": "no ruff", "interaction_only": "no ruff"},
33
+ "default": {"mutation_score": TIER, "pseudo_tested_functions": TIER},
34
+ }
35
+
36
+
37
+ def build(out, scenario):
38
+ out.mkdir(parents=True, exist_ok=True)
39
+ rules_path = rules_fixture.write_rules(out / "rules.toml", **({"total_runtime": dict(target=30, bad=300)} if scenario == "values" else {}))
40
+ import os
41
+ os.environ["TEST_WEIGH_IN_RULES"] = str(rules_path)
42
+ rules = load()
43
+ metrics, pillars = score(rules, VALUES[scenario])
44
+ if scenario == "scores":
45
+ metrics["smelly_tests"]["score"], metrics["long_tests"]["score"] = 0.2, 100.0
46
+ pillars["maintainability"]["score"] = 100.0
47
+ tests = {"tests/test_a.py::test_a": {"outcome": "passed", "duration": 0.1, "coverage": {}, "unique_coverage": 0, "flaky": False, "smells": [], "lines": 2}}
48
+ data = {"commit": "abc1234", "dirty": False, "inventory": {"tests": 1, "cases": 1, "test_files": 1, "test_lines": 2, "source_lines": 2, "runtime_seconds": 0.1},
49
+ "metrics": metrics, "pillars": pillars, "tests": tests, "overlaps": []}
50
+ if scenario in UNMEASURED:
51
+ data["unmeasured"] = UNMEASURED[scenario]
52
+ return write_dashboard(out, data, rules)
53
+
54
+
55
+ if __name__ == "__main__":
56
+ print(build(Path(sys.argv[1]), sys.argv[2]))
@@ -0,0 +1,60 @@
1
+ """Ticket 02 fixture, no repo run: `overlap_page.py <out-dir> [reversed]` writes <out-dir>/dashboard.html through
2
+ weigh_dashboard.write_dashboard and <out-dir>/pairs.json (the pairs as fed, same order unless "reversed").
3
+
4
+ 6,757 overlap pairs over 2,172 tests with 200-character ids, Jaccard values on a 0.90..1.00 grid (many ties).
5
+ One pair holds ids that occur nowhere else (UNIQUE_LEFT / UNIQUE_RIGHT), one pair holds markup in its ids (HOSTILE).
6
+ Interface the acceptance tests pin (the spec leaves the markup open), inside the Overlaps tab of the Economy pillar:
7
+ [data-testid=overlap-search] the search input (an `input` event applies the query)
8
+ [data-testid=overlap-count] the result count: contains the number of matching pairs
9
+ [data-testid=overlap-pair] one row per pair on the current page, at most 100 rows; holds two
10
+ [data-testid=overlap-test] identities and a label naming "Jaccard" with the value
11
+ [data-testid=overlap-empty] shown only when no pair matches, with an explanation
12
+ [data-testid=overlap-next] pages forward; disabled on the last page
13
+ """
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
19
+
20
+ from weigh_dashboard import write_dashboard
21
+ from weigh_rules import load
22
+ from weigh_score import feedback_values, score
23
+
24
+ N_TESTS, N_PAIRS = 2172, 6757
25
+ UNIQUE_LEFT = "tests/unique/test_alpha_only.py::test_only_left_xylophone"
26
+ UNIQUE_RIGHT = "tests/unique/test_omega_only.py::test_only_right_zeppelin"
27
+ HOSTILE = ['tests/<b id="pwn">x<img src=x onerror="pwned=1">/test_</script><script>window.pwned=1</script>.py::test_hostile',
28
+ "tests/test_ok_partner.py::test_partner"]
29
+
30
+
31
+ def name(i):
32
+ return f"tests/{'sub_package_' * 12}{i // 50:03d}/test_module_{i:04d}.py::TestClass{i % 7}::test_case_{i:04d}_{'x' * 40}"
33
+
34
+
35
+ def pairs():
36
+ out = []
37
+ for k in range(N_PAIRS):
38
+ a = k % N_TESTS
39
+ b = (a + 1 + k // N_TESTS) % N_TESTS
40
+ out.append({"tests": [name(a), name(b)], "jaccard": round(0.90 + (k * 7919 % 11) / 100, 2)})
41
+ out[1234] = {"tests": [UNIQUE_LEFT, UNIQUE_RIGHT], "jaccard": 0.93}
42
+ out[4321] = {"tests": HOSTILE, "jaccard": 0.91}
43
+ return out
44
+
45
+
46
+ def build(out, order="forward"):
47
+ out.mkdir(parents=True, exist_ok=True)
48
+ rules = load()
49
+ tests = {name(i): {"outcome": "passed", "duration": 0.01, "coverage": {}, "unique_coverage": 0, "flaky": False, "smells": [], "lines": 2}
50
+ for i in range(N_TESTS)}
51
+ metrics, pillars = score(rules, {**feedback_values(tests, 1.0), "no_unique_coverage": 100.0})
52
+ fed = pairs()[::-1] if order == "reversed" else pairs()
53
+ data = {"commit": "abc1234", "dirty": False, "inventory": {"tests": N_TESTS, "cases": 3196, "test_files": 44, "test_lines": 9000, "source_lines": 9000, "runtime_seconds": 64.2},
54
+ "metrics": metrics, "pillars": pillars, "tests": tests, "overlaps": fed}
55
+ (out / "pairs.json").write_text(json.dumps(fed))
56
+ return write_dashboard(out, data, rules)
57
+
58
+
59
+ if __name__ == "__main__":
60
+ print(build(Path(sys.argv[1]), *sys.argv[2:3]))
@@ -2,6 +2,7 @@
2
2
 
3
3
  Interface the tests pin (the spec leaves the TOML keys and the snapshot JSON keys open):
4
4
  rules.toml: version = 1; [pillars.<key>] name = "..."; [pillars.<key>.metrics.<id>] name, weight,
5
+ unit ("%", "s" or ""),
5
6
  optional partial_weight, target, bad, optional log = true. Percentages are 0-100,
6
7
  durations are seconds. Pillar keys: regression, refactoring, feedback,
7
8
  maintainability, economy.
@@ -50,7 +51,8 @@ def write_rules(path, **overrides):
50
51
  lines += [f"[pillars.{key}]", f'name = "{name}"', ""]
51
52
  for mid, mname, weight, partial, target, bad, log in metrics:
52
53
  m = {**dict(weight=weight, target=target, bad=bad), **overrides.get(mid, {})}
53
- lines += [f"[pillars.{key}.metrics.{mid}]", f'name = "{mname}"']
54
+ unit = "s" if mid in ("total_runtime", "p95_duration") else "" if mid == "test_source_ratio" else "%"
55
+ lines += [f"[pillars.{key}.metrics.{mid}]", f'name = "{mname}"', f'unit = "{unit}"']
54
56
  lines += [f"{k} = {v!r}" for k, v in m.items()]
55
57
  if partial is not None:
56
58
  lines.append(f"partial_weight = {partial!r}")
@@ -0,0 +1,35 @@
1
+ """Ticket 03 fixture, no repo run: `sorted_map_page.py <out-dir>` writes <out-dir>/dashboard.html through weigh_dashboard.write_dashboard.
2
+
3
+ PICKED covers lines 1-100. Its neighbours are fed in the order SIM_091 (0.91), SIM_100 (1.00), SIM_095 (0.95).
4
+ BELOW covers lines 1-50 (0.50 with PICKED, not eligible); LONELY covers lines 200-210 (similar to nothing).
5
+ """
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
+
11
+ from weigh_dashboard import write_dashboard
12
+ from weigh_rules import load
13
+ from weigh_score import feedback_values, score
14
+
15
+ PICKED = "tests/test_pick.py::test_picked"
16
+ SIM_091, SIM_100, SIM_095 = (f"tests/test_pick.py::test_sim_{n}" for n in ("091", "100", "095"))
17
+ BELOW = "tests/test_pick.py::test_below"
18
+ LONELY = "tests/test_pick.py::test_lonely"
19
+ COVERAGE = {PICKED: range(1, 101), SIM_091: range(1, 92), SIM_100: range(1, 101), SIM_095: range(1, 96),
20
+ BELOW: range(1, 51), LONELY: range(200, 211)}
21
+
22
+
23
+ def build(out):
24
+ out.mkdir(parents=True, exist_ok=True)
25
+ rules = load()
26
+ tests = {n: {"outcome": "passed", "duration": 0.05, "coverage": {"demo/a.py": list(lines)}, "unique_coverage": 0, "flaky": False, "smells": [], "lines": 2}
27
+ for n, lines in COVERAGE.items()}
28
+ metrics, pillars = score(rules, {**feedback_values(tests, 1.0), "no_unique_coverage": 100.0})
29
+ data = {"commit": "abc1234", "dirty": False, "inventory": {"tests": 6, "cases": 6, "test_files": 1, "test_lines": 12, "source_lines": 210, "runtime_seconds": 1.0},
30
+ "metrics": metrics, "pillars": pillars, "tests": tests, "overlaps": []}
31
+ return write_dashboard(out, data, rules)
32
+
33
+
34
+ if __name__ == "__main__":
35
+ print(build(Path(sys.argv[1])))
@@ -2,6 +2,7 @@
2
2
  Interface: see brittle_repo.py."""
3
3
  from brittle_repo import CLAIMS, TEST, board_repo, claims_repo, commit, history, without_git
4
4
  from fixture_repo import build_repo, load, snapshots, weigh
5
+ from weigh_rules import load as load_rules
5
6
 
6
7
  KEY = "github.com/jesdi/demo"
7
8
 
@@ -53,6 +54,10 @@ def test_a_target_that_is_not_a_git_repository_leaves_brittleness_unmeasured(tmp
53
54
  assert data["test_files"][TEST]["brittle"] is None
54
55
  assert "brittle_test_files" not in data["metrics"]
55
56
  assert data["pillars"]["refactoring"]["partial"] is True
57
+ assert data["unmeasured"]["brittle_test_files"] == "no git history"
58
+ # every metric is either measured or has the reason it is not, never both (hollow_tests is measured without mutation)
59
+ assert not data["unmeasured"].keys() & data["metrics"].keys()
60
+ assert data["unmeasured"].keys() | data["metrics"].keys() == {m for p in load_rules()["pillars"].values() for m in p["metrics"]}
56
61
 
57
62
 
58
63
  def test_two_runs_of_the_default_repo_are_equal_apart_from_durations(tmp_path, home, cache):
@@ -0,0 +1,103 @@
1
+ """Ticket 04 of specs/test-weigh-in-dashboard-polish: readable layout, visible tabs and the offline report (R8, R9, R11, R12).
2
+
3
+ Seam: weigh_dashboard.write_dashboard (via layout_page.py, the real-suite fixture: 2,172 tests, 3,196 cases, 6,757 pairs).
4
+ The returned standalone HTML is opened from disk in Chrome with the network off (browser_driver.py, run by `uv run
5
+ --with playwright`, needs Chrome or a Playwright chromium) and its visible controls are driven. Latency is not asserted:
6
+ the 200 ms claim needs the benchmark machine the operator agrees (design.md).
7
+ """
8
+ import json
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ import pytest
15
+
16
+ from fixture_repo import uv
17
+
18
+ HERE = Path(__file__).resolve().parent
19
+ SPEC = HERE.parents[2] / "specs" / "test-weigh-in-dashboard-polish"
20
+ TABS = ["Metrics", "Overlaps", "Map"]
21
+
22
+
23
+ @pytest.fixture(scope="module")
24
+ def report(tmp_path_factory):
25
+ out = tmp_path_factory.mktemp("layout04")
26
+ built = subprocess.run([sys.executable, str(HERE / "layout_page.py"), str(out)], capture_output=True, text=True, timeout=600)
27
+ assert built.returncode == 0, built.stderr
28
+ html = Path(built.stdout.strip())
29
+ drove = subprocess.run([uv(), "run", "--with", "playwright", "python", str(HERE / "browser_driver.py"), str(html)],
30
+ capture_output=True, text=True, timeout=600)
31
+ assert drove.returncode == 0, drove.stderr[-3000:]
32
+ return {"bytes": html.stat().st_size, **json.loads(drove.stdout)}
33
+
34
+
35
+ def only_active(tabs, label):
36
+ """Exactly one tab looks different from the rest, and it is `label`."""
37
+ sigs = [t["sig"] for t in tabs]
38
+ odd = [t["text"] for t in tabs if sigs.count(t["sig"]) == 1]
39
+ assert odd == [label], f"visibly active tabs: {odd}, selected {label}"
40
+ assert len({t["sig"] for t in tabs if t["text"] != label}) == 1, "the inactive tabs do not look alike"
41
+
42
+
43
+ def test_the_active_tab_follows_selection_and_keyboard_focus_shows(report):
44
+ for label in TABS:
45
+ only_active(report["tabs"]["steps"][label], label)
46
+ focus = report["tabs"]["focus"]
47
+ ring = not focus["outline"].startswith("none") and not focus["outline"].split()[1] == "0px"
48
+ assert ring or focus["sig_focused"] != focus["sig_unfocused"], f"no visible focus state: {focus}"
49
+
50
+
51
+ @pytest.mark.parametrize("view", ["desktop", "narrow"])
52
+ def test_gauges_align_and_partial_status_stays_readable(report, view):
53
+ gauges = report[view]["gauges"]
54
+ assert len(gauges) == 5
55
+ for g in gauges:
56
+ assert g["title"] and g["status"], "every gauge has a gauge-title and a gauge-status, a fully measured one too"
57
+ assert g["status"]["text"], "a fully measured pillar still states its measurement status"
58
+ assert not g["title"]["clipped"] and not g["status"]["clipped"]
59
+ assert g["status"]["font"] >= 11 and g["status"]["lines"] <= 2, f"partial status unreadable: {g['status']}"
60
+ rows = {}
61
+ for g in gauges:
62
+ rows.setdefault(g["card"]["top"], []).append(g)
63
+ for row in rows.values():
64
+ for part in ("title", "score", "status"):
65
+ assert len({g[part]["top"] for g in row}) == 1, f"{part} not aligned across a row at {view}: {[g[part]['top'] for g in row]}"
66
+ refactoring = next(g for g in gauges if "refactoring" in g["title"]["text"].lower())
67
+ assert "0 of 4" in refactoring["status"]["text"]
68
+ assert report[view]["overview"]["scroll_width"] <= report[view]["overview"]["viewport"], "the page overflows sideways"
69
+
70
+
71
+ @pytest.mark.parametrize("view", ["desktop", "narrow"])
72
+ def test_details_use_the_available_width_and_keep_full_identities(report, view):
73
+ r = report[view]
74
+ for key in ("feedback_details", "refactoring_details", "overlaps", "map"):
75
+ assert r[key]["scroll_width"] <= r[key]["viewport"], f"{key} overflows the viewport"
76
+ assert r[key]["details_right"] <= r[key]["viewport"]
77
+ assert r["feedback_table_share"] >= 0.85, "the metrics table leaves the right-hand region unused"
78
+ assert r["overlap_ids"]
79
+ for ident in r["overlap_ids"]:
80
+ assert ident["text"].endswith("x" * 40), "identity is not shown in full"
81
+ assert ident["right"] <= r["overlaps"]["viewport"] and not ident["clipped"] and not ident["ellipsis"]
82
+
83
+
84
+ def test_offline_from_disk_keeps_the_evidence(report):
85
+ j = report["journey"]
86
+ assert j["requests"] == [] and j["failed_requests"] == [] and j["page_errors"] == []
87
+ assert "No metrics were measured" in j["refactoring_text"] and "Total runtime" in j["feedback_text"]
88
+ assert "6,757" in j["count_all"] and j["first_row_page_1"] != j["first_row_page_2"]
89
+ assert re.search(r"\b1\b", j["count_search"]) and j["rows_search"] == 1 and "6,757" in j["count_cleared"]
90
+ assert j["dots"] == 2172 and "test_module_0010" in j["picked"] and j["similar_items"] > 0
91
+ assert "Anchors" in j["metrics_text"]
92
+ only_active(j["active_overlaps"], "Overlaps")
93
+ only_active(j["active_map"], "Map")
94
+ only_active(j["active_metrics"], "Metrics")
95
+
96
+
97
+ def test_the_size_of_the_real_suite_report_is_recorded_without_truncating_it(report):
98
+ record = (SPEC / "validation.md").read_text()
99
+ assert "2172 tests, 3196 cases, 6757 pairs" in record
100
+ recorded = int(re.search(r"html-bytes:\s*([\d,]+)", record).group(1).replace(",", ""))
101
+ assert report["bytes"] / 2 <= recorded <= report["bytes"] * 2, f"recorded {recorded}, this fixture renders {report['bytes']}"
102
+ assert report["bytes"] > 1_000_000
103
+ assert "6,757" in report["journey"]["count_all"] and report["journey"]["dots"] == 2172
@@ -101,6 +101,16 @@ def test_equal_anchors_stop_the_run_naming_the_metric(tmp_path, home, cache):
101
101
  assert snapshots(home, KEY) == []
102
102
 
103
103
 
104
+ def test_a_metric_with_an_unknown_unit_stops_the_run_naming_the_metric(tmp_path, home, cache):
105
+ repo = build_repo(tmp_path / "demo")
106
+ rules = write_rules(tmp_path / "rules.toml")
107
+ rules.write_text(rules.read_text().replace('unit = "s"', 'unit = "min"', 1)) # the first "s" metric is total_runtime
108
+ result = weigh(repo, home, cache=cache, rules=rules)
109
+ assert result.returncode == 2
110
+ assert "total runtime needs a unit" in (result.stdout + result.stderr).lower()
111
+ assert snapshots(home, KEY) == []
112
+
113
+
104
114
  def test_edited_rules_keep_the_version_and_change_the_hash(tmp_path, home, cache):
105
115
  repo = build_repo(tmp_path / "demo")
106
116
  before = write_rules(tmp_path / "before.toml", branch_coverage=dict(bad=50))
@@ -65,14 +65,23 @@ def main(argv=None):
65
65
  "runtime_seconds": max(run["runtime_seconds"], sum(c["duration"] for c in run["cases"].values())),
66
66
  }
67
67
  values = feedback_values(tests, inventory["runtime_seconds"])
68
- if mutation is not None:
69
- values["mutation_score"] = mutation["score"]
70
- values["pseudo_tested_functions"] = mutation["pseudo_tested"]
68
+ unmeasured = {}
69
+
70
+ def measure(mid, value, reason):
71
+ """An optional metric records its value, or the reason it has none, here and only here."""
72
+ if value is None:
73
+ unmeasured[mid] = reason
74
+ else:
75
+ values[mid] = value
76
+
77
+ tier = "the mutation tier did not run"
78
+ measure("mutation_score", None if mutation is None else mutation["score"], tier)
79
+ measure("pseudo_tested_functions", None if mutation is None else mutation["pseudo_tested"], tier)
71
80
  found, clusters = find_smells(repo, tests, violations(repo, rules.get("ruff", {}).get("pt", [])))
72
81
  for node, info in found.items():
73
82
  tests[node].update(info)
74
- if inventory["source_lines"]:
75
- values["test_source_ratio"] = inventory["test_lines"] / inventory["source_lines"]
83
+ measure("test_source_ratio", inventory["test_lines"] / inventory["source_lines"] if inventory["source_lines"] else None,
84
+ "no source lines found")
76
85
  # failing, erroring and skipped tests cost (runtime, lines, smells) but give no value: no coverage, overlap or uniqueness
77
86
  covered = per_test(cov["report"], cov["arcs"], repo)
78
87
  cov_tests = aggregate(cov["cases"])
@@ -84,18 +93,18 @@ def main(argv=None):
84
93
  unique = unique_coverage(passing)
85
94
  for node, test in tests.items():
86
95
  test["unique_coverage"] = unique.get(node, 0)
87
- if branch_percent(cov["value_report"]) is not None:
88
- values["branch_coverage"] = branch_percent(cov["value_report"])
89
- if mutation is not None: # flags tests before the metrics they change are computed
90
- values.update(kill_matrix(tests, passing, mutation))
96
+ measure("branch_coverage", branch_percent(cov["value_report"]), "no branch data in the coverage report")
97
+ # flags tests before the metrics they change are computed
98
+ measure("subsumed_in_kill_matrix", None if mutation is None else kill_matrix(tests, passing, mutation)["subsumed_in_kill_matrix"], tier)
91
99
  values.update(smell_values(tests))
92
- if passing:
93
- # a count-based metric is a percentage of all tests (req 17); only valued tests can lack unique coverage, and an
94
- # insufficient-evidence test counts in no Economy metric
95
- values["no_unique_coverage"] = 100 * sum(not u and not tests[n].get("insufficient_evidence") for n, u in unique.items()) / len(tests)
100
+ # a count-based metric is a percentage of all tests (req 17); only valued tests can lack unique coverage, and an
101
+ # insufficient-evidence test counts in no Economy metric
102
+ measure("no_unique_coverage",
103
+ 100 * sum(not u and not tests[n].get("insufficient_evidence") for n, u in unique.items()) / len(tests) if passing else None,
104
+ "no test passed")
96
105
  test_files = brittleness(repo, test_file_sources(tests))
97
- if (percent := brittle_percent(test_files)) is not None:
98
- values["brittle_test_files"] = percent
106
+ measure("brittle_test_files", brittle_percent(test_files),
107
+ "no source file maps to a test file" if is_repo(repo) else "no git history")
99
108
  metrics, pillars = score(rules, values, red=len(passing) < len(tests))
100
109
  data = {
101
110
  "commit": commit,
@@ -106,6 +115,7 @@ def main(argv=None):
106
115
  "rules": {"version": rules["version"], "sha256": rules["sha256"]},
107
116
  "inventory": inventory,
108
117
  "metrics": metrics,
118
+ "unmeasured": unmeasured,
109
119
  "pillars": pillars,
110
120
  "mutation_settings": {"mutation": args.mutation, "matrix_per_function": "all" if args.matrix_per_function is None else args.matrix_per_function},
111
121
  **({"mutation": {k: mutation[k] for k in ("sampled", "mutants", "matrix")}} if mutation is not None else {}),
@@ -18,6 +18,10 @@ def _failing(tests):
18
18
  return sum(t["outcome"] == "failed" for t in tests.values())
19
19
 
20
20
 
21
+ def _failing_names(tests):
22
+ return [n for n, t in tests.items() if t["outcome"] == "failed"]
23
+
24
+
21
25
  def _flaky(tests):
22
26
  return sum(t.get("flaky", False) for t in tests.values())
23
27
 
@@ -31,6 +35,7 @@ def write_dashboard(home, data, rules):
31
35
  failing = _failing(data["tests"])
32
36
  page = {
33
37
  "banner": f"{failing} tests are failing" if failing > 1 else "1 test is failing" if failing else None,
38
+ "failing": _failing_names(data["tests"]),
34
39
  "skipped": [n for n, t in data["tests"].items() if t["outcome"] == "skipped"],
35
40
  "insufficient": [n for n, t in data["tests"].items() if t.get("insufficient_evidence")],
36
41
  "overlaps": data.get("overlaps", []),
@@ -39,7 +44,10 @@ def write_dashboard(home, data, rules):
39
44
  "inventory": inventory_line(data["inventory"]),
40
45
  "pillars": [
41
46
  {"key": k, "name": p["name"], **data["pillars"][k],
42
- "metrics": [{"name": m["name"], **data["metrics"][i]} for i, m in p["metrics"].items() if i in data["metrics"]],
47
+ "metrics": [{"name": m["name"], "unit": m["unit"], "target": m["target"], "bad": m["bad"], **data["metrics"][i]}
48
+ for i, m in p["metrics"].items() if i in data["metrics"]],
49
+ # an entry the snapshot does not record (older data) has no known cause
50
+ "missing": [{"name": m["name"], "reason": data.get("unmeasured", {}).get(i)} for i, m in p["metrics"].items() if i not in data["metrics"]],
43
51
  "total": len(p["metrics"]),
44
52
  "worst": worst_tests(data["tests"], k, _slow(rules)),
45
53
  "smells": pillar_smells(data["tests"], PILLAR_SMELLS.get(k, ()))}
@@ -9,6 +9,7 @@ from weigh_env import SetupError
9
9
 
10
10
  DEFAULT = Path(__file__).resolve().parent / "rules.toml"
11
11
  TABLE = re.compile(r"^\[([A-Za-z0-9_.]+)\]$")
12
+ UNITS = ("%", "s", "") # percent of all tests, seconds, plain ratio
12
13
  PILLARS = ("regression", "refactoring", "feedback", "maintainability", "economy")
13
14
 
14
15
 
@@ -58,6 +59,8 @@ def validate(rules):
58
59
  if not pillar or not pillar.get("metrics"):
59
60
  raise RulesError(f"rules.toml: pillar {key} is missing or has no metrics")
60
61
  for mid, m in pillar["metrics"].items():
62
+ if m.get("unit") not in UNITS:
63
+ raise RulesError(f"rules.toml: {pillar['name']}: {m['name']} needs a unit, one of {', '.join(map(repr, UNITS))}")
61
64
  if m["target"] == m["bad"]:
62
65
  raise RulesError(f"rules.toml: {pillar['name']}: {m['name']} has target and bad anchors both {m['target']}")
63
66
  total = sum(m["weight"] for m in pillar["metrics"].values())
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-03T12:00:34.732Z",
3
+ "generatedAt": "2026-11-05T12:22:43.116Z",
4
4
  "skills": [
5
5
  {
6
6
  "name": "agents-wayfinder",
@@ -58,8 +58,8 @@
58
58
  },
59
59
  {
60
60
  "name": "implement-spec",
61
- "version": "0.1.48",
62
- "hash": "sha256-c1c51c34db8cb4c87c3437b3b0c1569dbabb60e327b3afdeaa5e0b9306efa0ba",
61
+ "version": "0.1.50",
62
+ "hash": "sha256-2b88ad4bcc572280fd6d023ad925e7644fae72483c4827c032362724d14cfa3d",
63
63
  "description": "Implement a specification in code."
64
64
  },
65
65
  {
@@ -106,8 +106,8 @@
106
106
  },
107
107
  {
108
108
  "name": "test-weigh-in",
109
- "version": "0.1.2",
110
- "hash": "sha256-3f0a00b5a362a869c0c9e12bfa6a9e11674338f24b5b2248ec9479b0e0581ed1",
109
+ "version": "0.1.3",
110
+ "hash": "sha256-aecabdc7fd3d511440930bdc3274960106fe37959227ae3be7428dd634f8d4eb",
111
111
  "description": "Measure a Python/pytest suite and score it on five pillars (Protection against regressions, Resistance to refactoring, Fast feedback, Maintainability, Economy), writing a JSON snapshot and a static HTML dashboard. Read-only. Use when the user asks to weigh, measure or score their test suite."
112
112
  },
113
113
  {