@jesdi/skills 0.0.85 → 0.0.87

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 (35) hide show
  1. package/package.json +1 -1
  2. package/skills/implement-spec/ARCHITECTURE.md +13 -6
  3. package/skills/implement-spec/README.md +23 -11
  4. package/skills/implement-spec/SKILL.md +1 -1
  5. package/skills/implement-spec/driver.py +3 -2
  6. package/skills/implement-spec/driver_agents.py +93 -32
  7. package/skills/implement-spec/driver_run.py +23 -13
  8. package/skills/implement-spec/driver_state.py +1 -1
  9. package/skills/implement-spec/driver_summary.py +8 -1
  10. package/skills/implement-spec/tests/conftest.py +2 -0
  11. package/skills/implement-spec/tests/test_agents.py +56 -5
  12. package/skills/implement-spec/tests/test_arbitration.py +3 -1
  13. package/skills/implement-spec/tests/test_driver.py +2 -1
  14. package/skills/implement-spec/tests/test_landing.py +2 -2
  15. package/skills/implement-spec/tests/test_lenses.py +10 -5
  16. package/skills/implement-spec/tests/test_models.py +74 -0
  17. package/skills/implement-spec/tests/test_summary.py +8 -0
  18. package/skills/implement-spec/tests/test_walk.py +2 -2
  19. package/skills/test-weigh-in/dashboard.html +185 -27
  20. package/skills/test-weigh-in/rules.toml +18 -0
  21. package/skills/test-weigh-in/tests/browser_driver.py +161 -0
  22. package/skills/test-weigh-in/tests/conftest.py +8 -1
  23. package/skills/test-weigh-in/tests/latency_probe.py +96 -0
  24. package/skills/test-weigh-in/tests/layout_page.py +37 -0
  25. package/skills/test-weigh-in/tests/metric_page.py +56 -0
  26. package/skills/test-weigh-in/tests/overlap_page.py +60 -0
  27. package/skills/test-weigh-in/tests/rules_fixture.py +3 -1
  28. package/skills/test-weigh-in/tests/sorted_map_page.py +35 -0
  29. package/skills/test-weigh-in/tests/test_brittleness.py +5 -0
  30. package/skills/test-weigh-in/tests/test_dashboard_layout.py +103 -0
  31. package/skills/test-weigh-in/tests/test_scoring.py +10 -0
  32. package/skills/test-weigh-in/weigh.py +25 -15
  33. package/skills/test-weigh-in/weigh_dashboard.py +9 -1
  34. package/skills/test-weigh-in/weigh_rules.py +3 -0
  35. package/skills-manifest.json +5 -5
@@ -192,14 +192,16 @@ def test_help_lists_the_timeout_flag_and_default_minutes():
192
192
 
193
193
 
194
194
  @pytest.mark.parametrize("entry", ["openai/gpt-sol@medium"])
195
- def test_openai_implementer_launches_codex_exec_in_workspace_write(env, entry):
195
+ def test_openai_implementer_launches_codex_exec_with_full_access_so_it_can_commit(env, entry):
196
+ # workspace-write keeps .git read-only, even with --add-dir on the git directory: git commit fails there.
196
197
  w = World(env, refactor=True, implementer=[entry, entry]) # the rerun after no report is on the next entry
197
198
  w.run(runner=False)
198
199
  argv = launches(w.tmp, "codex")[0]
199
200
  assert argv[0] == "exec" and "--ephemeral" not in argv
200
201
  assert value_after(argv, "--model", "-m") == "gpt-sol"
201
202
  assert any("model_reasoning_effort" in a and "medium" in a for a in argv)
202
- assert value_after(argv, "--sandbox", "-s") == "workspace-write"
203
+ assert value_after(argv, "--sandbox", "-s") == "danger-full-access"
204
+ assert "--json" in argv, "the log carries the token usage that prices the run"
203
205
  assert not launches(w.tmp, "claude")
204
206
 
205
207
 
@@ -210,6 +212,7 @@ def test_the_reviewer_launches_codex_exec_read_only(env):
210
212
  assert argv[0] == "exec" and "--ephemeral" not in argv
211
213
  assert value_after(argv, "--sandbox", "-s") == "read-only"
212
214
  assert value_after(argv, "--model", "-m") == "gpt-sol"
215
+ assert "--json" in argv
213
216
 
214
217
 
215
218
  @pytest.mark.parametrize("writes", ["file", "message"])
@@ -339,16 +342,18 @@ def test_a_model_the_account_cannot_use_is_skipped_and_its_roles_go_on_with_thei
339
342
 
340
343
 
341
344
  def test_a_cli_that_fails_with_no_report_stops_the_run_with_exit_4_and_the_same_command_resumes(env):
345
+ """Stop and ask: the first CLI failure stops the run, with no rerun on another entry of the list."""
342
346
  w = World(env, refactor=True)
343
- plan = {"implementer": [{"stderr": REFUSED + "\n", "exit": 1}] * 2 + [impl()]}
347
+ plan = {"implementer": [{"stderr": REFUSED + "\n", "exit": 1}, impl()]}
344
348
  proc = w.run(plan)
349
+ assert len(w.calls("implementer")) == 1, "no rerun after a CLI failure"
345
350
  assert proc.returncode == 4, proc.stdout + proc.stderr
346
- assert f"implement-spec: the run stopped: the implementer on openai/gpt-sol@medium exited 1 with no " \
351
+ assert f"implement-spec: the run stopped: the implementer on anthropic/claude-opus-5@medium exited 1 with no " \
347
352
  f"report: {REFUSED}" in proc.stdout.splitlines(), proc.stdout
348
353
  assert "BLOCKED" not in w.ledger() and "Ticket 01: the run stops and the phase stays for the next run: the implementer" in w.ledger()
349
354
  assert json.loads((w.repo / ".agent/implement/state.json").read_text())["tickets"]["01"]["phase"] == "implement"
350
355
  ok(w.run(plan))
351
- assert len(w.calls("implementer")) == 3
356
+ assert len(w.calls("implementer")) == 2
352
357
 
353
358
 
354
359
  def test_finished_status_reruns_the_implementer_once_with_the_error_appended(env):
@@ -452,3 +457,49 @@ def test_log_next_to_report_and_ledger_records_role_entry_duration_and_cost(env)
452
457
  assert "OUT-MARK" in log and "ERR-MARK" in log and (folder / "implementer-0.json").exists()
453
458
  (line,) = [l for l in w.ledger().splitlines() if "implementer" in l and "claude-opus-5@medium" in l]
454
459
  assert re.search(r"\d+(\.\d+)?s\b", line) and "0.4242" in line, line
460
+
461
+
462
+ def turn(used, cached, out):
463
+ return json.dumps({"type": "turn.completed", "usage": {"input_tokens": used, "cached_input_tokens": cached,
464
+ "output_tokens": out, "reasoning_output_tokens": 0}})
465
+
466
+
467
+ def test_a_codex_agent_is_priced_from_its_token_usage_at_the_list_price_of_its_model(env):
468
+ astra = "openai/gpt-6-astra@medium"
469
+ w = World(env, refactor=True, implementer=[astra])
470
+ # Two turns: 1.2M input of which 0.4M cached, 10k output. At 10 / 1 / 50 USD per million: 8 + 0.4 + 0.5.
471
+ ok(w.run({"implementer": [impl(stdout=turn(700_000, 300_000, 4_000) + "\n" + turn(500_000, 100_000, 6_000) + "\n")]}))
472
+ (line,) = [l for l in w.ledger().splitlines() if "implementer ran on" in l]
473
+ assert f"implementer ran on {astra} for " in line and ", cost 8.9 USD: report accepted." in line, line
474
+ (agent,) = [a for a in json.loads((w.repo / ".agent/implement/state.json").read_text())["run"]["agents"]
475
+ if a["role"] == "implementer"]
476
+ assert agent["cost"] == 8.9
477
+ assert agent["tokens"] == {"input": 1_200_000, "cached_input": 400_000, "output": 10_000}
478
+
479
+
480
+ def test_a_codex_model_with_no_list_price_keeps_its_tokens_and_the_ledger_says_it_is_not_priced(env):
481
+ w = World(env, refactor=True, implementer=["openai/gpt-sol@medium"])
482
+ ok(w.run({"implementer": [impl(stdout=turn(1_000, 200, 30) + "\n")]}))
483
+ (line,) = [l for l in w.ledger().splitlines() if "implementer ran on" in l]
484
+ assert ", 1000 input tokens (200 cached) and 30 output tokens, not priced: report accepted." in line, line
485
+ (agent,) = [a for a in json.loads((w.repo / ".agent/implement/state.json").read_text())["run"]["agents"]
486
+ if a["role"] == "implementer"]
487
+ assert agent["cost"] is None and agent["tokens"] == {"input": 1_000, "cached_input": 200, "output": 30}
488
+
489
+
490
+ @pytest.mark.parametrize("line", ['{"type": "error", "message": "You\'ve hit your usage limit."}',
491
+ '{"type": "turn.failed", "error": {"message": "You\'ve hit your usage limit."}}'])
492
+ def test_the_last_words_of_a_codex_json_log_are_its_error_message(tmp_path, line):
493
+ sys.path.insert(0, str(SKILL))
494
+ import driver_agents
495
+ log = tmp_path / "agent.log"
496
+ log.write_text('{"type": "thread.started"}\n' + line + "\n")
497
+ assert driver_agents.last_words(log) == "You've hit your usage limit."
498
+
499
+
500
+ def test_a_turn_with_no_usage_counts_no_token(tmp_path):
501
+ sys.path.insert(0, str(SKILL))
502
+ import driver_agents
503
+ log = tmp_path / "agent.log"
504
+ log.write_text('{"type": "turn.completed"}\n' + turn(10, 4, 2) + "\n")
505
+ assert driver_agents.tokens(log) == {"input": 10, "cached_input": 4, "output": 2}
@@ -149,7 +149,9 @@ def test_the_summary_keeps_its_table_and_counts_an_arbitration_as_a_reviewer_age
149
149
  rows = (rig.repo / ".agent/implement/summary.md").read_text().split("| Measure | Value |\n|---|---|\n")[1]
150
150
  names = re.findall(r"^\| (.+?) \|", rows, re.M)
151
151
  assert {f"wall time, {role}" for role in ("test-writer", "implementer", "reviewer", "fixer")} < set(names), rows
152
- assert names[-3:] == ["fix rounds per ticket", "human stops", "cost"] and rows.endswith(" USD |\n"), rows
152
+ # Most fake agents report no cost, so they are counted as not priced.
153
+ assert names[-4:] == ["fix rounds per ticket", "human stops", "cost", "agents not priced"], rows
154
+ assert re.search(r"^\| cost \| \d+\.\d\d USD \|$", rows, re.M), rows
153
155
  for row in ("| fast gates run | 2 |", "| full gates run | 1 |", "| agents, reviewer on anthropic/claude-opus-5@medium | 3 |",
154
156
  "| fix rounds per ticket | 01: 1, 02: 0 |", "| human stops | 1 |"):
155
157
  assert row in rows, rows
@@ -343,7 +343,8 @@ def test_a_timeout_for_an_unknown_role_is_a_usage_error(repo):
343
343
 
344
344
  def test_command_lines_per_provider():
345
345
  assert driver_agents.command("implementer", "openai/gpt-sol@high", "r.json") == [
346
- "codex", "exec", "--model", "gpt-sol", "-c", 'model_reasoning_effort="high"', "--sandbox", "workspace-write"]
346
+ "codex", "exec", "--json", "--model", "gpt-sol", "-c", 'model_reasoning_effort="high"', "--sandbox",
347
+ "danger-full-access"]
347
348
  assert driver_agents.command("reviewer", "openai/gpt-sol@high", "r.json")[-4:] == [
348
349
  "--sandbox", "read-only", "-o", "r.json.last"]
349
350
  assert driver_agents.command("reviewer", "opus@low", "r.json")[:6] == [
@@ -192,9 +192,9 @@ def ended(proc):
192
192
 
193
193
 
194
194
  def until(done, seconds=30):
195
- end = time.time() + seconds
195
+ end = time.monotonic() + seconds
196
196
  while not done():
197
- assert time.time() < end, "the first driver did not reach its agent"
197
+ assert time.monotonic() < end, "the first driver did not reach its agent"
198
198
  time.sleep(0.02)
199
199
 
200
200
 
@@ -109,12 +109,17 @@ def test_the_review_coverage_names_only_what_ran_so_an_undone_fallback_is_not_cl
109
109
 
110
110
  # ---------------------------------------------------------------- input validation
111
111
 
112
- def test_a_final_reviewer_list_with_no_entry_on_another_provider_exits_3_before_any_agent(tmp_path):
112
+ def test_a_final_reviewer_list_with_no_entry_on_another_provider_runs_every_review_on_it_and_says_so(
113
+ tmp_path, monkeypatch):
114
+ """Another provider for correctness is a preference: a config on one provider runs, and the ledger says so."""
115
+ monkeypatch.setattr(driver, "_preflight", lambda args, models: driver._checked(models))
116
+ monkeypatch.setattr(driver_agents, "_failures", lambda entries: {})
113
117
  rig = rig_of(tmp_path, models={"implementer": [SONNET], "final-reviewer": [OPUS]}).run(plan())
114
- assert rig.code == 3 and not rig.calls(), rig.out
115
- assert rig.out == (f"final-reviewer: no entry of its list ({OPUS}) is on another provider than the implementer's "
116
- f"first entry {SONNET}; its other-provider entry serves the correctness lens of the final "
117
- "review and the scoped review, which never run on the implementer's provider\n")
118
+ assert rig.code == 0, rig.out
119
+ said = (f"No final-reviewer entry is on another provider than {SONNET}: the correctness lens and the scoped review "
120
+ f"run on {OPUS}, the implementer's provider.")
121
+ assert rig.out.splitlines()[0] == said and rig.ledger()[0] == said
122
+ assert rig.led("End of run: final-correctness ran on", OPUS)
118
123
 
119
124
 
120
125
  def test_without_the_deep_quality_review_skill_the_run_exits_3_before_any_agent(tmp_path, monkeypatch):
@@ -5,6 +5,7 @@ skill's models.json does not define stops the run before the preflight and befor
5
5
  import json
6
6
  import re
7
7
  import subprocess
8
+ import sys
8
9
 
9
10
  import pytest
10
11
 
@@ -94,3 +95,76 @@ def test_only_correctness_exits_3_as_an_unknown_role(env, tmp_path):
94
95
  def test_the_skill_has_no_correctness_or_explorer_role():
95
96
  assert not {"correctness", "explorer"} & models().keys()
96
97
  assert not (SKILL / "prompts/correctness.md").exists()
98
+
99
+
100
+ # ---------------------------------------------------------------- the provider config files
101
+
102
+ OPUS, ASTRA, SOL = "claude-opus-5-5@medium", "openai/gpt-6-astra@medium", "openai/gpt-6.1-sol@medium"
103
+
104
+
105
+ @pytest.fixture
106
+ def layers(tmp_path, monkeypatch):
107
+ """A home config folder and a worktree; returns a writer of (the home file, the repo file)."""
108
+ sys.path.insert(0, str(SKILL))
109
+ import driver_agents
110
+ monkeypatch.setattr(driver_agents.shutil, "which", lambda cli: cli)
111
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
112
+ monkeypatch.chdir(tmp_path)
113
+ home, repo = tmp_path / "config/implement-spec/models.json", tmp_path / ".implement-spec/models.json"
114
+
115
+ def write(path, roles):
116
+ path.parent.mkdir(parents=True, exist_ok=True)
117
+ path.write_text(json.dumps(roles))
118
+ return path
119
+ return driver_agents, lambda roles: write(home, roles), lambda roles: write(repo, roles), tmp_path
120
+
121
+
122
+ def test_the_home_file_replaces_the_lists_it_names_and_keeps_the_rest(layers):
123
+ driver_agents, home, _, _ = layers
124
+ home({"reviewer": [OPUS]})
125
+ loaded, errors = driver_agents.load_models(None)
126
+ assert errors == [] and loaded["reviewer"] == [OPUS] and loaded["implementer"] == models()["implementer"]
127
+
128
+
129
+ def test_the_repo_file_wins_over_the_home_file_and_the_models_flag_wins_over_both(layers):
130
+ driver_agents, home, repo, tmp = layers
131
+ home({"reviewer": [OPUS], "fixer": [OPUS]})
132
+ repo({"reviewer": [ASTRA]})
133
+ loaded, errors = driver_agents.load_models(None)
134
+ assert errors == [] and loaded["reviewer"] == [ASTRA] and loaded["fixer"] == [OPUS]
135
+ flag = tmp / "flag.json"
136
+ flag.write_text(json.dumps({"reviewer": [SOL]}))
137
+ loaded, errors = driver_agents.load_models(str(flag))
138
+ assert errors == [] and loaded["reviewer"] == [SOL] and loaded["fixer"] == [OPUS]
139
+
140
+
141
+ def test_an_error_in_a_config_file_names_that_file(layers):
142
+ driver_agents, home, repo, tmp = layers
143
+ home({"correctness": [OPUS]})
144
+ repo({"planner": [OPUS]})
145
+ _, errors = driver_agents.load_models(None)
146
+ assert errors[0] == f"correctness: the role was removed; delete its key from {tmp}/config/implement-spec/models.json"
147
+ assert errors[1].startswith("planner: unknown role (known: ") and errors[1].endswith(
148
+ "); delete its key from .implement-spec/models.json"), errors
149
+ (tmp / ".implement-spec/models.json").write_text("{not json")
150
+ _, errors = driver_agents.load_models(None)
151
+ assert errors[1].startswith(".implement-spec/models.json: JSONDecodeError("), errors
152
+
153
+
154
+ def test_a_removed_role_in_the_repo_file_exits_3_naming_the_file_before_the_preflight(env, tmp_path):
155
+ repo = make_repo(tmp_path / "demo", three())
156
+ (repo / ".implement-spec").mkdir()
157
+ (repo / ".implement-spec/models.json").write_text(json.dumps({"correctness": [ASTRA]}))
158
+ proc = drive(env, repo, *RUNS)
159
+ assert proc.returncode == 3, proc.stdout + proc.stderr
160
+ assert ("correctness: the role was removed; delete its key from .implement-spec/models.json"
161
+ in proc.stdout.splitlines()), proc.stdout
162
+ assert not (tmp_path / "launched").exists(), "no preflight and no agent"
163
+
164
+
165
+ @pytest.mark.parametrize("content", ['{"reviewer": "openai/gpt-6-astra@medium"}', '{"reviewer": [1]}', "[]"])
166
+ def test_a_config_file_of_the_wrong_shape_is_an_error_naming_the_file(layers, content):
167
+ driver_agents, _, repo, _ = layers
168
+ repo({}).write_text(content)
169
+ _, errors = driver_agents.load_models(None)
170
+ assert len(errors) == 1 and errors[0].startswith(".implement-spec/models.json: "), errors
@@ -27,3 +27,11 @@ Ticket 03 is not merged: its phase is blocked.
27
27
  | human stops | 1 |
28
28
  | cost | 1.75 USD |
29
29
  """
30
+
31
+
32
+ def test_an_agent_with_no_price_is_counted_apart_from_the_cost():
33
+ agents = [{"role": "reviewer", "entry": "openai/gpt-x@low", "seconds": 1, "cost": None},
34
+ {"role": "implementer", "entry": "opus@medium", "seconds": 1, "cost": 0.5}]
35
+ state = {"run": {"pr_branch": "feat/csv", "gates": {"fast": 0, "full": 0}, "stops": 0, "final": driver_state._final(),
36
+ "agents": agents}, "tickets": {}}
37
+ assert driver_summary.render(state).endswith("| cost | 0.50 USD |\n| agents not priced | 1 |\n")
@@ -202,8 +202,8 @@ class Rig:
202
202
  proc = subprocess.Popen(["sh", str(RUN), *args], cwd=self.repo, env=self.env, text=True, stdout=o,
203
203
  stderr=e, start_new_session=True)
204
204
  self.snaps, self.torn = [], []
205
- state, end = self.repo / ".agent/implement/state.json", time.time() + 120
206
- while proc.poll() is None and time.time() < end:
205
+ state, end = self.repo / ".agent/implement/state.json", time.monotonic() + 120
206
+ while proc.poll() is None and time.monotonic() < end:
207
207
  if watch:
208
208
  try:
209
209
  self.snaps.append(json.loads(state.read_text()))
@@ -1,18 +1,54 @@
1
1
  <!doctype html>
2
2
  <html lang="en"><head><meta charset="utf-8"><title>test-weigh-in</title>
3
3
  <style>
4
- body{font:14px system-ui,sans-serif;margin:24px;color:#222}
5
- #gauges{display:flex;gap:12px;margin:16px 0}
6
- .gauge{flex:1;border:2px solid #ccc;border-radius:8px;padding:12px;background:#fff;text-align:center;cursor:pointer;font:inherit}
4
+ body{font:14px system-ui,sans-serif;margin:24px;color:#222;overflow-wrap:break-word}
5
+ #gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:0 12px;margin:16px 0}
6
+ .gauge{grid-row:span 3;display:grid;grid-template-rows:subgrid;row-gap:4px;align-content:start;margin-bottom:12px;border:2px solid #ccc;border-radius:8px;padding:12px;background:#fff;text-align:center;cursor:pointer;font:inherit}
7
+ .gauge>*{align-self:start}
8
+ .gauge-status{font-size:12px;line-height:1.3}
9
+ /* one row of tabs on a rule; it scrolls sideways when the row is wider than the screen */
10
+ .tabs{display:flex;gap:4px;overflow-x:auto;border-bottom:1px solid #ccc;scrollbar-width:thin}
11
+ .tabs>button{flex:none;font:inherit;padding:4px 12px;border:1px solid #ccc;border-bottom:3px solid transparent;border-radius:6px 6px 0 0;background:#f3f4f6;color:#222;cursor:pointer;white-space:nowrap}
12
+ .tabs>button[aria-pressed=true]{background:#2563eb;color:#fff;border-bottom-color:#1e40af;font-weight:600}
13
+ @media (max-width:600px){.tabs{gap:2px}.tabs>button{padding:4px 7px}}
14
+ button:focus-visible{outline:3px solid #f59e0b;outline-offset:2px}
15
+ #details table{width:100%}
16
+ #details tr+tr{border-top:1px solid #e5e7eb}
7
17
  .gauge[aria-pressed=true]{border-color:#2563eb}
8
18
  .score{display:block;font-size:32px;font-weight:600}
9
- #banner{background:#fef2f2;color:#991b1b;padding:8px 12px;border-radius:6px}
19
+ #banner{background:#fef2f2;color:#991b1b;padding:8px 12px;border-radius:6px;margin-bottom:0}
20
+ #failing{border:1px solid #fecaca;border-top:0;border-radius:0 0 6px 6px;padding:4px 12px;margin-bottom:16px}
21
+ #failing p{margin:4px 0}
22
+ #failing:empty{display:none}
23
+ #banner:has(+#failing:not(:empty)){border-radius:6px 6px 0 0}
10
24
  .flag{display:block;color:#92400e}
11
25
  table{border-collapse:collapse}td,th{padding:4px 12px;text-align:left}
26
+ /* a test identity: breaks after / :: . _ (see ident), anywhere only when one part is wider than the line */
27
+ .id{font:13px ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
28
+ /* the anchors column takes the spare width, so a metric and its value stay side by side */
29
+ @media (min-width:601px){#details th:nth-child(-n+3),#details td:nth-child(-n+3):not([colspan]){width:1%;white-space:nowrap}}
30
+ td:first-child,th:first-child{padding-left:0}
31
+ @media (max-width:600px){td,th{padding:4px 6px}td:last-child,th:last-child{padding-right:0}#details td:first-child{min-width:7em}}
32
+ input[type=search]{font:inherit;padding:6px 10px;border:1px solid #ccc;border-radius:6px;width:100%;max-width:24rem;box-sizing:border-box}
33
+ .pair{display:grid;grid-template-columns:8em minmax(0,1fr);gap:4px 12px;padding:8px 0;border-bottom:1px solid #e5e7eb}
34
+ .pair>strong{grid-row:span 3}
35
+ .pair hr{width:100%;border:0;border-top:1px dashed #d1d5db;margin:0}
36
+ @media (max-width:600px){.pair{grid-template-columns:minmax(0,1fr)}.pair>strong{grid-row:auto}}
37
+ .map{display:grid;gap:16px;align-items:start}
38
+ .map svg{display:block;width:100%;height:auto}
39
+ .map-side p{margin:0 0 8px}
40
+ .similar{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:4px 12px}
41
+ .similar>div{display:grid;grid-template-columns:subgrid;grid-column:1/-1}
42
+ .similar>.head{font-weight:600}
43
+ .similar>div+div+div{border-top:1px solid #f3f4f6;padding-top:4px}
44
+ .similar .num{text-align:right;font-variant-numeric:tabular-nums}
45
+ /* wide screens: the selection sits beside the map and stays in view while the map scrolls */
46
+ @media (min-width:900px){.map{grid-template-columns:minmax(0,1fr) 22rem}.map-side{position:sticky;top:0;max-height:100vh;overflow-y:auto}}
12
47
  </style></head><body>
13
48
  <h1>test-weigh-in</h1>
14
49
  <p data-testid="inventory" id="inventory"></p>
15
50
  <p data-testid="banner" id="banner"></p>
51
+ <div data-testid="failing" id="failing"></div>
16
52
  <div id="gauges"></div>
17
53
  <section data-testid="details" id="details"></section>
18
54
  <script>
@@ -20,15 +56,46 @@ const data = __DATA__;
20
56
  const shown = (s) => Math.min(99, Math.max(1, Math.round(s)));
21
57
  const el = (tag, text, parent) => { const e = document.createElement(tag); e.textContent = text; parent.appendChild(e); return e; };
22
58
  const fmt = (n) => String(Math.round(n * 100) / 100);
59
+ // words that belong together stay on one line: "71.3 %", "target ≤ 60 s"
60
+ const nb = (...parts) => parts.filter((x) => x !== '').join('\u00a0');
61
+ // ident marks an element whose text is a test identity. It gets break opportunities after / :: . or _ (not inside
62
+ // "name.py"), at least 12 characters apart, so it wraps between its parts; overflow-wrap breaks a part only when it is
63
+ // wider than the line. The breaks are added just before the next paint, to the identities still on the page then:
64
+ // paging through thousands of pairs in one go never builds the breaks of pages nobody saw.
65
+ let unbroken = [];
66
+ const addBreaks = () => {
67
+ const ids = unbroken; unbroken = [];
68
+ ids.forEach((s) => {
69
+ if (!s.isConnected) return;
70
+ const parts = [];
71
+ let chunk = '';
72
+ for (const part of s.textContent.split(/(?<=\/|::|\.(?!py\b)|_)/)) if ((chunk += part).length >= 12) { parts.push(chunk); chunk = ''; }
73
+ if (chunk) parts.push(chunk);
74
+ s.replaceChildren();
75
+ parts.forEach((part, i) => { if (i) s.appendChild(document.createElement('wbr')); s.appendChild(document.createTextNode(part)); });
76
+ });
77
+ };
78
+ const ident = (e) => {
79
+ e.className = 'id';
80
+ if (!unbroken.length) (window.requestAnimationFrame || setTimeout)(addBreaks);
81
+ unbroken.push(e);
82
+ return e;
83
+ };
84
+ // a block naming one test, optionally followed by a note such as "(skipped)" or "(Real sleep, 1.02 s)", whose numbers keep their units
85
+ const testLine = (tag, test, parent, note) => {
86
+ if (!note) return ident(el(tag, test, parent));
87
+ const e = el(tag, '', parent); ident(el('span', test, e));
88
+ e.append(' ' + note.replace(/(\d) (?=s\b|%)/g, '$1\u00a0'));
89
+ return e;
90
+ };
23
91
  let selected = 0, tab = 'Metrics', picked = null;
24
92
  const NS = 'http://www.w3.org/2000/svg';
25
- function drawMap(parent) {
26
- const near = picked ? new Map(picked.similar) : new Map();
27
- const svg = document.createElementNS(NS, 'svg');
28
- parent.appendChild(svg);
29
- // tests with the same or nearly the same coverage land on or near one place: push apart each pair of dots that
30
- // overlaps until none does, so every dot stays clickable; same data, same pushes, same map on every load
31
- // ponytail: all pairs per pass, quadratic; a spatial grid if maps of thousands of dots get slow
93
+ // tests with the same or nearly the same coverage land on or near one place: push apart each pair of dots that
94
+ // overlaps until none does, so every dot stays clickable; same data, same pushes, same map on every load.
95
+ // Computed once, on first opening: selecting a dot never moves one.
96
+ // ponytail: all pairs per pass, quadratic; a spatial grid if maps of thousands of dots get slow
97
+ let placed = null;
98
+ function place() {
32
99
  const dots = data.map.map((d) => ({ d, cx: 20 + d.x * 360, cy: 20 + d.y * 260, r: 4 + Math.min(10, d.runtime * 4) }));
33
100
  for (let pass = 0, moved = true; moved && pass < 200; pass++) {
34
101
  moved = false;
@@ -42,70 +109,161 @@ function drawMap(parent) {
42
109
  moved = true;
43
110
  }));
44
111
  }
45
- // the view grows to hold every ring, at one unit per pixel so sizes keep their meaning
112
+ // the view grows to hold every ring; the drawing then scales to the width it gets, dots and gaps alike
46
113
  const x0 = Math.min(0, ...dots.map((o) => o.cx - o.r - 2)), y0 = Math.min(0, ...dots.map((o) => o.cy - o.r - 2));
47
114
  const w = Math.max(400, ...dots.map((o) => o.cx + o.r + 2)) - x0, h = Math.max(300, ...dots.map((o) => o.cy + o.r + 2)) - y0;
48
- svg.setAttribute('viewBox', `${x0} ${y0} ${w} ${h}`); svg.setAttribute('width', w); svg.setAttribute('height', h);
115
+ return { dots, x0, y0, w, h };
116
+ }
117
+ function drawMap(parent) {
118
+ const { dots, x0, y0, w, h } = placed || (placed = place());
119
+ const legend = el('p', 'Colour shows unique lines: grey 0, amber 1–3, green 4+. Dot size shows runtime: slower tests are larger. Hover a dot for its test; click it to select.', parent);
120
+ legend.setAttribute('data-testid', 'map-legend');
121
+ const box = el('div', '', parent); box.className = 'map';
122
+ const svg = document.createElementNS(NS, 'svg');
123
+ box.appendChild(svg);
124
+ svg.setAttribute('viewBox', `${x0} ${y0} ${w} ${h}`);
125
+ const circles = new Map();
49
126
  dots.forEach(({ d, cx, cy, r }) => {
50
127
  const c = document.createElementNS(NS, 'circle');
51
128
  c.setAttribute('cx', cx); c.setAttribute('cy', cy);
52
129
  c.setAttribute('r', r);
53
130
  c.setAttribute('fill', d.unique === 0 ? '#9ca3af' : d.unique < 4 ? '#f59e0b' : '#16a34a');
54
- c.setAttribute('stroke', picked && (picked === d || near.has(d.test)) ? '#2563eb' : 'none');
55
131
  c.setAttribute('stroke-width', '3');
56
132
  c.setAttribute('data-testid', 'map-dot'); c.dataset.test = d.test;
57
- if (picked && (picked === d || near.has(d.test))) c.dataset.highlighted = 'true';
58
- c.onclick = () => { picked = d; render(); };
133
+ el('title', d.test, c);
134
+ circles.set(d.test, c);
135
+ c.onclick = () => pick(d);
59
136
  svg.appendChild(c);
60
137
  });
61
- const list = el('div', '', parent); list.setAttribute('data-testid', 'map-similar');
62
- if (picked) picked.similar.forEach(([n, s]) => el('p', n + ' ' + s.toFixed(2), list).setAttribute('data-testid', 'map-similar-item'));
138
+ const side = el('div', '', box); side.className = 'map-side';
139
+ const hint = el('p', 'Click a dot to see its test and the tests that cover nearly the same lines.', side);
140
+ const pickedName = el('p', '', side); pickedName.setAttribute('data-testid', 'map-picked');
141
+ const list = el('div', '', side); list.setAttribute('data-testid', 'map-similar');
142
+ let lit = [];
143
+ // selection touches only the previous and the new highlights and the neighbour list, never the placement
144
+ const pick = (d) => {
145
+ picked = d;
146
+ lit.forEach((c) => { c.setAttribute('stroke', 'none'); delete c.dataset.highlighted; });
147
+ const sims = d.similar.slice().sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
148
+ lit = [d.test, ...sims.map(([n]) => n)].map((n) => circles.get(n)).filter(Boolean);
149
+ lit.forEach((c) => { c.setAttribute('stroke', '#2563eb'); c.dataset.highlighted = 'true'; });
150
+ hint.hidden = true;
151
+ pickedName.replaceChildren();
152
+ el('strong', 'Selected', pickedName); el('br', '', pickedName); ident(el('span', d.test, pickedName));
153
+ list.replaceChildren();
154
+ if (!sims.length) { el('p', 'No test covers similar lines.', list); return; }
155
+ el('p', sims.length + (sims.length === 1 ? ' similar test' : ' similar tests') + ', highest Jaccard similarity first; 1.00 means identical coverage', list);
156
+ // built off the page and attached once: one insertion instead of hundreds keeps a 148-neighbour selection fast
157
+ const table = document.createElement('div'); table.className = 'similar';
158
+ const head = el('div', '', table); head.className = 'head';
159
+ el('span', 'Test', head); el('span', 'Jaccard', head).className = 'num';
160
+ sims.forEach(([n, s]) => {
161
+ const row = el('div', '', table); row.setAttribute('data-testid', 'map-similar-item');
162
+ ident(el('span', n, row)); row.append(' '); el('span', s.toFixed(2), row).className = 'num';
163
+ });
164
+ list.appendChild(table);
165
+ };
166
+ if (picked) pick(picked);
167
+ }
168
+ const PAGE = 100;
169
+ // highest similarity first; ties by identities, so the order does not depend on how the pairs arrive
170
+ const byIdentity = (o) => o.tests.slice().sort().join('\n');
171
+ const ranked = data.overlaps.slice().sort((a, b) => b.jaccard - a.jaccard || (byIdentity(a) < byIdentity(b) ? -1 : byIdentity(a) > byIdentity(b) ? 1 : 0));
172
+ let ovQuery = '', ovPage = 0;
173
+ function drawOverlaps(parent) {
174
+ const box = el('div', '', parent);
175
+ const input = document.createElement('input');
176
+ input.type = 'search'; input.placeholder = 'Search test identities'; input.value = ovQuery; input.setAttribute('aria-label', 'Search overlapping tests');
177
+ input.setAttribute('data-testid', 'overlap-search');
178
+ box.appendChild(input);
179
+ const out = el('div', '', box);
180
+ const draw = () => {
181
+ out.replaceChildren();
182
+ const q = ovQuery.toLowerCase();
183
+ const hits = q ? ranked.filter((o) => o.tests.some((t) => t.toLowerCase().includes(q))) : ranked;
184
+ const pages = Math.max(1, Math.ceil(hits.length / PAGE));
185
+ ovPage = Math.min(ovPage, pages - 1);
186
+ el('p', hits.length.toLocaleString('en-US') + (hits.length === 1 ? ' pair' : ' pairs'), out).setAttribute('data-testid', 'overlap-count');
187
+ if (!hits.length) el('p', 'No pair matches this search.', out).setAttribute('data-testid', 'overlap-empty');
188
+ // a page is built off the page and attached once: one insertion instead of hundreds
189
+ const rows = document.createDocumentFragment();
190
+ hits.slice(ovPage * PAGE, (ovPage + 1) * PAGE).forEach((o) => {
191
+ const row = el('div', '', rows);
192
+ row.setAttribute('data-testid', 'overlap-pair'); row.className = 'pair';
193
+ el('strong', 'Jaccard ' + o.jaccard.toFixed(2), row);
194
+ // the two tests on their own lines, a dashed rule between them
195
+ o.tests.forEach((t, k) => { if (k) el('hr', '', row); testLine('div', t, row).setAttribute('data-testid', 'overlap-test'); });
196
+ });
197
+ out.appendChild(rows);
198
+ const nav = el('p', '', out);
199
+ const step = (text, d, id) => { const b = el('button', text, nav); b.setAttribute('data-testid', id); b.disabled = ovPage + d < 0 || ovPage + d >= pages; b.onclick = () => { ovPage += d; draw(); }; };
200
+ step('Previous', -1, 'overlap-prev');
201
+ el('span', ' Page ' + (ovPage + 1) + ' of ' + pages + ' ', nav);
202
+ step('Next', 1, 'overlap-next');
203
+ };
204
+ input.oninput = () => { ovQuery = input.value; ovPage = 0; draw(); };
205
+ draw();
63
206
  }
64
207
  function render() {
65
208
  document.getElementById('inventory').textContent = data.inventory;
66
209
  const banner = document.getElementById('banner');
67
210
  if (banner) { if (data.banner) banner.textContent = data.banner; else banner.remove(); }
211
+ const failing = document.getElementById('failing'); failing.replaceChildren();
212
+ data.failing.forEach((n) => testLine('p', n, failing).setAttribute('data-testid', 'failing-test'));
68
213
  const gauges = document.getElementById('gauges'), details = document.getElementById('details');
69
214
  gauges.replaceChildren(); details.replaceChildren();
70
215
  data.pillars.forEach((p, i) => {
71
216
  const g = el('button', '', gauges);
72
217
  g.className = 'gauge'; g.dataset.testid = 'gauge'; g.setAttribute('data-testid', 'gauge');
73
218
  g.setAttribute('aria-pressed', i === selected);
74
- el('span', p.name, g);
219
+ el('span', p.name, g).setAttribute('data-testid', 'gauge-title');
75
220
  el('span', p.score === null ? '–' : shown(p.score), g).className = 'score';
76
- if (p.partial) el('span', 'partial: ' + p.metrics.length + ' of ' + p.total + ' metrics measured', g).className = 'flag';
221
+ const status = el('span', p.partial ? 'partial: ' + p.metrics.length + ' of ' + p.total + ' metrics measured' : 'all ' + p.total + ' metrics measured', g);
222
+ status.className = 'gauge-status' + (p.partial ? ' flag' : ''); status.setAttribute('data-testid', 'gauge-status');
77
223
  g.onclick = () => { selected = i; tab = 'Metrics'; picked = null; render(); };
78
224
  });
79
225
  const p = data.pillars[selected];
80
226
  el('h2', p.name, details);
81
227
  const names = ['Metrics', 'Worst tests', 'Smells', ...(p.key === 'economy' ? ['Overlaps', 'Map'] : [])];
82
- names.forEach((n) => { const b = el('button', n, details); b.setAttribute('aria-pressed', n === tab); b.onclick = () => { tab = n; picked = null; render(); }; });
228
+ const tabs = el('div', '', details); tabs.className = 'tabs';
229
+ names.forEach((n) => { const b = el('button', n, tabs); b.setAttribute('aria-pressed', n === tab); b.onclick = () => { tab = n; picked = null; render(); }; });
83
230
  el('h3', tab, details);
84
231
  if (tab === 'Metrics') {
232
+ if (!p.metrics.length) el('p', 'No metrics were measured for this pillar.', details);
85
233
  const t = el('table', '', details);
234
+ const head = el('tr', '', t);
235
+ ['Metric', 'Value', 'Score', 'Anchors'].forEach((h) => el('th', h, head));
86
236
  p.metrics.forEach((m) => {
237
+ const u = m.unit || '', up = m.target < m.bad;
238
+ const r = el('tr', '', t);
239
+ el('td', m.name, r); el('td', nb(fmt(m.value), u), r); el('td', String(shown(m.score)), r);
240
+ el('td', nb('target', up ? '≤' : '≥', fmt(m.target), u) + ', ' + nb('bad', up ? '≥' : '≤', fmt(m.bad), u), r);
241
+ });
242
+ p.missing.forEach((m) => {
87
243
  const r = el('tr', '', t);
88
- el('td', m.name, r); el('td', fmt(m.value), r); el('td', String(shown(m.score)), r);
244
+ // no value, so no score or anchors: the reason takes their place
245
+ el('td', m.name, r); el('td', 'unmeasured: ' + (m.reason || 'unavailable (cause not recorded)'), r).colSpan = 3;
89
246
  });
247
+ el('p', 'Scores are rounded and shown as 1 to 99, not 100 or 0. A metric at its target scores 90 and at its bad anchor 10; the logistic curve between them never reaches 0 or 100.', details);
90
248
  if (data.skipped.length) {
91
249
  el('h3', 'Skipped tests', details);
92
- data.skipped.forEach((n) => el('p', n + ' (skipped)', details));
250
+ data.skipped.forEach((n) => testLine('p', n, details, '(skipped)'));
93
251
  }
94
252
  if (p.key === 'economy' && data.insufficient.length) {
95
253
  el('h3', 'Insufficient evidence (fewer than 2 sampled mutants on their lines)', details);
96
- data.insufficient.forEach((n) => el('p', n, details));
254
+ data.insufficient.forEach((n) => testLine('p', n, details));
97
255
  }
98
256
  } else if (tab === 'Worst tests') {
99
- p.worst.forEach((w) => el('p', w.test + ' (' + w.reason + ')', details).setAttribute('data-testid', 'worst-test'));
257
+ p.worst.forEach((w) => testLine('p', w.test, details, '(' + w.reason + ')').setAttribute('data-testid', 'worst-test'));
100
258
  } else if (tab === 'Smells') {
101
259
  const smells = Object.entries(p.smells);
102
260
  if (!smells.length) el('p', 'No test has a smell of this pillar.', details);
103
261
  smells.forEach(([smell, tests]) => {
104
262
  el('h4', smell + ' (' + tests.length + (tests.length === 1 ? ' test)' : ' tests)'), details).setAttribute('data-testid', 'smell');
105
- tests.forEach((n) => el('p', n, details).setAttribute('data-testid', 'smell-test'));
263
+ tests.forEach((n) => testLine('p', n, details).setAttribute('data-testid', 'smell-test'));
106
264
  });
107
265
  } else if (tab === 'Overlaps') {
108
- data.overlaps.forEach((o) => el('p', o.tests.join(' ~ ') + ' ' + o.jaccard.toFixed(2), details));
266
+ drawOverlaps(details);
109
267
  } else if (tab === 'Map') drawMap(details);
110
268
  }
111
269
  render();