@jesdi/skills 0.0.81 → 0.0.82

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 +156 -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 +70 -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 +134 -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,134 @@
1
+ """The plain and coverage runs: pytest through the target's interpreter, cases aggregated into tests."""
2
+ import json
3
+ import os
4
+ import shlex
5
+ import subprocess
6
+ import tempfile
7
+
8
+ from weigh_coverage import contexts_regex
9
+ from weigh_env import SetupError
10
+ from weigh_inventory import TEST_GLOBS
11
+ from weigh_snapshot import git
12
+
13
+ PYTEST = ["-m", "pytest", "-p", "no:randomly", "-p", "no:cacheprovider", "-p", "weigh_pytest_plugin"]
14
+ # Paths inside the repo that the coverage run leaves out: environments, and the test files.
15
+ OMIT = (".venv/**", "venv/**") + TEST_GLOBS
16
+ # pytest exit codes of a run that executed its tests: all passed, some failed.
17
+ RAN = (0, 1)
18
+
19
+
20
+ def _pytest(python, repo, overlay, pytest_args, tmp, runner=(), env=None):
21
+ """One pytest run; the plugin sends pytest's file writers to tmp, and a run that still changed the repo is refused."""
22
+ args = shlex.split(pytest_args)
23
+ # --debug opens its log before any plugin is configured, so it cannot be redirected.
24
+ if any(a.split("=", 1)[0] == "--debug" for a in args + shlex.split(os.environ.get("PYTEST_ADDOPTS", ""))):
25
+ raise SetupError("--pytest-args: --debug writes files and would change the target repo")
26
+ out = os.path.join(tmp, "cases.json")
27
+ env = {**os.environ, **(env or {}), "PYTHONPATH": str(overlay), "PYTHONDONTWRITEBYTECODE": "1",
28
+ "TEST_WEIGH_IN_OUT": out, "TEST_WEIGH_IN_ARTIFACTS": tmp}
29
+ before = git(repo, "status", "--porcelain")
30
+ proc = subprocess.run([str(python), *runner, *PYTEST, *args], cwd=repo, env=env, capture_output=True, text=True)
31
+ if git(repo, "status", "--porcelain") != before:
32
+ raise SetupError("pytest changed the target repo; drop the --pytest-args or configuration that writes files:\n"
33
+ + git(repo, "status", "--porcelain"))
34
+ return proc, out
35
+
36
+
37
+ def plain_run(python, repo, overlay, pytest_args):
38
+ with tempfile.TemporaryDirectory() as tmp:
39
+ proc, out = _pytest(python, repo, overlay, pytest_args, tmp)
40
+ if proc.returncode not in RAN or not os.path.exists(out):
41
+ raise SetupError(f"pytest exited {proc.returncode} without running the tests:\n" + proc.stdout + proc.stderr)
42
+ with open(out) as f:
43
+ return json.load(f)
44
+
45
+
46
+ def aggregate(cases):
47
+ """Group cases by node id without [params]; durations sum, any failure wins, all-skipped is skipped."""
48
+ tests = {}
49
+ for node, case in cases.items():
50
+ tests.setdefault(node.split("[", 1)[0], []).append(case)
51
+ result = {}
52
+ for node, group in tests.items():
53
+ outcomes = {c["outcome"] for c in group}
54
+ if outcomes & {"failed", "error"}:
55
+ outcome = "failed"
56
+ elif outcomes == {"skipped"}:
57
+ outcome = "skipped"
58
+ else:
59
+ outcome = "passed"
60
+ result[node] = {"outcome": outcome, "duration": sum(c["duration"] for c in group), "cases": len(group)}
61
+ return result
62
+
63
+
64
+ def coverage_run(python, repo, overlay, pytest_args, eligible):
65
+ """Pytest under branch coverage with a context per test phase, as a dict: cases; report, the coverage json report of
66
+ the passing cases; value_report, the same of the eligible tests that also passed under coverage; arcs, the arcs of
67
+ each passing case's call context. A coverage report that fails is an error, so no metric comes from missing data."""
68
+ with tempfile.TemporaryDirectory() as tmp:
69
+ rc = os.path.join(tmp, "rc")
70
+ open(rc, "w").close()
71
+ data = os.path.join(tmp, "data")
72
+ # test files are the cost being weighed, not the code under test; anchored in the repo, so a folder
73
+ # named tests above it excludes nothing
74
+ omit = ",".join(f"{repo}/**/{p}" for p in OMIT)
75
+ run, out = _pytest(python, repo, overlay, pytest_args, tmp, env={"COVERAGE_RCFILE": rc},
76
+ runner=["-m", "coverage", "run", "--branch", f"--data-file={data}", f"--source={repo}", f"--omit={omit}"])
77
+ if run.returncode not in RAN or not os.path.exists(out):
78
+ raise SetupError(f"pytest under coverage exited {run.returncode} without running the tests:\n" + run.stdout + run.stderr)
79
+ with open(out) as f:
80
+ cases = json.load(f)["cases"]
81
+ eligible = eligible & {n for n, t in aggregate(cases).items() if t["outcome"] == "passed"}
82
+ env = {**os.environ, "PYTHONPATH": str(overlay), "PYTHONDONTWRITEBYTECODE": "1", "COVERAGE_RCFILE": rc}
83
+ coverage = lambda *a: subprocess.run([str(python), *a], cwd=repo, env=env, capture_output=True, text=True)
84
+ passing = contexts_regex(cases)
85
+ return {"cases": cases,
86
+ "report": _report(coverage, rc, data, os.path.join(tmp, "report.json"), passing),
87
+ "value_report": _report(coverage, rc, data, os.path.join(tmp, "eligible.json"), contexts_regex(cases, eligible)),
88
+ "arcs": _arcs(coverage, data, os.path.join(tmp, "arcs.json"), passing)}
89
+
90
+
91
+ def _report(coverage, rc, data, out, regex):
92
+ # coverage splits a config list at each comma and expands $NAME in it: write both as regex escapes that
93
+ # match the same characters (re.escape writes a literal $ as \$)
94
+ with open(rc, "w") as f:
95
+ f.write("[report]\ncontexts = " + regex.replace(",", r"\x2c").replace(r"\$", r"\x24") + "\n")
96
+ proc = coverage("-m", "coverage", "json", "--show-contexts", f"--data-file={data}", "-o", out, "-q")
97
+ if "No data to report" in proc.stdout + proc.stderr: # no source file ran at all: measured, and empty
98
+ return {"files": {}, "totals": {"covered_branches": 0, "num_branches": 0}}
99
+ if proc.returncode or not os.path.exists(out):
100
+ raise SetupError(f"coverage json exited {proc.returncode}:\n" + proc.stdout + proc.stderr)
101
+ with open(out) as f:
102
+ return json.load(f)
103
+
104
+
105
+ # Runs in the target's interpreter: coverage json has per-context lines but not per-context arcs.
106
+ # ponytail: one query per context and file; read the data file's arc table in one query if suites of thousands get slow
107
+ ARCS = """import json, re, sys
108
+ from coverage import Coverage, CoverageData
109
+ from coverage.python import PythonFileReporter
110
+ data, regex, out = sys.argv[1:]
111
+ cov = CoverageData(basename=data)
112
+ cov.read()
113
+ # raw arcs use the physical lines the tracer saw; the report maps them to each statement's first line, so
114
+ # map them the same way or a branch of a multi-line statement matches no reported branch
115
+ loaded = Coverage(data_file=data)
116
+ loaded.load()
117
+ reporters = {}
118
+ reporter = lambda path: reporters.setdefault(path, PythonFileReporter(path, loaded))
119
+ arcs = {}
120
+ for ctx in sorted(c for c in cov.measured_contexts() if re.search(regex, c)):
121
+ cov.set_query_contexts(["^" + re.escape(ctx) + "$"])
122
+ arcs[ctx] = {path: sorted(reporter(path).translate_arcs(a)) for path in cov.measured_files() if (a := cov.arcs(path))}
123
+ with open(out, "w") as f:
124
+ json.dump(arcs, f)
125
+ """
126
+
127
+
128
+ def _arcs(coverage, data, out, regex):
129
+ """{context: {measured path: [[from, to]]}} of the contexts the regex matches."""
130
+ proc = coverage("-c", ARCS, data, regex, out)
131
+ if proc.returncode or not os.path.exists(out):
132
+ raise SetupError(f"reading the coverage arcs exited {proc.returncode}:\n" + proc.stdout + proc.stderr)
133
+ with open(out) as f:
134
+ return json.load(f)
@@ -0,0 +1,80 @@
1
+ """Logistic metric scores, weighted pillar scores and the Fast feedback metrics."""
2
+ import math
3
+
4
+
5
+ def metric_score(x, target, bad, log=False):
6
+ if log:
7
+ x, target, bad = (math.log(max(v, 1e-9)) for v in (x, target, bad))
8
+ k = 2 * math.log(9) / (target - bad)
9
+ z = -k * (x - (target + bad) / 2)
10
+ return 0.0 if z > 700 else 100 / (1 + math.exp(z))
11
+
12
+
13
+ def display(score):
14
+ return min(99, max(1, round(score)))
15
+
16
+
17
+ def feedback_values(tests, runtime):
18
+ durations = sorted((t["duration"] for t in tests.values()), reverse=True)
19
+ n = len(durations)
20
+ top = durations[: max(1, math.ceil(n / 10))] if n else []
21
+ total = sum(durations)
22
+ return {
23
+ "total_runtime": runtime,
24
+ "p95_duration": durations[min(n - 1, int(n * 0.05))] if n else 0,
25
+ "slowest_decile_share": 100 * sum(top) / total if total else 0,
26
+ "tests_over_10s": 100 * sum(d > 10 for d in durations) / n if n else 0,
27
+ }
28
+
29
+
30
+ # Metrics read from the tests that give value (coverage, its test-file mapping, the kill matrix): a red suite leaves them partial.
31
+ VALUE_METRICS = {"mutation_score", "branch_coverage", "pseudo_tested_functions", "brittle_test_files", "no_unique_coverage",
32
+ "subsumed_in_kill_matrix"}
33
+
34
+
35
+ def score(rules, values, red=False):
36
+ """Metrics {id: {value, score}} and pillars {key: {score, partial}}; unmeasured metrics are left out and the weights re-normalized.
37
+
38
+ Without the mutation tier (no mutation_score), a pillar that gives partial weights uses them, and its metrics without one do not count.
39
+ With a red suite (a test that gives no value), every pillar using a value metric is partial (req 14)."""
40
+ metrics, pillars = {}, {}
41
+ for key, pillar in rules["pillars"].items():
42
+ partial_weights = "mutation_score" not in values and any("partial_weight" in m for m in pillar["metrics"].values())
43
+ scored = []
44
+ for mid, m in pillar["metrics"].items():
45
+ if mid in values:
46
+ s = metric_score(values[mid], m["target"], m["bad"], m.get("log", False))
47
+ metrics[mid] = {"value": values[mid], "score": s}
48
+ weight = m.get("partial_weight", 0) if partial_weights else m["weight"]
49
+ if weight:
50
+ scored.append((weight, s))
51
+ weight = sum(w for w, _ in scored)
52
+ pillars[key] = {
53
+ "score": sum(w * s for w, s in scored) / weight if weight else None,
54
+ "partial": not values.keys() >= pillar["metrics"].keys() or (red and bool(VALUE_METRICS & pillar["metrics"].keys())),
55
+ }
56
+ return metrics, pillars
57
+
58
+
59
+ MIN_EVIDENCE = 2
60
+
61
+
62
+ def kill_matrix(tests, passing, mutation):
63
+ """Flag each test hollow, subsumed or insufficient_evidence from the sampled kill matrix, and return the one metric the
64
+ matrix alone owns, subsumed_in_kill_matrix; the metrics the flags change are computed from them afterwards. Only
65
+ passing tests are judged.
66
+
67
+ On its lines = a sampled mutant whose line the test executes. Subsumed = at least 2 of them, it kills some, and one
68
+ other test kills all it kills."""
69
+ matrix = mutation["matrix"]
70
+ for node, test in tests.items():
71
+ covered = {rel: set(lines) for rel, lines in test.get("coverage", {}).items()}
72
+ on = [m for m, info in mutation["mutants"].items() if info["line"] in covered.get(info["file"], ())] if node in passing else []
73
+ kills = {m for m in on if node in matrix[m]}
74
+ enough = len(on) >= MIN_EVIDENCE
75
+ every = {m for m in matrix if node in matrix[m]}
76
+ test["insufficient_evidence"] = node in passing and not enough
77
+ test["hollow"] = enough and not kills
78
+ test["subsumed"] = enough and bool(kills) and any(
79
+ other != node and every <= {m for m in matrix if other in matrix[m]} for other in {t for row in matrix.values() for t in row})
80
+ return {"subsumed_in_kill_matrix": 100 * sum(t["subsumed"] for t in tests.values()) / (len(tests) or 1)}
@@ -0,0 +1,355 @@
1
+ """Per-test smells from each test function's syntax tree, one test at a time."""
2
+ import ast
3
+ import copy
4
+ import hashlib
5
+
6
+ from weigh_inventory import is_test
7
+
8
+ MOCK_ASSERTS = ("assert_called", "assert_any_call", "assert_has_calls", "assert_not_called", "assert_awaited", "assert_not_awaited")
9
+ # what an assertion on a mock reads
10
+ MOCK_ATTRS = ("called", "call_count", "call_args", "call_args_list", "mock_calls", "await_count", "await_args", "await_args_list")
11
+ MOCK_MAKERS = ("MagicMock", "Mock", "AsyncMock", "NonCallableMock", "create_autospec", "patch")
12
+ HELPER_ASSERTS = ("assert", "check_", "expect_")
13
+ RAISES = ("pytest.raises", "pytest.warns", "pytest.deprecated_call")
14
+ MOCK_HEAVY_ABOVE = 3
15
+ # Smells and Worst tests tabs: the smells of each pillar
16
+ PILLAR_SMELLS = {
17
+ "regression": ("No assertion",),
18
+ "refactoring": ("Mock-heavy", "Interaction-only", "Private access"),
19
+ "feedback": ("Real sleep",),
20
+ "maintainability": ("Eager test", "Conditional test logic", "Mystery guest", "Swallowed exception", "PT"),
21
+ "economy": ("Duplicate body",),
22
+ }
23
+ MAINTAINABILITY_SMELLS = PILLAR_SMELLS["maintainability"]
24
+ LONG_TEST_LINES = 50
25
+ EAGER_CYCLES = 3
26
+ SAFE_ROOTS = ("tmp_path", "tmp_path_factory", "monkeypatch")
27
+ FILE_READS = ("read_text", "read_bytes", "open")
28
+ SLEEPS = ("time.sleep", "asyncio.sleep")
29
+ HOME_ENV = ("os.environ", "os.getenv", "os.path.expanduser", "Path.home", "pathlib.Path.home")
30
+
31
+
32
+ def _dotted(node):
33
+ parts = []
34
+ while isinstance(node, ast.Attribute):
35
+ parts.append(node.attr)
36
+ node = node.value
37
+ if isinstance(node, ast.Name):
38
+ parts.append(node.id)
39
+ return ".".join(reversed(parts))
40
+
41
+
42
+ def _private(name):
43
+ return name.startswith("_") and not name.endswith("__")
44
+
45
+
46
+ def _from_test_module(node):
47
+ return is_test((node.module or "").replace(".", "/") + ".py")
48
+
49
+
50
+ def _scope_nodes(nodes):
51
+ """The nodes of a scope's statements in source order, not those inside the functions and classes it defines."""
52
+ for n in nodes:
53
+ yield n
54
+ if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
55
+ yield from _scope_nodes(ast.iter_child_nodes(n))
56
+
57
+
58
+ def _module_privates(tree):
59
+ """Private names the module imports, at module scope, from a non-test module."""
60
+ found = set()
61
+ for n in _scope_nodes(tree.body):
62
+ if isinstance(n, ast.ImportFrom) and not _from_test_module(n):
63
+ found |= {a.asname or a.name for a in n.names if _private(a.name)}
64
+ return found
65
+
66
+
67
+ def _aliases(nodes):
68
+ """{name bound by an import among nodes: the dotted module or object it names}; a later import wins."""
69
+ found = {}
70
+ for n in nodes:
71
+ if isinstance(n, ast.Import):
72
+ for a in n.names:
73
+ found[a.asname or a.name.split(".")[0]] = a.name if a.asname else a.name.split(".")[0]
74
+ elif isinstance(n, ast.ImportFrom):
75
+ found.update({a.asname or a.name: f"{n.module}.{a.name}" if n.module else a.name for a in n.names})
76
+ return found
77
+
78
+
79
+ def _test_owned(owner, aliases):
80
+ """The object an attribute is read from is the test's own: self, cls, or a name imported from a test module."""
81
+ dotted = _dotted(owner)
82
+ if dotted in ("self", "cls"):
83
+ return True
84
+ head, _, rest = dotted.partition(".")
85
+ return head in aliases and is_test(".".join(filter(None, (aliases[head], rest))).replace(".", "/") + ".py")
86
+
87
+
88
+ def _conjuncts(test):
89
+ """The checks of an assert: each side of an `and`, each pair of an equality of two tuples or lists."""
90
+ if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And):
91
+ return [c for v in test.values for c in _conjuncts(v)]
92
+ sides = [test.left, *test.comparators] if isinstance(test, ast.Compare) else []
93
+ if (len(sides) == 2 and isinstance(test.ops[0], ast.Eq) and all(isinstance(e, (ast.Tuple, ast.List)) for e in sides)
94
+ and len(sides[0].elts) == len(sides[1].elts) > 0):
95
+ return [c for a, b in zip(sides[0].elts, sides[1].elts) for c in _conjuncts(ast.Compare(a, [ast.Eq()], [b]))]
96
+ return [test]
97
+
98
+
99
+ def _reads_mock(expr):
100
+ return any(isinstance(a, ast.Attribute) and a.attr in MOCK_ATTRS for a in ast.walk(expr))
101
+
102
+
103
+ def _assertion(n):
104
+ """"plain", "mock" or None: the one classification of an assertion, shared by every rule that looks for one."""
105
+ if isinstance(n, ast.Expr):
106
+ return _assertion(n.value)
107
+ if isinstance(n, ast.Assert):
108
+ # `assert result == x and sender.call_count == 1` checks a result too
109
+ return "plain" if not all(_reads_mock(c) for c in _conjuncts(n.test)) else "mock"
110
+ if isinstance(n, (ast.With, ast.AsyncWith)):
111
+ return "plain" if any(isinstance(i.context_expr, ast.Call) and _dotted(i.context_expr.func) in RAISES for i in n.items) else None
112
+ if isinstance(n, ast.Call):
113
+ name = _dotted(n.func)
114
+ last = name.split(".")[-1]
115
+ if last.startswith(MOCK_ASSERTS):
116
+ return "mock"
117
+ if last.lower().startswith(HELPER_ASSERTS) or name == "pytest.fail":
118
+ return "plain"
119
+ return None
120
+
121
+
122
+ def _names(node):
123
+ return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
124
+
125
+
126
+ def _safe_names(func):
127
+ """Names obtained from tmp_path or monkeypatch: the fixtures and what is assigned from them."""
128
+ safe = {a.arg for a in func.args.args if a.arg in SAFE_ROOTS}
129
+ for n in ast.walk(func):
130
+ if isinstance(n, ast.Assign) and _names(n.value) & safe:
131
+ safe |= {t.id for t in n.targets if isinstance(t, ast.Name)}
132
+ return safe
133
+
134
+
135
+ def _literal_path(node, safe, guests):
136
+ """A path built from a string literal or from a name holding one, and not from tmp_path or monkeypatch."""
137
+ names = _names(node)
138
+ return bool(any(isinstance(c, ast.Constant) and isinstance(c.value, str) for c in ast.walk(node)) or names & guests) and not names & safe
139
+
140
+
141
+ def _guest_names(func, safe):
142
+ """Names assigned a literal path, in source order, so a name assigned from another one carries its path."""
143
+ guests = set()
144
+ for n in sorted((n for n in ast.walk(func) if isinstance(n, ast.Assign)), key=lambda n: (n.lineno, n.col_offset)):
145
+ if _literal_path(n.value, safe, guests):
146
+ guests |= {t.id for t in n.targets if isinstance(t, ast.Name)}
147
+ return guests
148
+
149
+
150
+ def _reads_guest(n, safe, guests):
151
+ """A file read or home/environment access whose path is not from tmp_path or monkeypatch."""
152
+ if isinstance(n, ast.Attribute) and _dotted(n) in HOME_ENV:
153
+ return "monkeypatch" not in safe
154
+ if not isinstance(n, ast.Call):
155
+ return False
156
+ if isinstance(n.func, ast.Name) and n.func.id == "open" and n.args:
157
+ target = n.args[0]
158
+ elif isinstance(n.func, ast.Attribute) and n.func.attr in FILE_READS:
159
+ target = n.func.value
160
+ else:
161
+ return False
162
+ return _literal_path(target, safe, guests)
163
+
164
+
165
+ def _eager(func):
166
+ """Act-then-assert cycles: a statement that is not an assertion, followed by one that is."""
167
+ cycles, acted = 0, False
168
+
169
+ def walk(body):
170
+ nonlocal cycles, acted
171
+ for st in body:
172
+ if _assertion(st):
173
+ cycles, acted = cycles + acted, False
174
+ elif isinstance(st, (ast.With, ast.AsyncWith)):
175
+ walk(st.body)
176
+ else:
177
+ acted = True
178
+
179
+ walk(func.body)
180
+ return cycles
181
+
182
+
183
+ def _swallows(func):
184
+ return any(isinstance(h, ast.ExceptHandler) and not any(isinstance(x, ast.Raise) or _assertion(x) for x in ast.walk(h))
185
+ for n in ast.walk(func) if isinstance(n, ast.Try) for h in n.handlers)
186
+
187
+
188
+ def _sleeps(func):
189
+ return any(isinstance(n, ast.Call) and _dotted(n.func) in SLEEPS and n.args
190
+ and not (isinstance(n.args[0], ast.Constant) and n.args[0].value == 0) for n in ast.walk(func))
191
+
192
+
193
+ class _Normalize(ast.NodeTransformer):
194
+ """Names and literals become placeholders; call and attribute structure stays."""
195
+
196
+ def visit_Name(self, node):
197
+ return ast.Name(id="_", ctx=node.ctx)
198
+
199
+ def visit_arg(self, node):
200
+ return ast.arg(arg="_")
201
+
202
+ def visit_Constant(self, node):
203
+ return ast.Constant(value=type(node.value).__name__)
204
+
205
+
206
+ def _body_hash(func):
207
+ body = ast.Module(body=[_Normalize().visit(copy.deepcopy(st)) for st in func.body], type_ignores=[])
208
+ return hashlib.sha1(ast.dump(body).encode()).hexdigest()
209
+
210
+
211
+ def smells_of(func, module_privates, module_aliases):
212
+ aliases = {**module_aliases, **_aliases(ast.walk(func))}
213
+ kinds = {_assertion(n) for n in ast.walk(func)}
214
+ plain, mock, private = "plain" in kinds, "mock" in kinds, False
215
+ mocks = 0
216
+ for n in ast.walk(func):
217
+ if isinstance(n, ast.Call):
218
+ name = _dotted(n.func)
219
+ if name.split(".")[-1] in MOCK_MAKERS or name.startswith(("patch.", "mock.patch.")) or name == "monkeypatch.setattr":
220
+ mocks += 1
221
+ elif isinstance(n, ast.ImportFrom):
222
+ private |= not _from_test_module(n) and any(_private(a.name) for a in n.names)
223
+ elif isinstance(n, ast.Name):
224
+ private |= n.id in module_privates
225
+ elif isinstance(n, ast.Attribute):
226
+ private |= _private(n.attr) and not _test_owned(n.value, aliases)
227
+ safe = _safe_names(func)
228
+ guests = _guest_names(func, safe)
229
+ return [s for s, has in (("No assertion", not plain and not mock), ("Interaction-only", mock and not plain),
230
+ ("Mock-heavy", mocks > MOCK_HEAVY_ABOVE), ("Private access", private),
231
+ ("Eager test", _eager(func) >= EAGER_CYCLES),
232
+ ("Conditional test logic", any(isinstance(n, (ast.If, ast.For, ast.While)) for n in ast.walk(func))),
233
+ ("Mystery guest", any(_reads_guest(n, safe, guests) for n in ast.walk(func))),
234
+ ("Swallowed exception", _swallows(func)), ("Real sleep", _sleeps(func))) if has]
235
+
236
+
237
+ def _definitions(tree):
238
+ """({"Class::name" or "name": function}, {"Class": (enclosing prefix, class)}), by the qualification pytest gives;
239
+ a later definition wins, as in Python."""
240
+ functions, classes = {}, {}
241
+
242
+ def visit(body, prefix):
243
+ for st in body:
244
+ if isinstance(st, ast.ClassDef):
245
+ classes[prefix + st.name] = (prefix, st)
246
+ visit(st.body, f"{prefix}{st.name}::")
247
+ elif isinstance(st, (ast.FunctionDef, ast.AsyncFunctionDef)):
248
+ functions[prefix + st.name] = st
249
+
250
+ visit(tree.body, "")
251
+ return functions, classes
252
+
253
+
254
+ def _mro(classes, cls, seen=frozenset()):
255
+ """Python's method resolution order (C3) of a class of the module; a base defined elsewhere ends its line."""
256
+ if cls not in classes or cls in seen:
257
+ return [cls]
258
+ prefix, node = classes[cls]
259
+ bases = [next((q for q in (prefix + d, d) if q in classes), d)
260
+ for d in (_dotted(b).replace(".", "::") for b in node.bases)]
261
+ lines, order = [_mro(classes, b, seen | {cls}) for b in bases] + [bases], [cls]
262
+ while lines := [line for line in lines if line]:
263
+ head = next((line[0] for line in lines if not any(line[0] in other[1:] for other in lines)), None)
264
+ if head is None: # no consistent order: Python refuses to create such a class
265
+ return order + [c for line in lines for c in line if c not in order]
266
+ order.append(head)
267
+ lines = [line[1:] if line[0] == head else line for line in lines]
268
+ return order
269
+
270
+
271
+ def _resolve(module, qualified):
272
+ """The function of a test: by its full qualification, else the method its class inherits, found in Python's
273
+ resolution order among the classes of the module (None when the method lives in another module)."""
274
+ functions, classes = module["functions"], module["classes"]
275
+ if qualified in functions:
276
+ return functions[qualified]
277
+ cls, _, name = qualified.rpartition("::")
278
+ return next((functions[f"{c}::{name}"] for c in _mro(classes, cls)[1:] if f"{c}::{name}" in functions), None)
279
+
280
+
281
+ def find_smells(repo, tests, ruff=()):
282
+ """({node: {smells, lines}}, clusters) for every test; a test whose source cannot be read or parsed has none.
283
+
284
+ ruff holds (path, row, code) violations: each is a smell of the test whose lines contain the row.
285
+
286
+ A cluster is the sorted node ids of 2 or more tests with one normalized body; each gets the smell Duplicate body."""
287
+ modules, result, bodies = {}, {}, {}
288
+ for node in tests:
289
+ path, _, qualified = node.partition("::")
290
+ if path not in modules:
291
+ try:
292
+ tree = ast.parse((repo / path).read_text(errors="replace"))
293
+ functions, classes = _definitions(tree)
294
+ modules[path] = {"functions": functions, "classes": classes, "privates": _module_privates(tree),
295
+ "aliases": _aliases(_scope_nodes(tree.body))}
296
+ except (OSError, SyntaxError, ValueError):
297
+ modules[path] = None
298
+ module = modules[path]
299
+ found = module and _resolve(module, qualified)
300
+ result[node] = {"smells": smells_of(found, module["privates"], module["aliases"]) if found else [],
301
+ "lines": found.end_lineno - found.lineno + 1 if found else 0}
302
+ if found:
303
+ result[node]["smells"] += sorted({c for p, row, c in ruff if p == path and found.lineno <= row <= found.end_lineno})
304
+ if found:
305
+ bodies.setdefault(_body_hash(found), []).append(node)
306
+ clusters = sorted(sorted(g) for g in bodies.values() if len(g) > 1)
307
+ for node in (n for c in clusters for n in c):
308
+ result[node]["smells"].append("Duplicate body")
309
+ return result, clusters
310
+
311
+
312
+ def smell_values(tests):
313
+ """Percentages of all tests. A hollow test is one with no assertion or one the kill matrix found hollow; an
314
+ insufficient-evidence test counts in no Economy metric (duplicate clusters)."""
315
+ n = len(tests) or 1
316
+ share = lambda smell: 100 * sum(smell in t["smells"] for t in tests.values()) / n
317
+ return {"hollow_tests": 100 * sum("No assertion" in t["smells"] or t.get("hollow", False) for t in tests.values()) / n,
318
+ "duplicate_clusters": 100 * sum("Duplicate body" in t["smells"] and not t.get("insufficient_evidence") for t in tests.values()) / n,
319
+ "smelly_tests": 100 * sum(any(s.startswith(MAINTAINABILITY_SMELLS) for s in t["smells"]) for t in tests.values()) / n,
320
+ "long_tests": 100 * sum(t["lines"] > LONG_TEST_LINES for t in tests.values()) / n, "mock_heavy": share("Mock-heavy"),
321
+ "interaction_only": share("Interaction-only"), "private_access": share("Private access")}
322
+
323
+
324
+ def pillar_smells(tests, smells):
325
+ """{smell: sorted node ids that have it}, for the smells given (a prefix such as "PT" matches every PT code)."""
326
+ found = {}
327
+ for node, t in sorted(tests.items()):
328
+ for s in t["smells"]:
329
+ if s.startswith(smells):
330
+ found.setdefault(s, []).append(node)
331
+ return dict(sorted(found.items()))
332
+
333
+
334
+ def _measured(test, pillar, slow):
335
+ """(reasons, weight) a test ranks low by in a pillar beyond its smells: its length, duration or redundant coverage."""
336
+ if pillar == "maintainability" and test["lines"] > LONG_TEST_LINES:
337
+ return [f"{test['lines']} lines"], test["lines"]
338
+ if pillar == "feedback" and test["duration"] > slow:
339
+ return [f"{test['duration']:.2f} s"], test["duration"]
340
+ # unique coverage is measured only for tests that passed unflaky
341
+ if pillar == "economy" and test["outcome"] == "passed" and not test["flaky"] and not test.get("unique_coverage", 0):
342
+ return ["No unique coverage"], 0
343
+ return [], 0
344
+
345
+
346
+ def worst_tests(tests, pillar, slow, limit=10):
347
+ """The lowest-ranked tests of a pillar, each with its reasons: most reasons first, then the longest or slowest.
348
+ A test is slow above `slow` seconds."""
349
+ ranked = []
350
+ for node, t in tests.items():
351
+ extra, weight = _measured(t, pillar, slow)
352
+ reasons = [s for s in t["smells"] if s.startswith(PILLAR_SMELLS.get(pillar, ()))] + extra
353
+ if reasons:
354
+ ranked.append((-len(reasons), -weight, node, reasons))
355
+ return [{"test": n, "reason": ", ".join(r)} for _, _, n, r in sorted(ranked)[:limit]]
@@ -0,0 +1,49 @@
1
+ """Repo key, commit state and exclusive snapshot writing under ~/.test-weigh-in/."""
2
+ import json
3
+ import os
4
+ import re
5
+ import subprocess
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ from weigh_env import SetupError
10
+
11
+ REMOTE = re.compile(r"^(?:[a-z+]+://)?(?:[^@/]+@)?([^:/]+)[:/](.+?)(?:\.git)?/?$")
12
+
13
+
14
+ def git(repo, *args):
15
+ return subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True).stdout.strip()
16
+
17
+
18
+ def repo_key(repo):
19
+ origin = git(repo, "remote", "get-url", "origin")
20
+ m = REMOTE.match(origin)
21
+ key = f"{m[1]}/{m[2]}" if m else f"local/{repo.name}"
22
+ # The key is a path under ~/.test-weigh-in: an origin like host:../../x must not climb out of it.
23
+ if any(part in ("", ".", "..") for part in key.split("/")):
24
+ raise SetupError(f"cannot store snapshots for origin {origin!r}: its path has an empty, . or .. segment")
25
+ return key
26
+
27
+
28
+ def commit_state(repo):
29
+ return git(repo, "rev-parse", "--short", "HEAD"), bool(git(repo, "status", "--porcelain"))
30
+
31
+
32
+ def home_dir(repo):
33
+ return Path.home() / ".test-weigh-in" / repo_key(repo)
34
+
35
+
36
+ def write_snapshot(home, data):
37
+ home.mkdir(parents=True, exist_ok=True)
38
+ now = os.environ.get("TEST_WEIGH_IN_NOW")
39
+ when = datetime.fromisoformat(now.replace("Z", "+00:00")) if now else datetime.now(timezone.utc)
40
+ stem = f"{when:%Y%m%dT%H%M%SZ}_{data['commit']}"
41
+ n = 1
42
+ while True:
43
+ path = home / (f"{stem}.json" if n == 1 else f"{stem}-{n}.json")
44
+ try:
45
+ with path.open("x") as out:
46
+ json.dump(data, out, indent=2)
47
+ return path
48
+ except FileExistsError:
49
+ n += 1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-02T14:19:47.551Z",
3
+ "generatedAt": "2026-11-03T07:02:30.559Z",
4
4
  "skills": [
5
5
  {
6
6
  "name": "agents-wayfinder",
@@ -34,8 +34,8 @@
34
34
  },
35
35
  {
36
36
  "name": "crap-gate",
37
- "version": "0.1.4",
38
- "hash": "sha256-a3fe7bcb7ad6566aa25c44b0bc7823c625b536b4f3eb5cdfe73e6628ad04ee05",
37
+ "version": "0.1.5",
38
+ "hash": "sha256-ddf100022e078ad567efc30cdffb02d2e332e59db5866614e42c100173a7974f",
39
39
  "description": "Score every function a branch changed with CRAP (cyclomatic complexity × untested fraction), fail on existing functions above 15 and new functions above 9, and drive a fixer + independent reviewer loop until the gate passes. Use when implementation is done and before pushing, when the user says \"run the crap gate\", \"check CRAP\", \"is this change tested enough\", or when a push gate reports CRAP violations."
40
40
  },
41
41
  {
@@ -58,8 +58,8 @@
58
58
  },
59
59
  {
60
60
  "name": "implement-spec",
61
- "version": "0.1.47",
62
- "hash": "sha256-0aef522504cc63d918dd8731f9b2fa00e33c7291c680f37c3dfc6a08adc38d93",
61
+ "version": "0.1.48",
62
+ "hash": "sha256-c1c51c34db8cb4c87c3437b3b0c1569dbabb60e327b3afdeaa5e0b9306efa0ba",
63
63
  "description": "Implement a specification in code."
64
64
  },
65
65
  {
@@ -104,6 +104,12 @@
104
104
  "hash": "sha256-cc46e2d40c52615a88a53f87c62f60ddc6944cacad55427a83f9191cd0900410",
105
105
  "description": "Mutation-guided test pruning: a fixer proposes deleting redundant tests and strengthening weak ones, an independent reviewer accepts or rejects each proposal, and prune.py applies the accepted batch behind a cold mutation run and the ratchet. Use when the user says \"prune tests\", \"test-prune\", \"mutation test pruning\" or \"strengthen weak tests\", or when a scheduled job runs it with `--unattended`."
106
106
  },
107
+ {
108
+ "name": "test-weigh-in",
109
+ "version": "0.1.0",
110
+ "hash": "sha256-b121ea2a0c8d1f96aac95e5d3d45ebdf11f64d89ec71ef04c67bdeb12bfd1179",
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
+ },
107
113
  {
108
114
  "name": "to-openspec",
109
115
  "version": "0.1.3",