@jesdi/skills 0.0.81 → 0.0.83

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 (71) hide show
  1. package/package.json +2 -1
  2. package/skills/crap-gate/launcher.sh +104 -0
  3. package/skills/crap-gate/run.sh +15 -75
  4. package/skills/crap-gate/test_launcher.py +39 -0
  5. package/skills/implement-spec/launcher.sh +104 -0
  6. package/skills/implement-spec/run.sh +10 -89
  7. package/skills/implement-spec/tests/test_launcher.py +138 -0
  8. package/skills/test-weigh-in/SKILL.md +16 -0
  9. package/skills/test-weigh-in/dashboard.html +112 -0
  10. package/skills/test-weigh-in/launcher.sh +104 -0
  11. package/skills/test-weigh-in/rules.toml +134 -0
  12. package/skills/test-weigh-in/run.sh +21 -0
  13. package/skills/test-weigh-in/tests/brittle_repo.py +79 -0
  14. package/skills/test-weigh-in/tests/conftest.py +35 -0
  15. package/skills/test-weigh-in/tests/fixture_repo.py +99 -0
  16. package/skills/test-weigh-in/tests/kill_repo.py +87 -0
  17. package/skills/test-weigh-in/tests/maint_repo.py +139 -0
  18. package/skills/test-weigh-in/tests/map_fixture.py +56 -0
  19. package/skills/test-weigh-in/tests/pt_repo.py +46 -0
  20. package/skills/test-weigh-in/tests/red_repo.py +44 -0
  21. package/skills/test-weigh-in/tests/rule_repo.py +208 -0
  22. package/skills/test-weigh-in/tests/rules_fixture.py +65 -0
  23. package/skills/test-weigh-in/tests/smell_repo.py +138 -0
  24. package/skills/test-weigh-in/tests/test_brittleness.py +75 -0
  25. package/skills/test-weigh-in/tests/test_brittleness_history.py +168 -0
  26. package/skills/test-weigh-in/tests/test_coverage_run.py +201 -0
  27. package/skills/test-weigh-in/tests/test_coverage_value.py +76 -0
  28. package/skills/test-weigh-in/tests/test_dashboard_map.py +20 -0
  29. package/skills/test-weigh-in/tests/test_interpreters.py +115 -0
  30. package/skills/test-weigh-in/tests/test_kill_matrix.py +126 -0
  31. package/skills/test-weigh-in/tests/test_maintainability_smells.py +113 -0
  32. package/skills/test-weigh-in/tests/test_mutation_recovery.py +67 -0
  33. package/skills/test-weigh-in/tests/test_mutation_sampling.py +53 -0
  34. package/skills/test-weigh-in/tests/test_mutation_score.py +140 -0
  35. package/skills/test-weigh-in/tests/test_mutation_stale.py +30 -0
  36. package/skills/test-weigh-in/tests/test_mutmut_contract.py +43 -0
  37. package/skills/test-weigh-in/tests/test_ruff_pt_smells.py +45 -0
  38. package/skills/test-weigh-in/tests/test_runs.py +175 -0
  39. package/skills/test-weigh-in/tests/test_score.py +26 -0
  40. package/skills/test-weigh-in/tests/test_scoring.py +154 -0
  41. package/skills/test-weigh-in/tests/test_smell_rules.py +96 -0
  42. package/skills/test-weigh-in/tests/test_smells.py +71 -0
  43. package/skills/test-weigh-in/tests/test_walking_skeleton.py +91 -0
  44. package/skills/test-weigh-in/tests/testdata/default_repo/demo/__init__.py +0 -0
  45. package/skills/test-weigh-in/tests/testdata/default_repo/demo/board.py +2 -0
  46. package/skills/test-weigh-in/tests/testdata/default_repo/demo/config.py +2 -0
  47. package/skills/test-weigh-in/tests/testdata/default_repo/pyproject.toml +8 -0
  48. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_board.py +19 -0
  49. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_config.py +19 -0
  50. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_parser.py +19 -0
  51. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_render.py +19 -0
  52. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_report.py +17 -0
  53. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_session.py +19 -0
  54. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_store.py +17 -0
  55. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_sync.py +17 -0
  56. package/skills/test-weigh-in/tests/testdata/default_repo/uv.lock +1 -0
  57. package/skills/test-weigh-in/weigh.py +133 -0
  58. package/skills/test-weigh-in/weigh_coverage.py +154 -0
  59. package/skills/test-weigh-in/weigh_dashboard.py +72 -0
  60. package/skills/test-weigh-in/weigh_env.py +112 -0
  61. package/skills/test-weigh-in/weigh_git.py +119 -0
  62. package/skills/test-weigh-in/weigh_inventory.py +49 -0
  63. package/skills/test-weigh-in/weigh_mutation.py +190 -0
  64. package/skills/test-weigh-in/weigh_pytest_plugin.py +56 -0
  65. package/skills/test-weigh-in/weigh_ruff.py +22 -0
  66. package/skills/test-weigh-in/weigh_rules.py +65 -0
  67. package/skills/test-weigh-in/weigh_runs.py +173 -0
  68. package/skills/test-weigh-in/weigh_score.py +80 -0
  69. package/skills/test-weigh-in/weigh_smells.py +355 -0
  70. package/skills/test-weigh-in/weigh_snapshot.py +49 -0
  71. package/skills-manifest.json +11 -5
@@ -0,0 +1,91 @@
1
+ import pytest
2
+
3
+ from fixture_repo import build_repo, git, load, short_sha, site_files, snapshots, weigh
4
+
5
+
6
+ def ok(result):
7
+ assert result.returncode == 0, result.stdout + result.stderr
8
+
9
+
10
+ def one_snapshot(home, key):
11
+ (snap,) = snapshots(home, key)
12
+ return load(snap)
13
+
14
+
15
+ def test_uv_repo_measured_without_touching_it(tmp_path, home, cache):
16
+ repo = build_repo(tmp_path / "demo")
17
+ before = site_files(repo)
18
+ result = weigh(repo, home, cache=cache)
19
+ ok(result)
20
+ assert len(snapshots(home, "github.com/jesdi/demo")) == 1
21
+ assert git(repo, "status", "--porcelain") == ""
22
+ assert site_files(repo) == before
23
+
24
+
25
+ def test_inventory_counts_lines_and_runtime(run, home):
26
+ _, result = run(test_lines=6000, source_lines=4000)
27
+ ok(result)
28
+ inv = one_snapshot(home, "github.com/jesdi/demo")["inventory"]
29
+ assert (inv["tests"], inv["test_files"], inv["test_lines"], inv["source_lines"]) == (40, 8, 6000, 4000)
30
+ assert inv["runtime_seconds"] == pytest.approx(45)
31
+
32
+
33
+ def test_pytest_args_select_tests_and_are_recorded(run, home):
34
+ _, result = run("--pytest-args", "-m 'not e2e'")
35
+ ok(result)
36
+ snap = one_snapshot(home, "github.com/jesdi/demo")
37
+ assert snap["inventory"]["tests"] == 30
38
+ assert snap["pytest_args"] == "-m 'not e2e'"
39
+
40
+
41
+ def test_repo_pytest_version_is_used_not_the_overlays(run, home):
42
+ _, result = run(pytest_version="7.4.4")
43
+ ok(result)
44
+ assert one_snapshot(home, "github.com/jesdi/demo")["pytest_version"].startswith("7.4")
45
+
46
+
47
+ @pytest.mark.parametrize(
48
+ "origin, name, key",
49
+ [
50
+ ("git@github.com:jesdi/api.git", "api", "github.com/jesdi/api"),
51
+ ("https://github.com/acme/api.git", "api", "github.com/acme/api"),
52
+ ("git@github.com:a-b/c.git", "x", "github.com/a-b/c"),
53
+ ("git@github.com:a/b-c.git", "y", "github.com/a/b-c"),
54
+ ("git@gitlab.com:jesdi/api.git", "y", "gitlab.com/jesdi/api"),
55
+ (None, "scratch", "local/scratch"),
56
+ ],
57
+ )
58
+ def test_repo_key_comes_from_origin(run, home, origin, name, key):
59
+ _, result = run(origin=origin, name=name)
60
+ ok(result)
61
+ assert len(snapshots(home, key)) == 1
62
+
63
+
64
+ def test_second_run_adds_a_snapshot_and_keeps_the_first(run, home, cache):
65
+ repo, result = run()
66
+ ok(result)
67
+ (first,) = snapshots(home, "github.com/jesdi/demo")
68
+ content = first.read_bytes()
69
+ ok(weigh(repo, home, cache=cache))
70
+ assert len(snapshots(home, "github.com/jesdi/demo")) == 2
71
+ assert first.read_bytes() == content
72
+
73
+
74
+ def test_dirty_tree_is_recorded(tmp_path, home, cache):
75
+ repo = build_repo(tmp_path / "demo")
76
+ (repo / "demo" / "board.py").write_text("def render(n):\n return str(n) + ''\n")
77
+ ok(weigh(repo, home, cache=cache))
78
+ snap = one_snapshot(home, "github.com/jesdi/demo")
79
+ assert git(repo, "rev-parse", "HEAD").startswith(snap["commit"])
80
+ assert snap["commit"] == short_sha(repo)
81
+ assert snap["dirty"] is True
82
+
83
+
84
+ def test_same_second_runs_get_suffixed_names(run, home, cache):
85
+ now = "2026-01-02T03:04:05Z"
86
+ repo, result = run(now=now)
87
+ ok(result)
88
+ ok(weigh(repo, home, cache=cache, now=now))
89
+ names = sorted(p.name for p in snapshots(home, "github.com/jesdi/demo"))
90
+ stem = f"20260102T030405Z_{short_sha(repo)}"
91
+ assert names == sorted([stem + ".json", stem + "-2.json"])
@@ -0,0 +1,2 @@
1
+ def render(n):
2
+ return str(n)
@@ -0,0 +1,2 @@
1
+ def load():
2
+ return {}
@@ -0,0 +1,8 @@
1
+ [project]
2
+ name = "demo"
3
+ version = "0.0.0"
4
+ requires-python = ">=3.10"
5
+ [tool.pytest.ini_options]
6
+ pythonpath = ["."]
7
+ addopts = "-p fakeclock"
8
+ markers = ["e2e: slow end-to-end test"]
@@ -0,0 +1,19 @@
1
+ import pytest
2
+ from demo import board, config
3
+ @pytest.mark.e2e
4
+ def test_board_0():
5
+ assert board.render(0) == "0"
6
+ assert config.load() == {}
7
+ @pytest.mark.e2e
8
+ def test_board_1():
9
+ assert board.render(1) == "1"
10
+ assert config.load() == {}
11
+ def test_board_2():
12
+ assert board.render(2) == "2"
13
+ assert config.load() == {}
14
+ def test_board_3():
15
+ assert board.render(3) == "3"
16
+ assert config.load() == {}
17
+ def test_board_4():
18
+ assert board.render(4) == "4"
19
+ assert config.load() == {}
@@ -0,0 +1,19 @@
1
+ import pytest
2
+ from demo import board, config
3
+ @pytest.mark.e2e
4
+ def test_config_0():
5
+ assert board.render(0) == "0"
6
+ assert config.load() == {}
7
+ @pytest.mark.e2e
8
+ def test_config_1():
9
+ assert board.render(1) == "1"
10
+ assert config.load() == {}
11
+ def test_config_2():
12
+ assert board.render(2) == "2"
13
+ assert config.load() == {}
14
+ def test_config_3():
15
+ assert board.render(3) == "3"
16
+ assert config.load() == {}
17
+ def test_config_4():
18
+ assert board.render(4) == "4"
19
+ assert config.load() == {}
@@ -0,0 +1,19 @@
1
+ import pytest
2
+ from demo import board, config
3
+ @pytest.mark.e2e
4
+ def test_parser_0():
5
+ assert board.render(0) == "0"
6
+ assert config.load() == {}
7
+ @pytest.mark.e2e
8
+ def test_parser_1():
9
+ assert board.render(1) == "1"
10
+ assert config.load() == {}
11
+ def test_parser_2():
12
+ assert board.render(2) == "2"
13
+ assert config.load() == {}
14
+ def test_parser_3():
15
+ assert board.render(3) == "3"
16
+ assert config.load() == {}
17
+ def test_parser_4():
18
+ assert board.render(4) == "4"
19
+ assert config.load() == {}
@@ -0,0 +1,19 @@
1
+ import pytest
2
+ from demo import board, config
3
+ @pytest.mark.e2e
4
+ def test_render_0():
5
+ assert board.render(0) == "0"
6
+ assert config.load() == {}
7
+ @pytest.mark.e2e
8
+ def test_render_1():
9
+ assert board.render(1) == "1"
10
+ assert config.load() == {}
11
+ def test_render_2():
12
+ assert board.render(2) == "2"
13
+ assert config.load() == {}
14
+ def test_render_3():
15
+ assert board.render(3) == "3"
16
+ assert config.load() == {}
17
+ def test_render_4():
18
+ assert board.render(4) == "4"
19
+ assert config.load() == {}
@@ -0,0 +1,17 @@
1
+ import pytest
2
+ from demo import board, config
3
+ def test_report_0():
4
+ assert board.render(0) == "0"
5
+ assert config.load() == {}
6
+ def test_report_1():
7
+ assert board.render(1) == "1"
8
+ assert config.load() == {}
9
+ def test_report_2():
10
+ assert board.render(2) == "2"
11
+ assert config.load() == {}
12
+ def test_report_3():
13
+ assert board.render(3) == "3"
14
+ assert config.load() == {}
15
+ def test_report_4():
16
+ assert board.render(4) == "4"
17
+ assert config.load() == {}
@@ -0,0 +1,19 @@
1
+ import pytest
2
+ from demo import board, config
3
+ @pytest.mark.e2e
4
+ def test_session_0():
5
+ assert board.render(0) == "0"
6
+ assert config.load() == {}
7
+ @pytest.mark.e2e
8
+ def test_session_1():
9
+ assert board.render(1) == "1"
10
+ assert config.load() == {}
11
+ def test_session_2():
12
+ assert board.render(2) == "2"
13
+ assert config.load() == {}
14
+ def test_session_3():
15
+ assert board.render(3) == "3"
16
+ assert config.load() == {}
17
+ def test_session_4():
18
+ assert board.render(4) == "4"
19
+ assert config.load() == {}
@@ -0,0 +1,17 @@
1
+ import pytest
2
+ from demo import board, config
3
+ def test_store_0():
4
+ assert board.render(0) == "0"
5
+ assert config.load() == {}
6
+ def test_store_1():
7
+ assert board.render(1) == "1"
8
+ assert config.load() == {}
9
+ def test_store_2():
10
+ assert board.render(2) == "2"
11
+ assert config.load() == {}
12
+ def test_store_3():
13
+ assert board.render(3) == "3"
14
+ assert config.load() == {}
15
+ def test_store_4():
16
+ assert board.render(4) == "4"
17
+ assert config.load() == {}
@@ -0,0 +1,17 @@
1
+ import pytest
2
+ from demo import board, config
3
+ def test_sync_0():
4
+ assert board.render(0) == "0"
5
+ assert config.load() == {}
6
+ def test_sync_1():
7
+ assert board.render(1) == "1"
8
+ assert config.load() == {}
9
+ def test_sync_2():
10
+ assert board.render(2) == "2"
11
+ assert config.load() == {}
12
+ def test_sync_3():
13
+ assert board.render(3) == "3"
14
+ assert config.load() == {}
15
+ def test_sync_4():
16
+ assert board.render(4) == "4"
17
+ assert config.load() == {}
@@ -0,0 +1,133 @@
1
+ """Weigh a repo's test suite: `weigh.py <repo-path> [--pytest-args "..."]`."""
2
+ import argparse
3
+ import signal
4
+ import sys
5
+ import webbrowser
6
+ from pathlib import Path
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
9
+
10
+ from weigh_env import SetupError, build_overlay, check_versions, find_interpreter
11
+ from weigh_coverage import branch_percent, overlaps, per_test, test_file_sources, unique_coverage, valued
12
+ from weigh_git import brittle_percent, brittleness, is_repo
13
+ from weigh_dashboard import summary, write_dashboard
14
+ from weigh_inventory import count_lines
15
+ from weigh_rules import RulesError, load as load_rules
16
+ from weigh_ruff import violations
17
+ from weigh_runs import aggregate, coverage_run, plain_run
18
+ from weigh_smells import find_smells, smell_values
19
+ from weigh_mutation import refuse_dirty, refuse_red, remove_stale, score as mutation_score
20
+ from weigh_score import feedback_values, kill_matrix, score
21
+ from weigh_snapshot import commit_state, home_dir, write_snapshot
22
+
23
+
24
+ def main(argv=None):
25
+ parser = argparse.ArgumentParser(prog="weigh.py")
26
+ parser.add_argument("repo_path")
27
+ parser.add_argument("--pytest-args", default="")
28
+ parser.add_argument("--python")
29
+ parser.add_argument("--mutation", action="store_true")
30
+ parser.add_argument("--matrix-per-function", default="3", type=lambda v: None if v == "all" else int(v))
31
+ parser.add_argument("--no-open", action="store_true")
32
+ args = parser.parse_args(argv)
33
+ repo = Path(args.repo_path).resolve()
34
+ try:
35
+ rules = load_rules()
36
+ except (RulesError, OSError, KeyError) as e:
37
+ print(f"weigh.py: {e}", file=sys.stderr)
38
+ return 2
39
+ try:
40
+ if args.mutation:
41
+ remove_stale() # before any refusal: an interrupted run's worktree never outlives the next start
42
+ if not is_repo(repo):
43
+ raise SetupError("--mutation needs a git repository with a commit")
44
+ refuse_dirty(repo)
45
+ home = home_dir(repo)
46
+ python = find_interpreter(repo, args.python)
47
+ check_versions(python)
48
+ overlay = build_overlay(python)
49
+ run = plain_run(python, repo, overlay, args.pytest_args)
50
+ if args.mutation:
51
+ refuse_red(run["cases"])
52
+ eligible = {n for n, t in aggregate(run["cases"]).items() if t["outcome"] == "passed"}
53
+ cov = coverage_run(python, repo, overlay, args.pytest_args, eligible)
54
+ mutation = mutation_score(python, repo, overlay, args.matrix_per_function) if args.mutation else None
55
+ except SetupError as e:
56
+ print(f"weigh.py: {e}", file=sys.stderr)
57
+ return 1
58
+ tests = aggregate(run["cases"])
59
+ commit, dirty = commit_state(repo)
60
+ inventory = {
61
+ "tests": len(tests),
62
+ "cases": len(run["cases"]),
63
+ **count_lines(repo),
64
+ "runtime_seconds": max(run["runtime_seconds"], sum(c["duration"] for c in run["cases"].values())),
65
+ }
66
+ values = feedback_values(tests, inventory["runtime_seconds"])
67
+ if mutation is not None:
68
+ values["mutation_score"] = mutation["score"]
69
+ values["pseudo_tested_functions"] = mutation["pseudo_tested"]
70
+ found, clusters = find_smells(repo, tests, violations(repo, rules.get("ruff", {}).get("pt", [])))
71
+ for node, info in found.items():
72
+ tests[node].update(info)
73
+ if inventory["source_lines"]:
74
+ values["test_source_ratio"] = inventory["test_lines"] / inventory["source_lines"]
75
+ # failing, erroring and skipped tests cost (runtime, lines, smells) but give no value: no coverage, overlap or uniqueness
76
+ covered = per_test(cov["report"], cov["arcs"], repo)
77
+ cov_tests = aggregate(cov["cases"])
78
+ for node, test in tests.items():
79
+ test.update(covered.get(node, {"coverage": {}, "branches": {}}))
80
+ test["flaky"] = cov_tests.get(node, {}).get("outcome") != test["outcome"]
81
+ # value metrics count only tests that passed in both runs
82
+ passing = valued(tests)
83
+ unique = unique_coverage(passing)
84
+ for node, test in tests.items():
85
+ test["unique_coverage"] = unique.get(node, 0)
86
+ if branch_percent(cov["value_report"]) is not None:
87
+ values["branch_coverage"] = branch_percent(cov["value_report"])
88
+ if mutation is not None: # flags tests before the metrics they change are computed
89
+ values.update(kill_matrix(tests, passing, mutation))
90
+ values.update(smell_values(tests))
91
+ if passing:
92
+ # a count-based metric is a percentage of all tests (req 17); only valued tests can lack unique coverage, and an
93
+ # insufficient-evidence test counts in no Economy metric
94
+ values["no_unique_coverage"] = 100 * sum(not u and not tests[n].get("insufficient_evidence") for n, u in unique.items()) / len(tests)
95
+ test_files = brittleness(repo, test_file_sources(tests))
96
+ if (percent := brittle_percent(test_files)) is not None:
97
+ values["brittle_test_files"] = percent
98
+ metrics, pillars = score(rules, values, red=len(passing) < len(tests))
99
+ data = {
100
+ "commit": commit,
101
+ "dirty": dirty,
102
+ "pytest_args": args.pytest_args,
103
+ "pytest_version": run["pytest_version"],
104
+ "python_version": run["python_version"],
105
+ "rules": {"version": rules["version"], "sha256": rules["sha256"]},
106
+ "inventory": inventory,
107
+ "metrics": metrics,
108
+ "pillars": pillars,
109
+ "mutation_settings": {"mutation": args.mutation, "matrix_per_function": "all" if args.matrix_per_function is None else args.matrix_per_function},
110
+ **({"mutation": {k: mutation[k] for k in ("sampled", "mutants", "matrix")}} if mutation is not None else {}),
111
+ "tests": tests,
112
+ "test_files": test_files,
113
+ "overlaps": overlaps(passing),
114
+ "clusters": clusters,
115
+ }
116
+ path = write_snapshot(home, data)
117
+ dashboard = write_dashboard(home, data, rules)
118
+ print(summary(data, rules, path, dashboard))
119
+ if not args.no_open:
120
+ webbrowser.open(dashboard.as_uri())
121
+ return 0
122
+
123
+
124
+ def _terminate(signum, frame):
125
+ raise KeyboardInterrupt
126
+
127
+
128
+ if __name__ == "__main__":
129
+ signal.signal(signal.SIGTERM, _terminate)
130
+ try:
131
+ sys.exit(main())
132
+ except KeyboardInterrupt: # the temporary worktree is removed on the way out
133
+ sys.exit(130)
@@ -0,0 +1,154 @@
1
+ """Read `coverage json --show-contexts` into per-test coverage, and derive unique coverage and overlaps."""
2
+ import os
3
+ import re
4
+ from itertools import combinations
5
+
6
+ from weigh_inventory import is_test
7
+
8
+ OVERLAP_JACCARD = 0.9
9
+
10
+
11
+ # Case outcomes that pass: an expected failure aggregates into a passing test, so its coverage counts like a pass.
12
+ PASSING = ("passed", "xfail")
13
+
14
+
15
+ def contexts_regex(cases, eligible=None):
16
+ """Matches the call context of every passing case, of the eligible tests only when given."""
17
+ passing = [re.escape(f"{node}|call") for node, c in cases.items()
18
+ if c["outcome"] in PASSING and (eligible is None or node.split("[", 1)[0] in eligible)]
19
+ return "^(" + "|".join(passing) + ")$" if passing else "(?!)"
20
+
21
+
22
+ def _relative(path, repo):
23
+ rel = os.path.relpath(path, repo) if os.path.isabs(path) else path
24
+ return None if is_test(rel) else rel
25
+
26
+
27
+ def per_test(report, arcs, repo):
28
+ """{test node id: {"coverage": {path: sorted lines}, "branches": {path: sorted [from, to]}}}, paths repo-relative,
29
+ from the call contexts; setup, teardown and collection are not the test's."""
30
+ found = {}
31
+
32
+ def add(ctx, kind, rel, item):
33
+ if ctx.endswith("|call"):
34
+ node = ctx[: -len("|call")].split("[", 1)[0]
35
+ found.setdefault(node, {"coverage": {}, "branches": {}})[kind].setdefault(rel, set()).add(item)
36
+
37
+ branches = {}
38
+ for path, info in report["files"].items():
39
+ if rel := _relative(path, repo):
40
+ branches[rel] = {tuple(a) for a in info.get("executed_branches", [])}
41
+ for line, contexts in info.get("contexts", {}).items():
42
+ for ctx in contexts:
43
+ add(ctx, "coverage", rel, int(line))
44
+ for ctx, files in arcs.items():
45
+ for path, file_arcs in files.items():
46
+ rel = _relative(path, repo)
47
+ for arc in map(tuple, file_arcs):
48
+ if arc in branches.get(rel, ()):
49
+ add(ctx, "branches", rel, arc)
50
+ return {node: {kind: {rel: sorted(items) for rel, items in files.items()} for kind, files in test.items()}
51
+ for node, test in found.items()}
52
+
53
+
54
+ def branch_percent(report):
55
+ """Branch arcs only: percent_covered mixes statements in. Code that ran without a branch misses none (100); with no
56
+ code run at all, the metric is not measured."""
57
+ totals = report["totals"]
58
+ if not totals["num_branches"]:
59
+ return 100.0 if report["files"] else None
60
+ return 100 * totals["covered_branches"] / totals["num_branches"]
61
+
62
+
63
+ def valued(tests):
64
+ """The tests that give value: passed in the plain run and the same under coverage, so not flaky."""
65
+ return {node: test for node, test in tests.items() if test["outcome"] == "passed" and not test["flaky"]}
66
+
67
+
68
+ def _items(test):
69
+ """The lines and branches a test covers."""
70
+ return ({(rel, n) for rel, lines in test.get("coverage", {}).items() for n in lines}
71
+ | {(rel, tuple(arc)) for rel, arcs in test.get("branches", {}).items() for arc in arcs})
72
+
73
+
74
+ def unique_coverage(tests):
75
+ """{node: lines and branches covered by that test and no other}, over the tests given."""
76
+ sets = {node: _items(t) for node, t in tests.items()}
77
+ seen = {}
78
+ for items in sets.values():
79
+ for item in items:
80
+ seen[item] = seen.get(item, 0) + 1
81
+ return {node: sum(seen[item] == 1 for item in items) for node, items in sets.items()}
82
+
83
+
84
+ def overlaps(tests):
85
+ # ponytail: all pairs, quadratic in the passing tests; bucket by file if suites of thousands get slow
86
+ sets = {node: items for node, t in tests.items() if (items := _items(t))}
87
+ found = []
88
+ for a, b in combinations(sets, 2):
89
+ jaccard = len(sets[a] & sets[b]) / len(sets[a] | sets[b])
90
+ if jaccard >= OVERLAP_JACCARD:
91
+ found.append({"tests": [a, b], "jaccard": jaccard})
92
+ return found
93
+
94
+
95
+ MAP_SHARE = 0.2
96
+
97
+
98
+ def test_file_sources(tests):
99
+ """{test file: sorted source files holding at least 20% of the lines its tests cover}."""
100
+ lines = {}
101
+ for node, t in tests.items():
102
+ for rel, covered in t.get("coverage", {}).items():
103
+ lines.setdefault(node.split("::", 1)[0], {}).setdefault(rel, set()).update(covered)
104
+ mapped = {}
105
+ for file, per_source in lines.items():
106
+ total = sum(map(len, per_source.values()))
107
+ mapped[file] = sorted(rel for rel, n in per_source.items() if len(n) >= MAP_SHARE * total)
108
+ return mapped
109
+
110
+
111
+ MAP_SIMILAR = 0.6
112
+
113
+
114
+ def _axis(b, others, n):
115
+ """Top eigenvector of the double-centred matrix b by power iteration from a fixed start, orthogonal to `others`."""
116
+ v = [1.0 + i % 7 for i in range(n)]
117
+ for _ in range(100):
118
+ for o in others:
119
+ d = sum(x * y for x, y in zip(v, o))
120
+ v = [x - d * y for x, y in zip(v, o)]
121
+ w = [sum(b[i][j] * v[j] for j in range(n)) for i in range(n)]
122
+ norm = sum(x * x for x in w) ** 0.5
123
+ if not norm:
124
+ return [0.0] * n
125
+ v = [x / norm for x in w]
126
+ lam = sum(sum(b[i][j] * v[j] for j in range(n)) * v[i] for i in range(n))
127
+ return [x * max(lam, 0) ** 0.5 for x in v]
128
+
129
+
130
+ def similarity_map(tests):
131
+ """Dots for the map, one per test given: [{test, x, y, similar: [[other, jaccard >= 0.6]]}], x and y in 0..1.
132
+ Placement is classical MDS of 1 - similarity from a fixed start, so it is the same on every load."""
133
+ # ponytail: dense n x n, fine for hundreds of tests; sample or bucket if suites of thousands get slow
134
+ nodes = list(tests)
135
+ sets = [_items(tests[n]) for n in nodes]
136
+ n = len(nodes)
137
+ if not n:
138
+ return []
139
+ sim = [[(len(a & b) / len(a | b) if a | b else 0.0) if i != j else 1.0 for j, b in enumerate(sets)] for i, a in enumerate(sets)]
140
+ sq = [[(1 - s) ** 2 for s in row] for row in sim]
141
+ row_mean = [sum(r) / n for r in sq]
142
+ total = sum(row_mean) / n
143
+ b = [[-0.5 * (sq[i][j] - row_mean[i] - row_mean[j] + total) for j in range(n)] for i in range(n)]
144
+ x = _axis(b, [], n)
145
+ y = _axis(b, [[v / (sum(u * u for u in x) ** 0.5 or 1) for v in x]], n)
146
+
147
+ def unit(axis):
148
+ lo, hi = min(axis, default=0), max(axis, default=0)
149
+ return [(v - lo) / (hi - lo) if hi > lo else 0.5 for v in axis]
150
+
151
+ xs, ys = unit(x), unit(y)
152
+ return [{"test": node, "x": xs[i], "y": ys[i],
153
+ "similar": [[nodes[j], sim[i][j]] for j in range(n) if j != i and sim[i][j] >= MAP_SIMILAR]}
154
+ for i, node in enumerate(nodes)]
@@ -0,0 +1,72 @@
1
+ """Render dashboard.html from the template and print the chat summary."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ from weigh_coverage import similarity_map, valued
6
+ from weigh_score import display
7
+ from weigh_smells import PILLAR_SMELLS, pillar_smells, worst_tests
8
+
9
+ TEMPLATE = Path(__file__).resolve().parent / "dashboard.html"
10
+
11
+
12
+ def inventory_line(inv):
13
+ return (f"{inv['tests']} tests ({inv['cases']} cases) in {inv['test_files']} files, "
14
+ f"{inv['test_lines']} test lines, {inv['source_lines']} source lines, {inv['runtime_seconds']:.1f} s")
15
+
16
+
17
+ def _failing(tests):
18
+ return sum(t["outcome"] == "failed" for t in tests.values())
19
+
20
+
21
+ def _flaky(tests):
22
+ return sum(t.get("flaky", False) for t in tests.values())
23
+
24
+
25
+ def _slow(rules):
26
+ """A test is slow when it takes longer than the target of the p95 test duration."""
27
+ return rules["pillars"]["feedback"]["metrics"]["p95_duration"]["target"]
28
+
29
+
30
+ def write_dashboard(home, data, rules):
31
+ failing = _failing(data["tests"])
32
+ page = {
33
+ "banner": f"{failing} tests are failing" if failing > 1 else "1 test is failing" if failing else None,
34
+ "skipped": [n for n, t in data["tests"].items() if t["outcome"] == "skipped"],
35
+ "insufficient": [n for n, t in data["tests"].items() if t.get("insufficient_evidence")],
36
+ "overlaps": data.get("overlaps", []),
37
+ "map": [{**d, "runtime": data["tests"][d["test"]]["duration"], "unique": data["tests"][d["test"]].get("unique_coverage", 0)}
38
+ for d in similarity_map(valued(data["tests"]))],
39
+ "inventory": inventory_line(data["inventory"]),
40
+ "pillars": [
41
+ {"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"]],
43
+ "total": len(p["metrics"]),
44
+ "worst": worst_tests(data["tests"], k, _slow(rules)),
45
+ "smells": pillar_smells(data["tests"], PILLAR_SMELLS.get(k, ()))}
46
+ for k, p in rules["pillars"].items()
47
+ ],
48
+ }
49
+ # "</" and U+2028/9 would end the script block or the literal early
50
+ blob = json.dumps(page).replace("</", "<\\/").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
51
+ path = home / "dashboard.html"
52
+ path.write_text(TEMPLATE.read_text().replace("__DATA__", blob))
53
+ return path
54
+
55
+
56
+ def summary(data, rules, snapshot, dashboard):
57
+ lines = [inventory_line(data["inventory"])]
58
+ for k, p in rules["pillars"].items():
59
+ s = data["pillars"][k]
60
+ shown = "not measured" if s["score"] is None else str(display(s["score"]))
61
+ lines.append(f"{p['name']}: {shown}" + (" (partial)" if s["partial"] else ""))
62
+ failing, flaky = _failing(data["tests"]), _flaky(data["tests"])
63
+ if failing:
64
+ lines.append(f"Warning: {failing} tests are failing" if failing > 1 else "Warning: 1 test is failing")
65
+ if flaky:
66
+ lines.append(f"Warning: {flaky} flaky tests" if flaky > 1 else "Warning: 1 flaky test")
67
+ scored = {k: p["score"] for k, p in data["pillars"].items() if p["score"] is not None}
68
+ if scored:
69
+ lowest = min(scored, key=scored.get)
70
+ worst = worst_tests(data["tests"], lowest, _slow(rules), 3)
71
+ lines += [f"Worst tests ({rules['pillars'][lowest]['name']}):", *(f" {w['test']} ({w['reason']})" for w in worst)]
72
+ return "\n".join([*lines, f"Snapshot: {snapshot}", f"Dashboard: {dashboard}"])