forgeproof-cli 0.2.0__py3-none-any.whl

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 (89) hide show
  1. forge_gate/__init__.py +44 -0
  2. forge_gate/_deprecated_cli.py +16 -0
  3. forgeproof/__init__.py +3 -0
  4. forgeproof/catalog.py +110 -0
  5. forgeproof/cli.py +560 -0
  6. forgeproof/config.py +339 -0
  7. forgeproof/data/gate_catalog.json +66 -0
  8. forgeproof/data/host_sets.json +7 -0
  9. forgeproof/debug_caller.py +271 -0
  10. forgeproof/debug_core.py +368 -0
  11. forgeproof/fixture_engine.py +81 -0
  12. forgeproof/fixtures/__init__.py +19 -0
  13. forgeproof/fixtures/decision_tree_id3.py +90 -0
  14. forgeproof/fixtures/gradient_descent_momentum.py +73 -0
  15. forgeproof/fixtures/kmeans_clustering.py +98 -0
  16. forgeproof/fixtures/knn_classifier.py +79 -0
  17. forgeproof/fixtures/linear_regression_gd.py +77 -0
  18. forgeproof/fixtures/logistic_regression.py +85 -0
  19. forgeproof/fixtures/naive_bayes_text.py +114 -0
  20. forgeproof/fixtures/perceptron.py +84 -0
  21. forgeproof/fixtures/polynomial_regression.py +67 -0
  22. forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
  23. forgeproof/ledger.py +633 -0
  24. forgeproof/lens_tools/__init__.py +11 -0
  25. forgeproof/lens_tools/guard_lens.py +1250 -0
  26. forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
  27. forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
  28. forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
  29. forgeproof/lens_tools/invariant_gate.py +199 -0
  30. forgeproof/lens_tools/metamorphic/__init__.py +9 -0
  31. forgeproof/lens_tools/metamorphic/relations.py +962 -0
  32. forgeproof/lens_tools/metamorphic/runner.py +112 -0
  33. forgeproof/lens_tools/twin_consensus.py +395 -0
  34. forgeproof/lenses.py +923 -0
  35. forgeproof/paths.py +56 -0
  36. forgeproof/reference/ORIGIN.md +29 -0
  37. forgeproof/reference/decision_tree_id3.py +197 -0
  38. forgeproof/reference/gradient_descent_momentum.py +141 -0
  39. forgeproof/reference/kmeans_clustering.py +139 -0
  40. forgeproof/reference/knn_classifier.py +118 -0
  41. forgeproof/reference/linear_regression_gd.py +106 -0
  42. forgeproof/reference/logistic_regression.py +141 -0
  43. forgeproof/reference/naive_bayes_text.py +152 -0
  44. forgeproof/reference/perceptron.py +123 -0
  45. forgeproof/reference/polynomial_regression.py +125 -0
  46. forgeproof/reference/ridge_regression_normal_eq.py +165 -0
  47. forgeproof/runner.py +147 -0
  48. forgeproof/scout/__init__.py +7 -0
  49. forgeproof/scout/behaviour.py +365 -0
  50. forgeproof/scout/box.py +581 -0
  51. forgeproof/scout/cards.py +180 -0
  52. forgeproof/scout/contract.py +37 -0
  53. forgeproof/scout/corpus.py +104 -0
  54. forgeproof/scout/embed.py +217 -0
  55. forgeproof/scout/engines/__init__.py +1 -0
  56. forgeproof/scout/engines/chaos.py +454 -0
  57. forgeproof/scout/engines/chaos_port.py +1331 -0
  58. forgeproof/scout/engines/chaos_runner.py +178 -0
  59. forgeproof/scout/engines/executor_port.py +239 -0
  60. forgeproof/scout/envfit.py +54 -0
  61. forgeproof/scout/experience.py +161 -0
  62. forgeproof/scout/fetchproxy.py +368 -0
  63. forgeproof/scout/ghcache.py +395 -0
  64. forgeproof/scout/ghpool.py +253 -0
  65. forgeproof/scout/ghsearch.py +248 -0
  66. forgeproof/scout/ids.py +82 -0
  67. forgeproof/scout/intent_lens.py +170 -0
  68. forgeproof/scout/learn.py +583 -0
  69. forgeproof/scout/meaning_lens.py +231 -0
  70. forgeproof/scout/outcomes.py +42 -0
  71. forgeproof/scout/plant.py +327 -0
  72. forgeproof/scout/ratify.py +214 -0
  73. forgeproof/scout/report.py +448 -0
  74. forgeproof/scout/rule2.py +177 -0
  75. forgeproof/scout/shape.py +107 -0
  76. forgeproof/scout/shape_lens.py +71 -0
  77. forgeproof/scout/signature.py +52 -0
  78. forgeproof/scout/slots.py +39 -0
  79. forgeproof/scout/upstream_facts.py +536 -0
  80. forgeproof/unsupported.py +83 -0
  81. forgeproof/verifier.py +208 -0
  82. forgeproof/view_coverage.py +166 -0
  83. forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
  84. forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
  85. forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
  86. forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
  87. forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
  88. forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
  89. forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,536 @@
1
+ """The GitHub fact tool: would this project's own tests notice a bug in this function?
2
+ (GitHub-lane loop S3, DESIGN github-lane-2026-11 §5 rules R0-R8.)
3
+
4
+ ``forgeproof github-facts ORG/REPO@SHA [--functions ...]``. For every admitted top-level function
5
+ (admission is ``ghpool.admit``, read only), it plants up to 12 single-node bugs (``plant``, R5),
6
+ runs the repo's OWN unittest suite in the run-mode isolation box once per bug, and appends one
7
+ FACT ROW per function to ``$FORGE_GATE_SCOUT_DIR/github_facts.jsonl``. A fact row is never a PASS
8
+ and never a card: this module imports neither ``learn`` nor ``cards`` and writes nothing else
9
+ (its own throwaway staging folder under the box root is removed after each module).
10
+
11
+ Rules, as built:
12
+ - R0: no ``FORGE_GATE_BOX_USER`` -> one run row BLIND(box-user-unset); nothing is admitted or run.
13
+ - R1: the suite runs unmutated before a function's mutants and after them (the "after" control
14
+ of one function is the "before" control of the next in the same module). Both must exit 0 with
15
+ >= 1 test and the same set of passing test ids, else BLIND(control-red | control-unstable |
16
+ no-tests). A red "before" control skips that function's mutants.
17
+ - R2: every box run is ``env PYTHONHASHSEED=0 python3 -m fg_unittest_json --module M`` in
18
+ ``/work`` (the repo root), the runner copied to the work root.
19
+ - R3: CAUGHT only when the box outcome is FOUND, rc == 1, the runner's JSON names >= 1 test that
20
+ failed or errored AND passed in both controls, no failing test's error is a MemoryError or
21
+ RecursionError, and one re-run of the same mutant fails that same test again (rc 1).
22
+ SURVIVED = rc 0 and every control-passing test passed. Everything else is UNCLEAR(reason).
23
+ - R4: every run's import proof (start and end of the suite) must name a file under ``/work`` whose
24
+ sha256 equals the bytes we wrote; any run that fails it makes the function BLIND(wrong-module).
25
+ - R6: mutant timeout = 3 x the median control time, clamped to [60, 300] s; controls get 300 s.
26
+ Every box run waits while the 1-minute load average > 4.0. After the first control, the
27
+ projected wall time sum((1 + 2 m_f) x median control) (every mutant re-run, the worst case)
28
+ over the selected functions is compared with 4 h; over it, only the first N functions in source
29
+ order that fit are run, the rest are BLIND(budget-cut ...). Before each function the elapsed
30
+ time plus that function's projected cost is also checked against 4 h (BLIND(budget-cut:
31
+ elapsed ...)), so a projection that was too low cannot run past the budget.
32
+ - R7: ``ghcache.check_cache(full=True)`` once before each module's runs; its result is in every
33
+ row of that module.
34
+ - R8: the row schema below; ``outcome`` is MEASURED or BLIND(reason). k, s, u are recomputable
35
+ from the per-mutant records.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import hashlib
40
+ import json
41
+ import os
42
+ import platform
43
+ import secrets
44
+ import shutil
45
+ import statistics
46
+ import tempfile
47
+ import time
48
+ from dataclasses import dataclass, field
49
+ from pathlib import Path, PurePosixPath
50
+
51
+ from .. import config
52
+ from . import box, ghcache, ghpool, plant
53
+
54
+ TOOL_VERSION = "github-facts/1 (S3)"
55
+ FACTS_NAME = "github_facts.jsonl"
56
+ RUNNER = "fg_unittest_json"
57
+ TIMEOUT_FACTOR, TIMEOUT_MIN, TIMEOUT_MAX = 3, 60.0, 300.0
58
+ CONTROL_TIMEOUT = TIMEOUT_MAX
59
+ LOAD_MAX = 4.0
60
+ LOAD_POLL_S = 15.0
61
+ LOAD_WAIT_MAX_S = 3600.0
62
+ BUDGET_S = 4 * 3600.0
63
+ RESOURCE_ERRORS = frozenset({"MemoryError", "RecursionError"})
64
+ MEASURED = "MEASURED"
65
+ CAUGHT, SURVIVED, UNCLEAR = "CAUGHT", "SURVIVED", "UNCLEAR"
66
+
67
+
68
+ @dataclass
69
+ class FactsResult:
70
+ run_id: str
71
+ rows: list = field(default_factory=list)
72
+ facts_file: str = ""
73
+ run_blind: str | None = None # a run-level BLIND (R0, admission, box unavailable)
74
+
75
+ @property
76
+ def measured(self) -> int:
77
+ return sum(1 for r in self.rows if r.get("outcome") == MEASURED)
78
+
79
+
80
+ def runner_file() -> Path | None:
81
+ h = config.home()
82
+ if h is not None and (Path(h) / "tools" / f"{RUNNER}.py").is_file():
83
+ return Path(h) / "tools" / f"{RUNNER}.py"
84
+ p = Path(__file__).resolve().parents[3] / "tools" / f"{RUNNER}.py"
85
+ return p if p.is_file() else None
86
+
87
+
88
+ def module_name(path: str) -> str:
89
+ parts = list(PurePosixPath(path).with_suffix("").parts)
90
+ if parts[-1] == "__init__":
91
+ parts = parts[:-1]
92
+ return ".".join(parts)
93
+
94
+
95
+ def test_argv(module: str) -> list[str]:
96
+ return ["env", "PYTHONHASHSEED=0", "python3", "-m", RUNNER, "--module", module]
97
+
98
+
99
+ def mutant_timeout(control_seconds: list[float]) -> float:
100
+ med = statistics.median(control_seconds) if control_seconds else TIMEOUT_MAX / TIMEOUT_FACTOR
101
+ return float(min(TIMEOUT_MAX, max(TIMEOUT_MIN, TIMEOUT_FACTOR * med)))
102
+
103
+
104
+ def _default_run_box(stage: Path, argv: list[str], timeout: float, label: str) -> box.BoxResult:
105
+ return box.run(stage, argv, mode="run", timeout=timeout)
106
+
107
+
108
+ class _Ctx:
109
+ def __init__(self, run_id, facts, run_box, loadavg, sleep, clock):
110
+ self.run_id, self.facts, self.run_box = run_id, facts, run_box
111
+ self.loadavg, self.sleep, self.clock = loadavg, sleep, clock
112
+ self.control_seconds: list[float] = []
113
+ self.started = clock()
114
+ self.box_user = box.box_user()
115
+
116
+
117
+ def run(spec: str, functions: list[str] | None = None, *, gh_opts: dict | None = None, run_box=None,
118
+ loadavg=os.getloadavg, sleep=time.sleep, clock=time.monotonic) -> FactsResult:
119
+ """Measure every admitted function of ``spec`` (or only ``functions``); append the rows.
120
+ ``gh_opts`` (list_file, signers_file, cache_root, trust_pin_value, host_sets_file) and
121
+ ``run_box`` / ``loadavg`` / ``sleep`` / ``clock`` exist for tests."""
122
+ facts = config.scout_dir() / FACTS_NAME # NotConfigured propagates: no place for the rows
123
+ run_id = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + "-" + secrets.token_hex(4)
124
+ ctx = _Ctx(run_id, facts, run_box or _default_run_box, loadavg, sleep, clock)
125
+ res = FactsResult(run_id, facts_file=str(facts))
126
+ opts = dict(gh_opts or {})
127
+
128
+ def run_row(reason: str) -> FactsResult:
129
+ res.run_blind = reason
130
+ row = _base_row(ctx, spec, None, None, None)
131
+ row["outcome"] = f"BLIND({reason})"
132
+ row["scope"] = "run"
133
+ _append(facts, row)
134
+ res.rows.append(row)
135
+ return res
136
+
137
+ # R0: before anything is read or run.
138
+ if not ctx.box_user:
139
+ return run_row("box-user-unset")
140
+ why = box.available()
141
+ if why:
142
+ return run_row(why)
143
+ runner = runner_file()
144
+ if runner is None:
145
+ return run_row("runner-missing")
146
+ m = ghpool._SPEC.fullmatch(spec or "")
147
+ if not m:
148
+ return run_row(f"unsigned: not org/repo@<40 hex>: {spec!r}")
149
+ org, repo, commit = m.groups()
150
+ root = Path(opts["cache_root"]) if opts.get("cache_root") is not None else ghcache.cache_root()
151
+ try:
152
+ store, tree_dir, _pin = ghcache._paths(root, org, repo, commit)
153
+ tree = ghcache.tree_files(store, commit)
154
+ except Exception as e: # noqa: BLE001 - an unreadable cache is BLIND, never a traceback
155
+ return run_row(f"pin-mismatch: cache unreadable: {type(e).__name__}: {e}"[:300])
156
+
157
+ # Admission, read only: every .py path in the pinned tree goes through ghpool.admit.
158
+ admitted: dict[str, bytes] = {}
159
+ excluded: dict[str, int] = {}
160
+ for path in sorted(p for p in tree if p.endswith(".py")):
161
+ try:
162
+ a = ghpool.admit(spec, path, **opts)
163
+ except ghpool.NotAdmitted as e:
164
+ reason = str(e)
165
+ if reason.startswith(("unsigned", "pin-mismatch", "licence:")):
166
+ return run_row(reason[:300]) # repo-level: nothing is measured
167
+ excluded[reason.split(":")[0]] = excluded.get(reason.split(":")[0], 0) + 1
168
+ continue
169
+ admitted[path] = a.data
170
+ ctx.admission = {"admitted_files": sorted(admitted), "excluded": excluded}
171
+
172
+ # Selection in source order: files by path, functions as they appear.
173
+ selected: list[tuple[str, str]] = []
174
+ unparsable: list[str] = []
175
+ for path, data in admitted.items():
176
+ try:
177
+ names = plant.functions(data)
178
+ except plant.PlantError:
179
+ unparsable.append(path)
180
+ continue
181
+ selected += [(path, n) for n in names]
182
+ if functions:
183
+ want = list(functions)
184
+ keep = [(p, n) for p, n in selected if n in want or f"{p}::{n}" in want
185
+ or f"{module_name(p)}:{n}" in want]
186
+ matched = {n for _p, n in keep} | {f"{p}::{n}" for p, n in keep} | {f"{module_name(p)}:{n}" for p, n in keep}
187
+ for w in want:
188
+ if w not in matched:
189
+ row = _base_row(ctx, spec, None, None, w)
190
+ row["outcome"] = "BLIND(function-not-admitted)"
191
+ _append(facts, row)
192
+ res.rows.append(row)
193
+ selected = keep
194
+
195
+ plans: dict[tuple[str, str], object] = {}
196
+ for path, name in selected:
197
+ try:
198
+ plans[(path, name)] = plant.plant(admitted[path], name)
199
+ except plant.PlantError as e:
200
+ plans[(path, name)] = e
201
+
202
+ by_module: dict[str, list[str]] = {}
203
+ for path, name in selected:
204
+ by_module.setdefault(path, []).append(name)
205
+ budget = {"n": None}
206
+ order = list(selected)
207
+ for path in sorted(by_module):
208
+ _measure_module(ctx, res, spec, org, repo, commit, tree, tree_dir, root, path, admitted[path],
209
+ by_module[path], plans, runner, budget, order, opts)
210
+ return res
211
+
212
+
213
+ def _measure_module(ctx, res, spec, org, repo, commit, tree, tree_dir, root, path, data, names, plans,
214
+ runner, budget, order, opts) -> None:
215
+ mod = module_name(path)
216
+
217
+ def emit(row):
218
+ _append(ctx.facts, row)
219
+ res.rows.append(row)
220
+
221
+ def blind_all(reason, todo, extra=None):
222
+ for n in todo:
223
+ row = _base_row(ctx, spec, path, mod, n, extra)
224
+ row["outcome"] = f"BLIND({reason})"
225
+ emit(row)
226
+
227
+ # The package chain must be importable from /work.
228
+ parts = PurePosixPath(path).parts
229
+ missing = [str(PurePosixPath(*parts[:i], "__init__.py")) for i in range(1, len(parts))
230
+ if str(PurePosixPath(*parts[:i], "__init__.py")) not in tree]
231
+ if missing:
232
+ return blind_all(f"not-importable: no {missing[0]}", names)
233
+ if f"{RUNNER}.py" in tree:
234
+ return blind_all(f"runner-name-taken: the repo has its own {RUNNER}.py", names)
235
+ # R7: the full tree check once per module, before its runs.
236
+ try:
237
+ verdict = ghpool.admit(spec, path, **opts).verdict
238
+ pin = ghcache.check_cache(org, repo, commit, verdict, full=True, root=root)
239
+ r7 = {"ok": True, "full": True, "tree": pin.get("tree")}
240
+ except (ghpool.NotAdmitted, ghcache.PinMismatch) as e:
241
+ return blind_all(f"pin-mismatch: {e}"[:300], names, {"tree_check": {"ok": False, "error": str(e)[:300]}})
242
+
243
+ stage_root = box.box_root()
244
+ stage_root.mkdir(parents=True, exist_ok=True)
245
+ tmp = Path(tempfile.mkdtemp(prefix="facts-", dir=stage_root))
246
+ try:
247
+ stage = tmp / "t"
248
+ box._plain_copy(tree_dir, stage)
249
+ shutil.copyfile(runner, stage / f"{RUNNER}.py")
250
+ target = stage.joinpath(*PurePosixPath(path).parts)
251
+ argv = test_argv(mod)
252
+ prev_control = None
253
+ for name in names:
254
+ plan = plans[(path, name)]
255
+ extra = {"tree_check": r7, "test_argv": argv}
256
+ if isinstance(plan, plant.PlantError):
257
+ row = _base_row(ctx, spec, path, mod, name, extra)
258
+ row["outcome"] = f"BLIND(not-plantable: {plan})"[:300]
259
+ emit(row)
260
+ continue
261
+ if budget["n"] is not None and order.index((path, name)) >= budget["n"]:
262
+ row = _base_row(ctx, spec, path, mod, name, extra)
263
+ row["outcome"] = f"BLIND(budget-cut: first {budget['n']} of {len(order)} functions fit {int(BUDGET_S)} s)"
264
+ row["budget"] = dict(budget)
265
+ emit(row)
266
+ continue
267
+ if not plan.mutants:
268
+ row = _row_with_plan(ctx, spec, path, mod, name, plan, extra)
269
+ row["outcome"] = "BLIND(no-mutants)"
270
+ emit(row)
271
+ continue
272
+ if budget.get("median_control_s") is not None:
273
+ elapsed = ctx.clock() - ctx.started
274
+ need = (1 + 2 * len(plan.mutants)) * budget["median_control_s"]
275
+ if elapsed + need > BUDGET_S:
276
+ row = _base_row(ctx, spec, path, mod, name, extra)
277
+ row["outcome"] = f"BLIND(budget-cut: elapsed {int(elapsed)} s + {int(need)} s > {int(BUDGET_S)} s)"
278
+ row["budget"] = dict(budget, elapsed_s=round(elapsed, 1))
279
+ emit(row)
280
+ continue
281
+ before = prev_control or _box_run(ctx, stage, target, data, argv, CONTROL_TIMEOUT, "control")
282
+ if budget["n"] is None:
283
+ _budget(ctx, budget, order, plans)
284
+ if budget["n"] is not None and order.index((path, name)) >= budget["n"]:
285
+ row = _base_row(ctx, spec, path, mod, name, extra)
286
+ row["outcome"] = f"BLIND(budget-cut: first {budget['n']} of {len(order)} functions fit {int(BUDGET_S)} s)"
287
+ row["budget"] = dict(budget)
288
+ emit(row)
289
+ prev_control = before
290
+ continue
291
+ row = _row_with_plan(ctx, spec, path, mod, name, plan, extra)
292
+ bad = _control_bad(before)
293
+ if bad:
294
+ row["controls"] = [_control_view(before), None]
295
+ row["outcome"] = f"BLIND({bad})"
296
+ emit(row)
297
+ prev_control = None # the next function takes a fresh control
298
+ continue
299
+ tmo = mutant_timeout(ctx.control_seconds)
300
+ row["timeout_s"] = tmo
301
+ records = []
302
+ for mu in plan.mutants:
303
+ first = _box_run(ctx, stage, target, mu.source, argv, tmo, f"mutant:{mu.id}")
304
+ rerun = None
305
+ if _wants_rerun(first, before):
306
+ rerun = _box_run(ctx, stage, target, mu.source, argv, tmo, f"rerun:{mu.id}")
307
+ records.append((mu, first, rerun))
308
+ target.write_bytes(data)
309
+ after = _box_run(ctx, stage, target, data, argv, CONTROL_TIMEOUT, "control")
310
+ prev_control = after
311
+ row["controls"] = [_control_view(before), _control_view(after)]
312
+ row["control_times"] = [before.get("seconds"), after.get("seconds")]
313
+ row["box_python"] = (before.get("json") or {}).get("python")
314
+ muts = [_classify(mu, first, rerun, before, after) for mu, first, rerun in records]
315
+ row["mutants"] = muts
316
+ row["k"] = sum(1 for x in muts if x["outcome"] == CAUGHT)
317
+ row["s"] = sum(1 for x in muts if x["outcome"] == SURVIVED)
318
+ row["u"] = sum(1 for x in muts if x["outcome"].startswith(UNCLEAR))
319
+ row["outcome"] = _row_outcome(before, after, records, muts)
320
+ emit(row)
321
+ finally:
322
+ shutil.rmtree(tmp, ignore_errors=True) # our own staging folder, created above
323
+
324
+
325
+ # --- one box run -------------------------------------------------------------------------------------
326
+
327
+ def _wait_load(ctx) -> str | None:
328
+ waited = 0.0
329
+ while ctx.loadavg()[0] > LOAD_MAX:
330
+ if waited >= LOAD_WAIT_MAX_S:
331
+ return f"load-wait-exceeded: 1-min load > {LOAD_MAX} for {int(waited)} s"
332
+ ctx.sleep(LOAD_POLL_S)
333
+ waited += LOAD_POLL_S
334
+ return None
335
+
336
+
337
+ def _box_run(ctx, stage: Path, target: Path, data: bytes, argv, timeout: float, label: str) -> dict:
338
+ """Write ``data`` as the module, run the suite once in the box, parse and judge the proof.
339
+ kind: ok (a parsed report), box-timeout, box-blind, no-json."""
340
+ target.write_bytes(data)
341
+ expected = hashlib.sha256(data).hexdigest()
342
+ rec = {"label": label, "expected_sha": expected, "timeout_s": timeout}
343
+ why = _wait_load(ctx)
344
+ if why:
345
+ rec.update(kind="box-blind", box=f"BLIND({why})", rc=None, seconds=None)
346
+ return rec
347
+ t0 = ctx.clock()
348
+ r = ctx.run_box(stage, list(argv), timeout, label)
349
+ secs = round(ctx.clock() - t0, 3)
350
+ rec.update(box=r.outcome.label(), rc=r.returncode, seconds=secs)
351
+ if r.outcome.kind != "FOUND":
352
+ rec["kind"] = "box-timeout" if r.outcome.reason.startswith("timeout") else "box-blind"
353
+ return rec
354
+ try:
355
+ rep = json.loads((r.stdout or "").strip())
356
+ if not isinstance(rep, dict) or not isinstance(rep.get("results"), dict):
357
+ raise ValueError("not a runner report")
358
+ except ValueError:
359
+ rec["kind"] = "no-json"
360
+ rec["stderr_tail"] = (r.stderr or "")[-500:]
361
+ return rec
362
+ rec["kind"] = "ok"
363
+ rec["json"] = rep
364
+ rec["tests_run"] = rep.get("tests_run")
365
+ res = rep["results"]
366
+ rec["pass_set"] = sorted(t for t, v in res.items() if v.get("outcome") == "pass")
367
+ rec["pass_set_sha256"] = hashlib.sha256("\n".join(rec["pass_set"]).encode()).hexdigest()
368
+ rec["failing"] = sorted(t for t, v in res.items() if v.get("outcome") in ("fail", "error"))
369
+ rec["error_classes"] = {t: res[t].get("exc") for t in rec["failing"]}
370
+ rec["resource_errors"] = sorted(t for t in rec["failing"]
371
+ if RESOURCE_ERRORS & set(res[t].get("exc_mro") or [res[t].get("exc")]))
372
+ # R4: start and end proof; report the first one that fails (or the end one).
373
+ module = rep.get("module") or {}
374
+ proofs = [module.get("start") or {}, module.get("end") or {}]
375
+ bad = [p for p in proofs if not _proof_ok(p, expected)]
376
+ shown = bad[0] if bad else proofs[1]
377
+ rec["module_file"], rec["module_sha"] = shown.get("file"), shown.get("sha256")
378
+ rec["module_ok"] = not bad
379
+ # review F2: the module did not import at all (a mutant broke it): no copy was loaded, so this
380
+ # is not evidence of another copy; the mutant is UNCLEAR(import-error), the row unaffected.
381
+ rec["import_error"] = module.get("import_error") if not (module.get("start") or {}).get("file") else None
382
+ if label == "control" and r.returncode == 0:
383
+ ctx.control_seconds.append(secs)
384
+ return rec
385
+
386
+
387
+ def _proof_ok(p: dict, expected: str) -> bool:
388
+ f = p.get("file")
389
+ return (isinstance(f, str) and os.path.normpath(f).startswith("/work/") and p.get("sha256") == expected)
390
+
391
+
392
+ # --- judgement ------------------------------------------------------------------------------------------
393
+
394
+ def _control_bad(c: dict) -> str | None:
395
+ if c["kind"] != "ok":
396
+ return f"control-red: {c['kind']} {c.get('box', '')}".strip()
397
+ if c.get("import_error"):
398
+ return "control-red: import-error"
399
+ if not c["module_ok"]:
400
+ return "wrong-module"
401
+ if c["rc"] != 0:
402
+ return f"control-red: rc {c['rc']}"
403
+ if not isinstance(c.get("tests_run"), int) or c["tests_run"] < 1 or not c["pass_set"]:
404
+ return "no-tests"
405
+ return None
406
+
407
+
408
+ def _control_view(c: dict) -> dict:
409
+ return {"rc": c.get("rc"), "tests_run": c.get("tests_run"), "pass_set_sha256": c.get("pass_set_sha256"),
410
+ "seconds": c.get("seconds"), "box": c.get("box"), "kind": c.get("kind"),
411
+ "module_file": c.get("module_file"), "module_sha": c.get("module_sha"),
412
+ "expected_sha": c.get("expected_sha")}
413
+
414
+
415
+ def _wants_rerun(first: dict, before: dict) -> bool:
416
+ return (first["kind"] == "ok" and first["rc"] == 1 and first["module_ok"]
417
+ and bool(set(first["failing"]) & set(before.get("pass_set") or [])))
418
+
419
+
420
+ def _classify(mu, first: dict, rerun: dict | None, before: dict, after: dict) -> dict:
421
+ out = {"id": mu.id, "op": mu.op, "line": mu.line, "col": mu.col, "diff": mu.diff,
422
+ "rc": first.get("rc"), "box": first.get("box"), "seconds": first.get("seconds"),
423
+ "failing_ids": first.get("failing", []), "error_classes": first.get("error_classes", {}),
424
+ "rerun_failing_ids": (rerun or {}).get("failing", []) if rerun else None,
425
+ "rerun_rc": rerun.get("rc") if rerun else None,
426
+ "module_file": first.get("module_file"), "module_sha": first.get("module_sha"),
427
+ "expected_sha": first.get("expected_sha")}
428
+ if rerun is not None:
429
+ out["rerun_module_file"], out["rerun_module_sha"] = rerun.get("module_file"), rerun.get("module_sha")
430
+ ctrl = set(before.get("pass_set") or []) & set(after.get("pass_set") or [])
431
+ if first["kind"] == "box-timeout":
432
+ out["outcome"] = "UNCLEAR(timeout)"
433
+ elif first["kind"] == "box-blind":
434
+ out["outcome"] = f"UNCLEAR(box: {first.get('box')})"
435
+ elif first["kind"] == "no-json":
436
+ out["outcome"] = "UNCLEAR(no-runner-report)"
437
+ elif first.get("import_error"):
438
+ out["outcome"] = "UNCLEAR(import-error)"
439
+ elif not first["module_ok"] or (rerun is not None and rerun.get("kind") == "ok" and not rerun["module_ok"]):
440
+ out["outcome"] = "UNCLEAR(wrong-module)"
441
+ elif first["rc"] == 0:
442
+ passed = set(first["pass_set"])
443
+ out["outcome"] = SURVIVED if ctrl <= passed else "UNCLEAR(control-tests-not-passed)"
444
+ elif first["rc"] != 1:
445
+ out["outcome"] = f"UNCLEAR(rc {first['rc']})"
446
+ elif first["resource_errors"]:
447
+ cls = sorted({first["error_classes"][t] for t in first["resource_errors"]})
448
+ out["outcome"] = f"UNCLEAR(resource-error: {','.join(cls)})"
449
+ else:
450
+ hit = set(first["failing"]) & ctrl
451
+ if not hit:
452
+ out["outcome"] = "UNCLEAR(failed-only-outside-control)"
453
+ elif rerun is None or rerun.get("kind") != "ok" or rerun.get("rc") != 1:
454
+ out["outcome"] = "UNCLEAR(rerun-not-failing)"
455
+ elif rerun.get("resource_errors"):
456
+ out["outcome"] = "UNCLEAR(resource-error-on-rerun)"
457
+ elif not (hit & set(rerun["failing"])):
458
+ out["outcome"] = "UNCLEAR(rerun-not-failing)"
459
+ else:
460
+ out["outcome"] = CAUGHT
461
+ return out
462
+
463
+
464
+ def _row_outcome(before, after, records, muts) -> str:
465
+ runs = [before, after] + [r for _mu, a, b in records for r in (a, b) if r is not None]
466
+ if any(r.get("kind") == "ok" and not r["module_ok"] and not r.get("import_error") for r in runs):
467
+ return "BLIND(wrong-module)"
468
+ bad = _control_bad(after)
469
+ if bad:
470
+ return f"BLIND({bad})"
471
+ if before["pass_set_sha256"] != after["pass_set_sha256"]:
472
+ return "BLIND(control-unstable)"
473
+ boxbad = [r for r in runs if r.get("kind") == "box-blind"]
474
+ if boxbad:
475
+ return f"BLIND(box: {boxbad[0].get('box')})"[:300]
476
+ if not muts:
477
+ return "BLIND(no-mutants)"
478
+ if not any(x["outcome"] in (CAUGHT, SURVIVED) for x in muts):
479
+ # review F1: nothing was decided, so nothing was measured (e.g. every mutant timed out)
480
+ return "BLIND(all-mutants-unclear)"
481
+ return MEASURED
482
+
483
+
484
+ def _budget(ctx, budget: dict, order, plans) -> None:
485
+ """R6: after the first control, project the run; over BUDGET_S, keep the first N that fit."""
486
+ if not ctx.control_seconds:
487
+ return
488
+ med = statistics.median(ctx.control_seconds)
489
+ cost = []
490
+ for key in order:
491
+ p = plans.get(key)
492
+ m = len(p.mutants) if isinstance(p, plant.Plan) else 0
493
+ cost.append((1 + 2 * m) * med if m else 0.0) # review F3: a caught mutant is re-run
494
+ projected = med + sum(cost)
495
+ budget["projected_s"] = round(projected, 1)
496
+ budget["median_control_s"] = med
497
+ if projected <= BUDGET_S:
498
+ budget["n"] = len(order)
499
+ return
500
+ total, n = med, 0
501
+ for c in cost:
502
+ if total + c > BUDGET_S:
503
+ break
504
+ total += c
505
+ n += 1
506
+ budget["n"] = n
507
+ budget["cut"] = True
508
+
509
+
510
+ # --- rows -------------------------------------------------------------------------------------------------
511
+
512
+ def _base_row(ctx, spec, path, mod, function, extra=None) -> dict:
513
+ row = {"run_id": ctx.run_id, "tool_version": TOOL_VERSION, "spec": spec, "file": path, "module": mod,
514
+ "function": function, "box_user": ctx.box_user, "host_python": platform.python_version(),
515
+ "written_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
516
+ "trust": "raw", "kind": "fact"}
517
+ if getattr(ctx, "admission", None) is not None:
518
+ row["admission"] = ctx.admission
519
+ if extra:
520
+ row.update(extra)
521
+ return row
522
+
523
+
524
+ def _row_with_plan(ctx, spec, path, mod, name, plan, extra) -> dict:
525
+ row = _base_row(ctx, spec, path, mod, name, extra)
526
+ row.update(m=len(plan.mutants), k=0, s=0, u=0, not_planted=plan.not_planted,
527
+ version_gated=plan.version_gated, candidates=plan.candidates, capped=plan.capped,
528
+ dropped=[list(d) for d in plan.dropped], controls=[None, None], mutants=[])
529
+ return row
530
+
531
+
532
+ def _append(facts: Path, row: dict) -> None:
533
+ with open(facts, "a", encoding="utf-8") as fh:
534
+ fh.write(json.dumps(row, sort_keys=True) + "\n")
535
+ fh.flush()
536
+ os.fsync(fh.fileno())
@@ -0,0 +1,83 @@
1
+ """Reason-coded UNSUPPORTED taxonomy for lenses (BRIEF §3.2).
2
+
3
+ A lens that cannot render a verdict must say WHY, in a way that names WHOSE
4
+ problem it might be. Free-string reasons hide the distinction that matters:
5
+ "the file is malformed" (certain, the user must FIX)
6
+ vs.
7
+ "our capture subprocess died" (undetermined, could be the lens).
8
+
9
+ Reporting "your code failed" when the honest answer is "our analyser could
10
+ not complete" is the single most damaging thing this tool can do.
11
+
12
+ Every reason code is declared here with (subclass, meaning, remedy,
13
+ dispositions). ``_u(code, detail)`` is the only permitted constructor;
14
+ an undeclared code raises ``KeyError``, by design — a code with no
15
+ declared remedy and no allowed dispositions must not reach a reader.
16
+ """
17
+ from __future__ import annotations
18
+ from dataclasses import dataclass
19
+ from typing import FrozenSet
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Unsupported:
24
+ code: str
25
+ subclass: str
26
+ meaning: str
27
+ remedy: str
28
+ dispositions: FrozenSet[str]
29
+ detail: str
30
+
31
+ def summary(self) -> str:
32
+ d = f": {self.detail}" if self.detail else ""
33
+ return f"[{self.code}] {self.meaning}{d}"
34
+
35
+
36
+ _REGISTRY: dict[str, dict] = {
37
+ "U1:no_coverage": {
38
+ "subclass": "U1",
39
+ "meaning": "no implementation for this lane",
40
+ "remedy": "TOOL_WORK — extend the lens, or declare the lane out of scope",
41
+ "dispositions": frozenset({"TOOL_WORK", "DEFER"}),
42
+ },
43
+ "U2:contract_unratified": {
44
+ "subclass": "U2",
45
+ "meaning": "contract exists but is not human-ratified",
46
+ "remedy": "HUMAN_RATIFY — the ratification queue owns this",
47
+ "dispositions": frozenset({"HUMAN_RATIFY", "DEFER"}),
48
+ },
49
+ "U3:input_malformed": {
50
+ "subclass": "U3",
51
+ "meaning": "required input is absent or malformed (cause CERTAIN)",
52
+ "remedy": "FIX the input, or QUARANTINE the pattern",
53
+ "dispositions": frozenset({"FIX", "QUARANTINE"}),
54
+ },
55
+ "U4:capture_failed": {
56
+ "subclass": "U4",
57
+ "meaning": "capture subprocess exited non-zero — cause UNDETERMINED",
58
+ "remedy": "investigate stderr; the lens OR the input may be at fault",
59
+ "dispositions": frozenset({"FIX", "TOOL_WORK", "QUARANTINE"}),
60
+ },
61
+ "U4:coverage_gap": {
62
+ "subclass": "U4",
63
+ "meaning": "lens ran but could not exercise the code enough to render a verdict — cause UNDETERMINED",
64
+ "remedy": "widen lens coverage OR restructure the code so the lens can reach it; blame is not fixed",
65
+ "dispositions": frozenset({"TOOL_WORK", "FIX", "DEFER"}),
66
+ },
67
+ }
68
+
69
+
70
+ def _u(code: str, detail: str = "") -> Unsupported:
71
+ entry = _REGISTRY[code] # KeyError on undeclared, by design
72
+ return Unsupported(
73
+ code=code,
74
+ subclass=entry["subclass"],
75
+ meaning=entry["meaning"],
76
+ remedy=entry["remedy"],
77
+ dispositions=entry["dispositions"],
78
+ detail=(detail or "")[:200],
79
+ )
80
+
81
+
82
+ def declared_codes() -> tuple[str, ...]:
83
+ return tuple(sorted(_REGISTRY.keys()))