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,231 @@
1
+ """Lens 4, language meaning (design §4a.3; build step 8b s2; DECISIONS-8b H1-H5).
2
+
3
+ "Related" means the code, its comments and its description say the same thing. Score = cosine of
4
+ two embeddings from the pinned LOCAL embedder (``embed.py``). Two scorers are built and measured
5
+ against the same Rule-2 set (H2); a scorer is switched on only if it passes EVERY case on this run,
6
+ and the first that passes (in SCORERS order) is used. None passing = BLIND(rule2-failed), with the
7
+ failing cases printed: an honest red is what Rule 2 is for.
8
+
9
+ - ``raw``: the text as written (code, comments, strings);
10
+ - ``words``: only the meaning-bearing words: comment text, and identifiers split at ``_`` and
11
+ camelCase, lower-cased, language keywords dropped.
12
+
13
+ Members are ranked across ALL languages (the Rule-2 case only this lens gets right is a Bash and
14
+ a Python script doing one job). A scout run never embeds a pool member: member vectors come from
15
+ the cache that ``forgeproof scout --embed-fill`` writes (H4); a member missing from it makes the
16
+ lens BLIND(index-incomplete), never a partial list that looks complete. The query, the control and
17
+ the Rule-2 fixtures are short and embedded live.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import re
22
+ from dataclasses import dataclass, field
23
+
24
+ from . import embed, rule2, shape_lens, slots
25
+ from .outcomes import Outcome, blind, clean, found
26
+
27
+ NAME = "meaning"
28
+ # Thresholds per scorer, set from the probe on the Rule-2 fixtures (DECISIONS-8b F12/F16). They are
29
+ # calibrated ON the Rule-2 set, so that set is not a held-out test of them (KD-15).
30
+ TAU = {"raw": 0.61, "words": 0.61}
31
+ SCORERS = ("raw", "words")
32
+ TEXT_MAX = 8000 # characters sent per text: deterministic truncation, not the model's
33
+ MIN_WORDS = 3 # fewer meaning-bearing words than this: nothing to compare
34
+
35
+ _KEYWORDS = frozenset("""
36
+ and as assert async await break class continue def del elif else except false finally for from global if
37
+ import in is lambda none nonlocal not or pass raise return self true try while with yield print
38
+ then fi do done case esac function local echo set eu exit
39
+ let const var new this null undefined void typeof public private static int str bool float list dict
40
+ """.split())
41
+ _COMMENT = re.compile(r"(?:^|\s)(?:#|//)\s?(.*)$", re.M)
42
+ _IDENT = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
43
+ _CAMEL = re.compile(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])|[0-9]+")
44
+
45
+
46
+ def words_text(text: str) -> str:
47
+ """The meaning-bearing words of a text: comment text first, then split identifiers."""
48
+ out = []
49
+ for m in _COMMENT.finditer(text):
50
+ if not m.group(1).startswith("!"): # a shebang says which interpreter, not what
51
+ out += [w.lower() for w in _IDENT.findall(m.group(1))]
52
+ code = _COMMENT.sub(" ", text)
53
+ for ident in _IDENT.findall(code):
54
+ for part in ident.split("_"):
55
+ out += [w.lower() for w in _CAMEL.findall(part)]
56
+ return " ".join(w for w in out if w not in _KEYWORDS and len(w) > 1)
57
+
58
+
59
+ def lens_text(text: str, scorer: str) -> str:
60
+ t = text if scorer == "raw" else words_text(text)
61
+ return t[:TEXT_MAX]
62
+
63
+
64
+ @dataclass
65
+ class LensResult:
66
+ outcome: Outcome
67
+ hits: list = field(default_factory=list)
68
+ looked_at: int = 0
69
+ scorer: str = ""
70
+
71
+
72
+ # ---------------------------------------------------------------- Rule 2 (H3), written first
73
+
74
+ # A second same-job pair in two languages, so the only-this-lens case does not rest on one family.
75
+ ERRCOUNT_PY = """import sys
76
+ from collections import Counter
77
+ # count how many error lines each log file has
78
+ counts = Counter()
79
+ for path in sys.argv[1:]:
80
+ with open(path) as fh:
81
+ counts[path] = sum(1 for line in fh if "ERROR" in line)
82
+ for path, n in counts.most_common():
83
+ print(n, path)
84
+ """
85
+
86
+ ERRCOUNT_SH = """#!/bin/bash
87
+ # how many ERROR lines per log file, most first
88
+ grep -c ERROR -- "$@" | awk -F: '{print $2, $1}' | sort -rn
89
+ """
90
+
91
+ POOL = dict(rule2.POOL, errcount_py=ERRCOUNT_PY, errcount_sh=ERRCOUNT_SH)
92
+ SAME_JOB = (("backup_tar", "backup_py"), ("backup_tar", "backup_rsync"), ("backup_py", "backup_rsync"),
93
+ ("errcount_py", "errcount_sh"))
94
+ MUST_NOT = {"TAX (same look as area)": rule2.TAX, "null (Stack)": rule2.NULL,
95
+ "keyword trap": rule2.KEYWORD_TRAP}
96
+
97
+
98
+ def rule2_cases(score, tau: float, baseline=None) -> list:
99
+ """Failed cases for a scorer ``score(a, b) -> float`` (empty = may be switched on)."""
100
+ fails = []
101
+
102
+ def top(q, exclude=None):
103
+ r = sorted(((score(q, b), n) for n, b in POOL.items() if n != exclude), key=lambda t: (-t[0], t[1]))
104
+ return r
105
+ # 1. same meaning / different look, and the only-this-lens case: each member of a same-job group
106
+ # has its partners at the top of its list, at or above tau (shape misses these: J 0.00-0.12).
107
+ groups = {"backup": ["backup_tar", "backup_py", "backup_rsync"], "errcount": ["errcount_py", "errcount_sh"]}
108
+ for g, names in groups.items():
109
+ for n in names:
110
+ want = set(names) - {n}
111
+ r = top(POOL[n], exclude=n)
112
+ got = {name for _, name in r[:len(want)]}
113
+ low = [f"{name} {s:.3f}" for s, name in r[:len(want)] if s < tau]
114
+ if got != want or low:
115
+ fails.append(f"same-meaning/different-look: {n}'s top {len(want)} are "
116
+ f"{[f'{name} {s:.3f}' for s, name in r[:len(want)]]}; must be {sorted(want)} >= {tau}")
117
+ # 2. renamed copy: meaning must survive renaming.
118
+ s, n = top(rule2.NEAREST)[0]
119
+ if not (n == "kmeans" and s >= tau):
120
+ fails.append(f"renamed copy: NEAREST ranked {n} at {s:.3f}; must be kmeans >= {tau}")
121
+ # 3. same look / different meaning, the null case and the keyword trap: nothing at or above tau.
122
+ # The same-look case is valid only while shape still matches TAX to area (8b crew review, 6E).
123
+ if shape_lens.score(rule2.TAX, rule2.AREA) < shape_lens.TAU:
124
+ fails.append("case invalid: shape no longer matches TAX to area, so the same-look case tests nothing")
125
+ for what, q in MUST_NOT.items():
126
+ s, n = top(q)[0]
127
+ if s >= tau:
128
+ fails.append(f"{what}: matched {n} at {s:.3f} >= {tau}")
129
+ # 4. the keyword baseline, scored alongside, must separate worse than the lens; and the trap
130
+ # must lure the baseline, or the trap case tests nothing.
131
+ # NOTE (8b s2 review F1): with tau between them, the cases above force the lens's separation
132
+ # above 0 while the baseline's is negative on these fixtures, so 'beats the baseline' is IMPLIED
133
+ # by them here and is not separate evidence (KD-15 j). The trap-lure check is independent.
134
+ if baseline is not None:
135
+ sep_l, sep_b = separation(score), separation(baseline)
136
+ if not sep_l > sep_b:
137
+ fails.append(f"baseline: lens separation {sep_l:.3f} does not beat the keyword baseline's {sep_b:.3f}")
138
+ if not sorted(((baseline(rule2.KEYWORD_TRAP, b), n) for n, b in POOL.items()), reverse=True)[0][1].startswith("backup"):
139
+ fails.append("baseline: the keyword trap did not lure the baseline; the trap tests nothing")
140
+ return fails
141
+
142
+
143
+ def separation(score) -> float:
144
+ pos = [score(POOL[a], POOL[b]) for a, b in SAME_JOB] + [score(rule2.NEAREST, POOL["kmeans"])]
145
+ neg = [score(q, b) for q in MUST_NOT.values() for b in POOL.values()]
146
+ return min(pos) - max(neg)
147
+
148
+
149
+ def _texts_for_rule2(scorer: str) -> list:
150
+ return [lens_text(t, scorer) for t in
151
+ list(POOL.values()) + [rule2.NEAREST] + list(MUST_NOT.values())]
152
+
153
+
154
+ def rule2_run(emb, scorer: str) -> list:
155
+ """Embed the fixtures live with ``emb`` and return the failed cases for ``scorer``."""
156
+ texts = _texts_for_rule2(scorer)
157
+ vecs = dict(zip(texts, emb.embed(texts)))
158
+
159
+ def score(a, b):
160
+ return embed.cosine(vecs[lens_text(a, scorer)], vecs[lens_text(b, scorer)])
161
+ return rule2_cases(score, TAU[scorer], shape_lens.keyword_score)
162
+
163
+
164
+ def choose(emb) -> tuple:
165
+ """(scorer, {scorer: fails}). scorer is '' when none passes. EmbedError propagates (BLIND)."""
166
+ tried = {}
167
+ for sc in SCORERS:
168
+ tried[sc] = rule2_run(emb, sc)
169
+ if not tried[sc]:
170
+ return sc, tried
171
+ return "", tried
172
+
173
+
174
+ # ---------------------------------------------------------------- the lens
175
+
176
+ def comparable(members: list, scorer: str) -> list:
177
+ """Members whose lens text has at least MIN_WORDS words: the only ones the fill embeds and rank
178
+ compares (8b s2 review F2: an empty text would stop the fill on every run, BLIND for good)."""
179
+ return [m for m in members if len(lens_text(m["body"], scorer).split()) >= MIN_WORDS]
180
+
181
+
182
+ def rank(query: str, members: list, *, emb, cache: dict, scorer: str, pool: str, trust: str) -> LensResult:
183
+ """members: dicts with item_id, body (any language). ``cache``: {embed.key(text): vector}."""
184
+ qt = lens_text(query, scorer)
185
+ if len(qt.split()) < MIN_WORDS:
186
+ return LensResult(blind(f"no-input: the query has fewer than {MIN_WORDS} words for scorer {scorer}"),
187
+ scorer=scorer)
188
+ if not members:
189
+ return LensResult(blind(f"no-input: {pool} pool is empty"), scorer=scorer)
190
+ usable = comparable(members, scorer)
191
+ if not usable:
192
+ return LensResult(blind(f"no-input: no {pool} member has {MIN_WORDS} words for scorer {scorer}"),
193
+ scorer=scorer)
194
+ note = (f" ({len(members) - len(usable)} member(s) under {MIN_WORDS} words not compared)"
195
+ if len(usable) < len(members) else "")
196
+ keyed = [(m, embed.key(lens_text(m["body"], scorer), emb.digest)) for m in usable]
197
+ missing = sum(1 for _, k in keyed if k not in cache)
198
+ if missing:
199
+ return LensResult(blind(f"index-incomplete: {len(usable) - missing} of {len(usable)} comparable members "
200
+ f"embedded for scorer {scorer}; run `forgeproof scout --embed-fill`"),
201
+ looked_at=len(usable) - missing, scorer=scorer)
202
+ qv = emb.embed([qt])[0]
203
+ hits = [shape_lens.Hit(m["item_id"], round(embed.cosine(qv, cache[k]), 4), pool, trust,
204
+ m.get("lang", ""), m.get("kind", "")) for m, k in keyed]
205
+ hits.sort(key=lambda h: (-h.score, h.item_id))
206
+ top, explore = slots.split(hits, lens=NAME, query=query)
207
+ shown = top + ([explore] if explore else [])
208
+ tau = TAU[scorer]
209
+ over = [h for h in top if h.score >= tau]
210
+ if over:
211
+ return LensResult(found(f"{len(over)} at or above cos={tau} ({scorer}){note}"), shown, len(usable), scorer)
212
+ return LensResult(clean(f"best cos={top[0].score} < {tau} ({scorer}){note}"), shown, len(usable), scorer)
213
+
214
+
215
+ def control(members: list, *, emb, cache: dict, scorer: str) -> tuple:
216
+ """The planted case (§4a.2): the shortest cached member, embedded LIVE, must come back first at
217
+ cos >= 0.999 against its CACHED vector. That also proves the cache matches the live model.
218
+ Returns (ok, why)."""
219
+ cands = sorted(comparable(members, scorer), key=lambda m: (len(lens_text(m["body"], scorer)), m["item_id"]))
220
+ if not cands:
221
+ return False, "no member long enough to plant"
222
+ m = cands[0]
223
+ k = embed.key(lens_text(m["body"], scorer), emb.digest)
224
+ if k not in cache:
225
+ return False, (f"index-incomplete: planted {m['item_id']} is not in the cache; "
226
+ "run `forgeproof scout --embed-fill`")
227
+ live = emb.embed([lens_text(m["body"], scorer)])[0]
228
+ s = embed.cosine(live, cache[k])
229
+ if s < 0.999:
230
+ return False, f"planted {m['item_id']}: live vs cached cos={s:.4f} < 0.999 (cache from another model state)"
231
+ return True, f"planted {m['item_id']} came back at cos={s:.4f}"
@@ -0,0 +1,42 @@
1
+ """P1 outcomes (design v1.4.5 §4a.2): every check ends FOUND, LOOKED-CLEAN or BLIND(reason).
2
+
3
+ Empty is never a verdict. BLIND reasons are scout's own vocabulary, separate from the
4
+ U-codes in ``forgeproof.unsupported``.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+ FOUND = "FOUND"
11
+ LOOKED_CLEAN = "LOOKED-CLEAN"
12
+ BLIND = "BLIND"
13
+ KINDS = (FOUND, LOOKED_CLEAN, BLIND)
14
+ BLIND_FLAG_SHARE = 0.10 # more than 10% of a run's items BLIND -> the run is flagged
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Outcome:
19
+ kind: str
20
+ reason: str = "" # required for BLIND, empty otherwise
21
+ evidence: tuple = field(default=()) # what was found / what was looked at
22
+
23
+ def __post_init__(self):
24
+ if self.kind not in KINDS:
25
+ raise ValueError(f"outcome {self.kind!r} not in {KINDS}")
26
+ if (self.kind == BLIND) != bool(self.reason):
27
+ raise ValueError("BLIND needs a reason; FOUND and LOOKED-CLEAN take none")
28
+
29
+ def label(self) -> str:
30
+ return f"BLIND({self.reason})" if self.kind == BLIND else self.kind
31
+
32
+
33
+ def found(*evidence) -> Outcome:
34
+ return Outcome(FOUND, "", tuple(evidence))
35
+
36
+
37
+ def clean(*evidence) -> Outcome:
38
+ return Outcome(LOOKED_CLEAN, "", tuple(evidence))
39
+
40
+
41
+ def blind(reason: str, *evidence) -> Outcome:
42
+ return Outcome(BLIND, reason, tuple(evidence))
@@ -0,0 +1,327 @@
1
+ """The bug planter for the GitHub fact tool (GitHub-lane loop S3, DESIGN github-lane-2026-11 §5 R5).
2
+
3
+ It plants small, single-node bugs into ONE top-level function of a Python source file, so the
4
+ fact tool can ask whether the project's own tests notice them. It never runs anything.
5
+
6
+ How a mutant is made (R5):
7
+ - ``ast`` finds the candidate nodes inside the function's body;
8
+ - ``tokenize`` finds the operator token inside the node's span. ``ast`` gives operators no
9
+ position, and ``col_offset`` counts UTF-8 BYTES, while tokenize counts characters;
10
+ - the change is spliced into the ORIGINAL SOURCE BYTES, so everything outside the token stays
11
+ byte-identical (docstrings and their doctests included; ``ast.unparse`` would rewrite them).
12
+
13
+ Operators: comparison flip (``<`` <-> ``>=``, ``==`` <-> ``!=``, ``is`` <-> ``is not``,
14
+ ``in`` <-> ``not in``), ``+`` <-> ``-``, an integer constant + 1, ``return <expr>`` ->
15
+ ``return None``, ``and`` <-> ``or`` (every operator token of one BoolOp).
16
+
17
+ Self-check per mutant: the mutant compiles, and its AST differs from the original's in EXACTLY
18
+ ONE node, of the stated operator class. Otherwise it is dropped and counted as ``not_planted``.
19
+ A candidate anywhere inside an ``if`` (or a conditional expression) whose test reads
20
+ ``sys.version_info``, ``sys.hexversion``, ``hexversion`` or ``version_info`` is not planted and is
21
+ counted as ``version_gated`` (unreachable on the host's Python, so it could only "survive" falsely).
22
+
23
+ At most :data:`MAX_MUTANTS` per function, spread evenly over the valid ones in source order. Ids
24
+ are ``<function>:<op>:<line>:<col>`` (line 1-based, col the 0-based character column of the
25
+ token), stable for the same bytes.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import ast
30
+ import difflib
31
+ import io
32
+ import tokenize
33
+ from dataclasses import dataclass, field
34
+
35
+ MAX_MUTANTS = 12
36
+ OPS = ("cmp", "arith", "const", "return", "bool")
37
+ VERSION_NAMES = frozenset({"version_info", "hexversion"})
38
+
39
+ _CMP_TEXT = {ast.Lt: "<", ast.LtE: "<=", ast.Gt: ">", ast.GtE: ">=", ast.Eq: "==", ast.NotEq: "!=",
40
+ ast.Is: "is", ast.IsNot: "is not", ast.In: "in", ast.NotIn: "not in"}
41
+ _CMP_FLIP = {ast.Lt: ast.GtE, ast.GtE: ast.Lt, ast.Gt: ast.LtE, ast.LtE: ast.Gt, ast.Eq: ast.NotEq,
42
+ ast.NotEq: ast.Eq, ast.Is: ast.IsNot, ast.IsNot: ast.Is, ast.In: ast.NotIn, ast.NotIn: ast.In}
43
+ _CMP_WORDS = frozenset({"<", "<=", ">", ">=", "==", "!=", "is", "not", "in"})
44
+
45
+
46
+ class PlantError(Exception):
47
+ """The source cannot be planted at all (not UTF-8, does not parse, no such function)."""
48
+
49
+
50
+ @dataclass
51
+ class Mutant:
52
+ id: str
53
+ op: str
54
+ line: int
55
+ col: int
56
+ source: bytes # the whole mutated file
57
+ diff: str # unified diff of the changed line(s)
58
+
59
+
60
+ @dataclass
61
+ class Plan:
62
+ function: str
63
+ mutants: list = field(default_factory=list)
64
+ candidates: int = 0 # valid mutants before the cap
65
+ capped: int = 0 # valid mutants left out by the cap
66
+ not_planted: int = 0 # failed the self-check (or no token found)
67
+ version_gated: int = 0
68
+ dropped: list = field(default_factory=list) # [(id, why)] for not_planted
69
+
70
+
71
+ @dataclass
72
+ class _Cand:
73
+ op: str
74
+ start: int # absolute byte offsets of the span to replace
75
+ end: int
76
+ new: bytes
77
+ line: int
78
+ col: int # character column, for the id
79
+ check: object # callable(orig_node, mut_node) -> bool on the single diff
80
+
81
+ def splice(self, source: bytes) -> bytes:
82
+ return source[:self.start] + self.new + source[self.end:]
83
+
84
+
85
+ def functions(source: bytes) -> list[str]:
86
+ """Top-level ``def`` names in source order (methods and async functions are not planted)."""
87
+ tree = _parse(source)
88
+ return [n.name for n in tree.body if isinstance(n, ast.FunctionDef)]
89
+
90
+
91
+ def plant(source: bytes, function: str, max_mutants: int = MAX_MUTANTS) -> Plan:
92
+ tree = _parse(source)
93
+ defs = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == function]
94
+ if len(defs) != 1:
95
+ raise PlantError(f"{function}: {len(defs)} top-level definitions (need exactly one)")
96
+ fn = defs[0]
97
+ lines = source.splitlines(keepends=True)
98
+ starts = [0]
99
+ for ln in lines:
100
+ starts.append(starts[-1] + len(ln))
101
+ toks = _tokens(source, lines, starts)
102
+ plan = Plan(function)
103
+ gated = _gated_nodes(fn)
104
+ valid = []
105
+ for node in _body_nodes(fn):
106
+ for cand in _candidates(node, toks, lines, starts):
107
+ if id(node) in gated:
108
+ plan.version_gated += 1
109
+ continue
110
+ if cand is None: # the token was not where the node says: not planted
111
+ plan.not_planted += 1
112
+ plan.dropped.append((f"{function}:?:{getattr(node, 'lineno', 0)}", "no-token"))
113
+ continue
114
+ mid = f"{function}:{cand.op}:{cand.line}:{cand.col}"
115
+ new = cand.splice(source)
116
+ why = _self_check(tree, new, cand)
117
+ if why:
118
+ plan.not_planted += 1
119
+ plan.dropped.append((mid, why))
120
+ continue
121
+ valid.append(Mutant(mid, cand.op, cand.line, cand.col, new, _diff(source, new)))
122
+ valid.sort(key=lambda m: (m.line, m.col, m.op))
123
+ plan.candidates = len(valid)
124
+ if len(valid) > max_mutants:
125
+ keep = sorted({i * len(valid) // max_mutants for i in range(max_mutants)})
126
+ plan.capped = len(valid) - len(keep)
127
+ valid = [valid[i] for i in keep]
128
+ plan.mutants = valid
129
+ return plan
130
+
131
+
132
+ # --- parsing and positions -------------------------------------------------------------------
133
+
134
+ def _parse(source: bytes) -> ast.Module:
135
+ try:
136
+ source.decode("utf-8")
137
+ except UnicodeDecodeError as e:
138
+ raise PlantError(f"not UTF-8: {e}") from None
139
+ try:
140
+ return ast.parse(source)
141
+ except (SyntaxError, ValueError) as e:
142
+ raise PlantError(f"does not parse: {e}") from None
143
+
144
+
145
+ def _tokens(source, lines, starts) -> list[tuple[int, int, str, int]]:
146
+ """(abs_byte_start, abs_byte_end, string, type) for every token on one line."""
147
+ out = []
148
+ for t in tokenize.tokenize(io.BytesIO(source).readline):
149
+ if t.type in (tokenize.ENCODING, tokenize.ENDMARKER) or t.start[0] != t.end[0]:
150
+ continue
151
+ row = t.start[0]
152
+ if row > len(lines):
153
+ continue
154
+ text = lines[row - 1].decode("utf-8")
155
+ b0 = starts[row - 1] + len(text[:t.start[1]].encode("utf-8"))
156
+ b1 = starts[row - 1] + len(text[:t.end[1]].encode("utf-8"))
157
+ out.append((b0, b1, t.string, t.type))
158
+ return out
159
+
160
+
161
+ def _abs(lines, starts, lineno, col_bytes) -> int:
162
+ return starts[lineno - 1] + col_bytes
163
+
164
+
165
+ def _char_col(lines, abs_byte, starts) -> tuple[int, int]:
166
+ for i in range(len(lines)):
167
+ if starts[i] <= abs_byte < starts[i + 1]:
168
+ return i + 1, len(lines[i][:abs_byte - starts[i]].decode("utf-8", "replace"))
169
+ return len(lines), 0
170
+
171
+
172
+ def _span(node, lines, starts) -> tuple[int, int]:
173
+ return (_abs(lines, starts, node.lineno, node.col_offset),
174
+ _abs(lines, starts, node.end_lineno, node.end_col_offset))
175
+
176
+
177
+ def _between(toks, lo, hi, words) -> list:
178
+ return [t for t in toks if lo <= t[0] and t[1] <= hi and t[2] in words]
179
+
180
+
181
+ def _body_nodes(fn: ast.FunctionDef):
182
+ for stmt in fn.body:
183
+ yield from ast.walk(stmt)
184
+
185
+
186
+ def _reads_version(test: ast.AST) -> bool:
187
+ for n in ast.walk(test):
188
+ if isinstance(n, ast.Attribute) and n.attr in VERSION_NAMES:
189
+ return True
190
+ if isinstance(n, ast.Name) and n.id in VERSION_NAMES:
191
+ return True
192
+ return False
193
+
194
+
195
+ def _gated_nodes(fn: ast.FunctionDef) -> set:
196
+ out = set()
197
+ for n in ast.walk(fn):
198
+ if isinstance(n, (ast.If, ast.IfExp)) and _reads_version(n.test):
199
+ out.update(id(x) for x in ast.walk(n))
200
+ return out
201
+
202
+
203
+ # --- candidates ----------------------------------------------------------------------------------
204
+
205
+ def _candidates(node, toks, lines, starts):
206
+ """Yield _Cand (or None when the node's operator token cannot be found) for one node."""
207
+ if isinstance(node, ast.Compare):
208
+ prev = node.left
209
+ for op, right in zip(node.ops, node.comparators):
210
+ lo, hi = _span(prev, lines, starts)[1], _span(right, lines, starts)[0]
211
+ found = _between(toks, lo, hi, _CMP_WORDS)
212
+ text = " ".join(t[2] for t in found)
213
+ if not found or text != _CMP_TEXT[type(op)]:
214
+ yield None
215
+ else:
216
+ want = _CMP_FLIP[type(op)]
217
+ yield _cand("cmp", found[0][0], found[-1][1], _CMP_TEXT[want], lines, starts,
218
+ lambda a, b, o=type(op), w=want: type(a) is o and type(b) is w)
219
+ prev = right
220
+ elif isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)):
221
+ lo, hi = _span(node.left, lines, starts)[1], _span(node.right, lines, starts)[0]
222
+ found = _between(toks, lo, hi, {"+", "-"})
223
+ sym = "+" if isinstance(node.op, ast.Add) else "-"
224
+ if len(found) != 1 or found[0][2] != sym:
225
+ yield None
226
+ else:
227
+ want = ast.Sub if sym == "+" else ast.Add
228
+ yield _cand("arith", found[0][0], found[0][1], "-" if sym == "+" else "+", lines, starts,
229
+ lambda a, b, o=type(node.op), w=want: type(a) is o and type(b) is w)
230
+ elif isinstance(node, ast.Constant) and type(node.value) is int:
231
+ lo, hi = _span(node, lines, starts)
232
+ found = [t for t in toks if t[0] == lo and t[1] == hi and t[3] == tokenize.NUMBER]
233
+ if len(found) != 1:
234
+ yield None
235
+ else:
236
+ v = node.value
237
+ yield _cand("const", lo, hi, str(v + 1), lines, starts,
238
+ lambda a, b, v=v: (isinstance(a, ast.Constant) and isinstance(b, ast.Constant)
239
+ and type(a.value) is int and type(b.value) is int
240
+ and a.value == v and b.value == v + 1))
241
+ elif isinstance(node, ast.Return) and node.value is not None and not (
242
+ isinstance(node.value, ast.Constant) and node.value.value is None):
243
+ lo, hi = _span(node.value, lines, starts)
244
+ yield _cand("return", lo, hi, "None", lines, starts,
245
+ lambda a, b, orig=node.value: (a is orig and isinstance(b, ast.Constant)
246
+ and b.value is None))
247
+ elif isinstance(node, ast.BoolOp):
248
+ found = []
249
+ for left, right in zip(node.values, node.values[1:]):
250
+ lo, hi = _span(left, lines, starts)[1], _span(right, lines, starts)[0]
251
+ found += _between(toks, lo, hi, {"and", "or"})
252
+ sym = "and" if isinstance(node.op, ast.And) else "or"
253
+ if len(found) != len(node.values) - 1 or any(t[2] != sym for t in found):
254
+ yield None
255
+ else:
256
+ yield _BoolCand(found, "or" if sym == "and" else "and", lines, starts, type(node.op))
257
+
258
+
259
+ def _cand(op, b0, b1, new_text, lines, starts, check) -> _Cand:
260
+ line, col = _char_col(lines, b0, starts)
261
+ return _Cand(op, b0, b1, new_text.encode("utf-8"), line, col, check)
262
+
263
+
264
+ class _BoolCand(_Cand):
265
+ """Several tokens of one BoolOp, all flipped: spliced as one span from first to last token."""
266
+
267
+ def __init__(self, found, new_word, lines, starts, orig_cls):
268
+ line, col = _char_col(lines, found[0][0], starts)
269
+ want = ast.Or if orig_cls is ast.And else ast.And
270
+ super().__init__("bool", found[0][0], found[-1][1], b"", line, col,
271
+ lambda a, b: type(a) is orig_cls and type(b) is want)
272
+ self._found = found
273
+ self._word = new_word.encode("utf-8")
274
+
275
+ def splice(self, source: bytes) -> bytes:
276
+ out, pos = [], self.start
277
+ for b0, b1, _s, _t in self._found:
278
+ out.append(source[pos:b0])
279
+ out.append(self._word)
280
+ pos = b1
281
+ return source[:self.start] + b"".join(out) + source[self.end:]
282
+
283
+
284
+ # --- self-check ------------------------------------------------------------------------------------
285
+
286
+ def _self_check(orig_tree, new: bytes, cand: _Cand) -> str | None:
287
+ try:
288
+ mut_tree = ast.parse(new)
289
+ compile(mut_tree, "<mutant>", "exec")
290
+ except (SyntaxError, ValueError) as e:
291
+ return f"does-not-compile: {e.__class__.__name__}"
292
+ diffs = []
293
+ _diffs(orig_tree, mut_tree, diffs)
294
+ if len(diffs) != 1:
295
+ return f"ast-differs-in-{len(diffs)}-places"
296
+ a, b = diffs[0]
297
+ if not cand.check(a, b):
298
+ return f"wrong-node-class: {type(a).__name__}->{type(b).__name__}"
299
+ return None
300
+
301
+
302
+ def _diffs(a, b, out: list) -> None:
303
+ """The top-most differing node pairs of two ASTs (positions ignored)."""
304
+ if type(a) is not type(b):
305
+ out.append((a, b))
306
+ return
307
+ if isinstance(a, ast.AST):
308
+ for f in a._fields:
309
+ va, vb = getattr(a, f, None), getattr(b, f, None)
310
+ if isinstance(va, list) and isinstance(vb, list):
311
+ if len(va) != len(vb):
312
+ out.append((a, b))
313
+ continue
314
+ for x, y in zip(va, vb):
315
+ _diffs(x, y, out)
316
+ elif isinstance(va, ast.AST) or isinstance(vb, ast.AST):
317
+ _diffs(va, vb, out)
318
+ elif type(va) is not type(vb) or va != vb:
319
+ out.append((a, b))
320
+ return
321
+ elif a != b:
322
+ out.append((a, b))
323
+
324
+
325
+ def _diff(old: bytes, new: bytes) -> str:
326
+ return "".join(difflib.unified_diff(old.decode("utf-8").splitlines(keepends=True),
327
+ new.decode("utf-8").splitlines(keepends=True), n=0))