letitloop 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 (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,206 @@
1
+ """AST Property-Based Fuzz Engine for letitloop (Pruned & Hardened).
2
+
3
+ Provides grammar-aware AST mutation operators, property invariant oracles,
4
+ and sandboxed execution harness with simple random/round-robin operator selection.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ import copy
11
+ import os
12
+ import random
13
+ from dataclasses import dataclass, field
14
+ from typing import Any, Dict, List, Optional, Set
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Default State Machine & Taxonomy Constants (aligned with orchestrator)
18
+ # ---------------------------------------------------------------------------
19
+
20
+ DEFAULT_STATES: Set[str] = {
21
+ "DRAFTED",
22
+ "PREFLIGHT_RUNNING",
23
+ "PREFLIGHT_FAILED",
24
+ "BLOCKED",
25
+ "READY",
26
+ "WORKING",
27
+ "VERIFYING",
28
+ "VERIFICATION_FAILED",
29
+ "RETRY_PENDING",
30
+ "CRASHED",
31
+ "ESCALATED",
32
+ "VERIFIED",
33
+ "QC_RUNNING",
34
+ "QC_REJECTED",
35
+ "QC_INSUFFICIENT_EVIDENCE",
36
+ "QC_CONDITIONAL_PASS",
37
+ "QC_PASSED",
38
+ "COMPLETE",
39
+ "FORCE_COMPLETE",
40
+ "DEGRADED_PASS",
41
+ "PAUSED",
42
+ "CANCELLED",
43
+ }
44
+
45
+ DEFAULT_TERMINAL_STATES: Set[str] = {
46
+ "COMPLETE",
47
+ "FORCE_COMPLETE",
48
+ "DEGRADED_PASS",
49
+ "ESCALATED",
50
+ "BLOCKED",
51
+ "CANCELLED",
52
+ }
53
+
54
+ SECRET_ENV_PATTERNS = [
55
+ "KEY",
56
+ "SECRET",
57
+ "TOKEN",
58
+ "PASSWORD",
59
+ "AUTH",
60
+ "CREDENTIAL",
61
+ "APIKEY",
62
+ "BEARER",
63
+ ]
64
+
65
+
66
+ @dataclass
67
+ class InvariantResult:
68
+ """Result of evaluating a property invariant predicate."""
69
+
70
+ invariant_id: str
71
+ passed: bool
72
+ message: str = ""
73
+ details: Dict[str, Any] = field(default_factory=dict)
74
+
75
+
76
+ @dataclass
77
+ class MutationResult:
78
+ """Result of an AST mutation operation."""
79
+
80
+ mutated_ast: ast.AST
81
+ mutated_code: str
82
+ operator_name: str
83
+ mutations_applied: int
84
+ seed: Optional[int] = None
85
+
86
+
87
+ class AstMutationOperator(ast.NodeTransformer):
88
+ """Base class for all AST-level mutation operators."""
89
+
90
+ name: str = "BASE_OPERATOR"
91
+ description: str = "Base AST mutation operator"
92
+
93
+ def __init__(self, mutation_rate: float = 0.5, seed: Optional[int] = None):
94
+ super().__init__()
95
+ self.mutation_rate = max(0.0, min(1.0, float(mutation_rate)))
96
+ self.seed = seed
97
+ self.rng = random.Random(seed)
98
+ self.mutations_applied = 0
99
+
100
+ def should_mutate(self) -> bool:
101
+ return self.rng.random() <= self.mutation_rate
102
+
103
+ def mutate(self, tree: ast.AST) -> MutationResult:
104
+ self.mutations_applied = 0
105
+ cloned_tree = copy.deepcopy(tree)
106
+ transformed_tree = self.visit(cloned_tree)
107
+ ast.fix_missing_locations(transformed_tree)
108
+ try:
109
+ mutated_code = ast.unparse(transformed_tree)
110
+ except Exception:
111
+ mutated_code = ""
112
+ return MutationResult(
113
+ mutated_ast=transformed_tree,
114
+ mutated_code=mutated_code,
115
+ operator_name=self.name,
116
+ mutations_applied=self.mutations_applied,
117
+ seed=self.seed,
118
+ )
119
+
120
+
121
+ class InvertBranchOperator(AstMutationOperator):
122
+ """Invert if-statement condition or swap if/else blocks."""
123
+
124
+ name = "CF_INVERT_BRANCH"
125
+
126
+ def visit_If(self, node: ast.If) -> ast.AST:
127
+ self.generic_visit(node)
128
+ if self.should_mutate():
129
+ node.test = ast.UnaryOp(op=ast.Not(), operand=node.test)
130
+ self.mutations_applied += 1
131
+ return node
132
+
133
+
134
+ class SwallowExceptionOperator(AstMutationOperator):
135
+ """Swallow exceptions by replacing handler body with pass."""
136
+
137
+ name = "CF_SWALLOW_EXCEPTION"
138
+
139
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> ast.AST:
140
+ self.generic_visit(node)
141
+ if self.should_mutate():
142
+ node.body = [ast.Pass()]
143
+ self.mutations_applied += 1
144
+ return node
145
+
146
+
147
+ # ---------------------------------------------------------------------------
148
+ # Property Oracles (Clean, Deterministic Invariant Checks)
149
+ # ---------------------------------------------------------------------------
150
+
151
+
152
+ class PropertyOracle:
153
+ """Verifies invariant properties on orchestrator states and WAL execution traces."""
154
+
155
+ @staticmethod
156
+ def check_monotonic_wal_sequence(wal_entries: List[Dict[str, Any]]) -> InvariantResult:
157
+ """Verifies that WAL event sequence indices and timestamps are strictly monotonic."""
158
+ if not wal_entries:
159
+ return InvariantResult("ORACLE_MONOTONIC_WAL", True, "Empty WAL is trivially monotonic.")
160
+
161
+ last_seq = -1
162
+ for idx, entry in enumerate(wal_entries):
163
+ seq = entry.get("seq", entry.get("sequence", idx))
164
+ if seq <= last_seq and idx > 0:
165
+ return InvariantResult(
166
+ "ORACLE_MONOTONIC_WAL",
167
+ False,
168
+ f"Non-monotonic sequence: step {idx} had seq {seq} <= {last_seq}",
169
+ {"index": idx, "entry": entry},
170
+ )
171
+ last_seq = seq
172
+ return InvariantResult("ORACLE_MONOTONIC_WAL", True, "WAL sequence is strictly monotonic.")
173
+
174
+ @staticmethod
175
+ def check_terminal_sink(state_history: List[str], terminal_states: Optional[Set[str]] = None) -> InvariantResult:
176
+ """Verifies that once a state reaches a terminal state, no further transitions occur."""
177
+ terminals = terminal_states or DEFAULT_TERMINAL_STATES
178
+ terminal_hit_at: Optional[int] = None
179
+
180
+ for idx, s in enumerate(state_history):
181
+ if terminal_hit_at is not None:
182
+ return InvariantResult(
183
+ "ORACLE_TERMINAL_SINK",
184
+ False,
185
+ f"State transition occurred after terminal state '{state_history[terminal_hit_at]}' at index {idx}",
186
+ {"terminal_index": terminal_hit_at, "violation_index": idx, "state": s},
187
+ )
188
+ if s in terminals:
189
+ terminal_hit_at = idx
190
+
191
+ return InvariantResult("ORACLE_TERMINAL_SINK", True, "Terminal states are strict sinks.")
192
+
193
+ @staticmethod
194
+ def check_secret_masking(log_output: str, secret_patterns: Optional[List[str]] = None) -> InvariantResult:
195
+ """Verifies that raw API keys or sensitive env strings never leak unmasked into logs."""
196
+ patterns = secret_patterns or SECRET_ENV_PATTERNS
197
+ for env_k, env_v in os.environ.items():
198
+ if any(pat in env_k.upper() for pat in patterns):
199
+ if len(env_v) > 8 and env_v in log_output:
200
+ return InvariantResult(
201
+ "ORACLE_SECRET_MASKING",
202
+ False,
203
+ f"Secret value for env '{env_k}' detected unmasked in output.",
204
+ {"env_name": env_k},
205
+ )
206
+ return InvariantResult("ORACLE_SECRET_MASKING", True, "No secrets detected in output logs.")
@@ -0,0 +1,382 @@
1
+ """
2
+ Mutation Tester Module
3
+ Provides AST-based mutation operators and mutant injection logic for Python code.
4
+
5
+ Strategy:
6
+ 1. Identify AST nodes suitable for mutation (binary operators, comparisons, boolean operators, unary operators, constants).
7
+ 2. Use AST Visitor / NodeTransformer pattern (ASTMutantInjector) to traverse and selectively mutate targets.
8
+ 3. Provide high-level generation and injection functions: generate_mutants, inject_mutants, apply_mutations, mutate_ast.
9
+ """
10
+
11
+ import ast
12
+ import copy
13
+ from dataclasses import dataclass
14
+ from enum import Enum, auto
15
+ from typing import Any, Dict, List, Optional, Type
16
+
17
+
18
+ class OperatorType(Enum):
19
+ """Types of mutation operators."""
20
+
21
+ AOR = auto() # Arithmetic Operator Replacement
22
+ ROR = auto() # Relational / Comparison Operator Replacement
23
+ LOR = auto() # Logical / Boolean Operator Replacement
24
+ UOR = auto() # Unary Operator Replacement
25
+ LCR = auto() # Literal / Constant Replacement
26
+ SDR = auto() # Statement Deletion Replacement
27
+
28
+
29
+ @dataclass
30
+ class MutationLocation:
31
+ """Location and metadata for a potential mutation."""
32
+
33
+ lineno: int
34
+ col_offset: int
35
+ node_type: str
36
+ operator_type: OperatorType
37
+ original_op: str
38
+ replacement_op: str
39
+ description: str
40
+
41
+
42
+ @dataclass
43
+ class Mutant:
44
+ """Represents an individual mutant created from source code."""
45
+
46
+ mutant_id: int
47
+ original_code: str
48
+ mutated_code: str
49
+ location: MutationLocation
50
+ ast_tree: ast.AST
51
+
52
+
53
+ class MutationOperator:
54
+ """
55
+ Base class and registry for AST mutation operators.
56
+ Defines transformation rules for AST nodes.
57
+ """
58
+
59
+ # Binary Arithmetic Operators
60
+ BINOP_REPLACEMENTS: Dict[Type[ast.operator], List[Type[ast.operator]]] = {
61
+ ast.Add: [ast.Sub, ast.Mult],
62
+ ast.Sub: [ast.Add, ast.Mult],
63
+ ast.Mult: [ast.Div, ast.Add],
64
+ ast.Div: [ast.Mult, ast.FloorDiv],
65
+ ast.FloorDiv: [ast.Div, ast.Mult],
66
+ ast.Mod: [ast.Mult, ast.Div],
67
+ ast.Pow: [ast.Mult, ast.Add],
68
+ ast.BitAnd: [ast.BitOr, ast.BitXor],
69
+ ast.BitOr: [ast.BitAnd, ast.BitXor],
70
+ ast.BitXor: [ast.BitAnd, ast.BitOr],
71
+ ast.LShift: [ast.RShift],
72
+ ast.RShift: [ast.LShift],
73
+ }
74
+
75
+ # Comparison / Relational Operators
76
+ CMPOP_REPLACEMENTS: Dict[Type[ast.cmpop], List[Type[ast.cmpop]]] = {
77
+ ast.Eq: [ast.NotEq, ast.Lt, ast.Gt],
78
+ ast.NotEq: [ast.Eq],
79
+ ast.Lt: [ast.LtE, ast.Gt, ast.Eq],
80
+ ast.LtE: [ast.Lt, ast.GtE, ast.Eq],
81
+ ast.Gt: [ast.GtE, ast.Lt, ast.Eq],
82
+ ast.GtE: [ast.Gt, ast.LtE, ast.Eq],
83
+ ast.Is: [ast.IsNot],
84
+ ast.IsNot: [ast.Is],
85
+ ast.In: [ast.NotIn],
86
+ ast.NotIn: [ast.In],
87
+ }
88
+
89
+ # Logical / Boolean Operators
90
+ BOOLOP_REPLACEMENTS: Dict[Type[ast.boolop], List[Type[ast.boolop]]] = {
91
+ ast.And: [ast.Or],
92
+ ast.Or: [ast.And],
93
+ }
94
+
95
+ # Unary Operators
96
+ UNARYOP_REPLACEMENTS: Dict[Type[ast.unaryop], List[Type[ast.unaryop]]] = {
97
+ ast.Not: [ast.UAdd],
98
+ ast.UAdd: [ast.USub],
99
+ ast.USub: [ast.UAdd],
100
+ ast.Invert: [ast.UAdd],
101
+ }
102
+
103
+ @classmethod
104
+ def get_binop_replacements(cls, op: ast.operator) -> List[ast.operator]:
105
+ """Return replacement operator instances for a given binary operator."""
106
+ op_cls = type(op)
107
+ return [repl_cls() for repl_cls in cls.BINOP_REPLACEMENTS.get(op_cls, [])]
108
+
109
+ @classmethod
110
+ def get_cmpop_replacements(cls, op: ast.cmpop) -> List[ast.cmpop]:
111
+ """Return replacement operator instances for a given comparison operator."""
112
+ op_cls = type(op)
113
+ return [repl_cls() for repl_cls in cls.CMPOP_REPLACEMENTS.get(op_cls, [])]
114
+
115
+ @classmethod
116
+ def get_boolop_replacements(cls, op: ast.boolop) -> List[ast.boolop]:
117
+ """Return replacement operator instances for a given boolean operator."""
118
+ op_cls = type(op)
119
+ return [repl_cls() for repl_cls in cls.BOOLOP_REPLACEMENTS.get(op_cls, [])]
120
+
121
+ @classmethod
122
+ def get_unaryop_replacements(cls, op: ast.unaryop) -> List[ast.unaryop]:
123
+ """Return replacement operator instances for a given unary operator."""
124
+ op_cls = type(op)
125
+ return [repl_cls() for repl_cls in cls.UNARYOP_REPLACEMENTS.get(op_cls, [])]
126
+
127
+ @classmethod
128
+ def get_constant_replacements(cls, val: Any) -> List[Any]:
129
+ """Return replacement values for constant/literal nodes."""
130
+ if isinstance(val, bool):
131
+ return [not val]
132
+ elif isinstance(val, (int, float)):
133
+ if val == 0:
134
+ return [1, -1]
135
+ elif val == 1:
136
+ return [0, 2]
137
+ else:
138
+ return [val + 1, val - 1, 0]
139
+ elif isinstance(val, str):
140
+ if val == "":
141
+ return ["mutated"]
142
+ return [""]
143
+ return []
144
+
145
+
146
+ class ASTMutantInjector(ast.NodeTransformer):
147
+ """
148
+ AST visitor and transformer that identifies mutation points and injects
149
+ mutations into the AST.
150
+ """
151
+
152
+ def __init__(self, target_location: Optional[MutationLocation] = None, replacement: Any = None):
153
+ super().__init__()
154
+ self.target_location = target_location
155
+ self.replacement = replacement
156
+ self.found_locations: List[MutationLocation] = []
157
+ self.current_mutation_applied = False
158
+
159
+ def collect_mutation_points(self, tree: ast.AST) -> List[MutationLocation]:
160
+ """Scan AST and collect all possible mutation points."""
161
+ self.found_locations = []
162
+ self.visit(tree)
163
+ return list(self.found_locations)
164
+
165
+ def visit_BinOp(self, node: ast.BinOp) -> ast.AST:
166
+ """Visit binary operations (e.g., +, -, *, /)."""
167
+ op_cls = type(node.op)
168
+ if op_cls in MutationOperator.BINOP_REPLACEMENTS:
169
+ for repl_cls in MutationOperator.BINOP_REPLACEMENTS[op_cls]:
170
+ loc = MutationLocation(
171
+ lineno=getattr(node, "lineno", 0),
172
+ col_offset=getattr(node, "col_offset", 0),
173
+ node_type="BinOp",
174
+ operator_type=OperatorType.AOR,
175
+ original_op=op_cls.__name__,
176
+ replacement_op=repl_cls.__name__,
177
+ description=f"Replace {op_cls.__name__} with {repl_cls.__name__}",
178
+ )
179
+ self.found_locations.append(loc)
180
+
181
+ if self._is_target(loc):
182
+ new_node = copy.deepcopy(node)
183
+ new_node.op = repl_cls()
184
+ self.current_mutation_applied = True
185
+ return new_node
186
+
187
+ self.generic_visit(node)
188
+ return node
189
+
190
+ def visit_Compare(self, node: ast.Compare) -> ast.AST:
191
+ """Visit comparison operations (e.g., ==, !=, <, <=, >, >=)."""
192
+ for idx, op in enumerate(node.ops):
193
+ op_cls = type(op)
194
+ if op_cls in MutationOperator.CMPOP_REPLACEMENTS:
195
+ for repl_cls in MutationOperator.CMPOP_REPLACEMENTS[op_cls]:
196
+ loc = MutationLocation(
197
+ lineno=getattr(node, "lineno", 0),
198
+ col_offset=getattr(node, "col_offset", 0),
199
+ node_type="Compare",
200
+ operator_type=OperatorType.ROR,
201
+ original_op=op_cls.__name__,
202
+ replacement_op=repl_cls.__name__,
203
+ description=f"Replace comparison {op_cls.__name__} with {repl_cls.__name__}",
204
+ )
205
+ self.found_locations.append(loc)
206
+
207
+ if self._is_target(loc):
208
+ new_node = copy.deepcopy(node)
209
+ new_node.ops[idx] = repl_cls()
210
+ self.current_mutation_applied = True
211
+ return new_node
212
+
213
+ self.generic_visit(node)
214
+ return node
215
+
216
+ def visit_BoolOp(self, node: ast.BoolOp) -> ast.AST:
217
+ """Visit boolean operations (e.g., and, or)."""
218
+ op_cls = type(node.op)
219
+ if op_cls in MutationOperator.BOOLOP_REPLACEMENTS:
220
+ for repl_cls in MutationOperator.BOOLOP_REPLACEMENTS[op_cls]:
221
+ loc = MutationLocation(
222
+ lineno=getattr(node, "lineno", 0),
223
+ col_offset=getattr(node, "col_offset", 0),
224
+ node_type="BoolOp",
225
+ operator_type=OperatorType.LOR,
226
+ original_op=op_cls.__name__,
227
+ replacement_op=repl_cls.__name__,
228
+ description=f"Replace boolean op {op_cls.__name__} with {repl_cls.__name__}",
229
+ )
230
+ self.found_locations.append(loc)
231
+
232
+ if self._is_target(loc):
233
+ new_node = copy.deepcopy(node)
234
+ new_node.op = repl_cls()
235
+ self.current_mutation_applied = True
236
+ return new_node
237
+
238
+ self.generic_visit(node)
239
+ return node
240
+
241
+ def visit_UnaryOp(self, node: ast.UnaryOp) -> ast.AST:
242
+ """Visit unary operations (e.g., not, -x, +x, ~x)."""
243
+ op_cls = type(node.op)
244
+ if op_cls in MutationOperator.UNARYOP_REPLACEMENTS:
245
+ for repl_cls in MutationOperator.UNARYOP_REPLACEMENTS[op_cls]:
246
+ loc = MutationLocation(
247
+ lineno=getattr(node, "lineno", 0),
248
+ col_offset=getattr(node, "col_offset", 0),
249
+ node_type="UnaryOp",
250
+ operator_type=OperatorType.UOR,
251
+ original_op=op_cls.__name__,
252
+ replacement_op=repl_cls.__name__,
253
+ description=f"Replace unary op {op_cls.__name__} with {repl_cls.__name__}",
254
+ )
255
+ self.found_locations.append(loc)
256
+
257
+ if self._is_target(loc):
258
+ new_node = copy.deepcopy(node)
259
+ new_node.op = repl_cls()
260
+ self.current_mutation_applied = True
261
+ return new_node
262
+
263
+ self.generic_visit(node)
264
+ return node
265
+
266
+ def visit_Constant(self, node: ast.Constant) -> ast.AST:
267
+ """Visit constant literal nodes."""
268
+ replacements = MutationOperator.get_constant_replacements(node.value)
269
+ for repl_val in replacements:
270
+ loc = MutationLocation(
271
+ lineno=getattr(node, "lineno", 0),
272
+ col_offset=getattr(node, "col_offset", 0),
273
+ node_type="Constant",
274
+ operator_type=OperatorType.LCR,
275
+ original_op=repr(node.value),
276
+ replacement_op=repr(repl_val),
277
+ description=f"Replace constant {repr(node.value)} with {repr(repl_val)}",
278
+ )
279
+ self.found_locations.append(loc)
280
+
281
+ if self._is_target(loc):
282
+ new_node = copy.deepcopy(node)
283
+ new_node.value = repl_val
284
+ self.current_mutation_applied = True
285
+ return new_node
286
+
287
+ self.generic_visit(node)
288
+ return node
289
+
290
+ def _is_target(self, location: MutationLocation) -> bool:
291
+ """Check if the current location matches target location for mutation."""
292
+ if not self.target_location:
293
+ return False
294
+ return (
295
+ not self.current_mutation_applied
296
+ and self.target_location.lineno == location.lineno
297
+ and self.target_location.col_offset == location.col_offset
298
+ and self.target_location.original_op == location.original_op
299
+ and self.target_location.replacement_op == location.replacement_op
300
+ )
301
+
302
+
303
+ def mutate_ast(tree: ast.AST, location: MutationLocation) -> ast.AST:
304
+ """
305
+ Apply a specific mutation to an AST at the specified location.
306
+
307
+ Args:
308
+ tree: The original AST.
309
+ location: The mutation location specification.
310
+
311
+ Returns:
312
+ A new mutated AST.
313
+ """
314
+ copied_tree = copy.deepcopy(tree)
315
+ injector = ASTMutantInjector(target_location=location)
316
+ mutated_tree = injector.visit(copied_tree)
317
+ ast.fix_missing_locations(mutated_tree)
318
+ return mutated_tree
319
+
320
+
321
+ def apply_mutations(source_code: str, locations: Optional[List[MutationLocation]] = None) -> List[Mutant]:
322
+ """
323
+ Parse source code and apply mutations for given or all discovered mutation locations.
324
+
325
+ Args:
326
+ source_code: The Python source code as string.
327
+ locations: Optional list of mutation locations. If None, all possible locations are used.
328
+
329
+ Returns:
330
+ A list of Mutant objects.
331
+ """
332
+ tree = ast.parse(source_code)
333
+ if locations is None:
334
+ collector = ASTMutantInjector()
335
+ locations = collector.collect_mutation_points(tree)
336
+
337
+ mutants: List[Mutant] = []
338
+ for idx, loc in enumerate(locations, start=1):
339
+ mutated_tree = mutate_ast(tree, loc)
340
+ try:
341
+ mutated_code = ast.unparse(mutated_tree)
342
+ except AttributeError:
343
+ import astor # type: ignore
344
+
345
+ mutated_code = astor.to_source(mutated_tree)
346
+
347
+ mutants.append(
348
+ Mutant(
349
+ mutant_id=idx,
350
+ original_code=source_code,
351
+ mutated_code=mutated_code,
352
+ location=loc,
353
+ ast_tree=mutated_tree,
354
+ )
355
+ )
356
+ return mutants
357
+
358
+
359
+ def inject_mutants(source_code: str) -> List[Mutant]:
360
+ """
361
+ Alias/wrapper to generate and inject all possible mutants for a source code string.
362
+
363
+ Args:
364
+ source_code: The Python source code to mutate.
365
+
366
+ Returns:
367
+ List of generated Mutant instances.
368
+ """
369
+ return apply_mutations(source_code)
370
+
371
+
372
+ def generate_mutants(source_code: str) -> List[Mutant]:
373
+ """
374
+ Generate all mutants from Python source code.
375
+
376
+ Args:
377
+ source_code: Python source code string.
378
+
379
+ Returns:
380
+ List of Mutant objects containing mutated code and ASTs.
381
+ """
382
+ return apply_mutations(source_code)