tzero-mcp 10.7.4 → 11.0.0

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 (127) hide show
  1. package/CHANGELOG.md +56 -29
  2. package/CONTRIBUTING.md +71 -71
  3. package/README.md +64 -64
  4. package/bin/tzero-mcp.js +62 -66
  5. package/bin/tzero.js +61 -65
  6. package/index.d.ts +25 -25
  7. package/index.js +15 -15
  8. package/package.json +88 -88
  9. package/src/addmcp.py +14 -11
  10. package/src/app.py +1810 -0
  11. package/src/main.py +1 -1
  12. package/src/pc_fixer_mcp.py +25 -0
  13. package/src/tzero/__init__.py +54 -0
  14. package/src/tzero/__main__.py +6 -0
  15. package/src/tzero/siber_akademi.ico +0 -0
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
  22. package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
  23. package/src/tzero/tzero_contracts.py +1093 -0
  24. package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
  25. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
  26. package/src/tzero/tzero_debt.py +461 -0
  27. package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
  28. package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
  29. package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
  30. package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
  31. package/src/tzero/tzero_federation.py +299 -0
  32. package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
  33. package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
  58. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
  59. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
  60. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
  61. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
  62. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
  63. package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
  64. package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
  65. package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
  66. package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
  67. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
  68. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
  69. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
  70. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
  71. package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
  72. package/src/tzero/tzero_golden.py +319 -0
  73. package/src/tzero/tzero_graph_hud.html +338 -0
  74. package/src/tzero/tzero_graph_rag.py +263 -0
  75. package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
  76. package/src/tzero/tzero_hooks.py +565 -0
  77. package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
  78. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
  79. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
  80. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
  81. package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
  82. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
  83. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
  84. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
  85. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
  86. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
  87. package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
  88. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
  89. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
  90. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
  91. package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
  92. package/src/tzero/tzero_lsp.py +634 -0
  93. package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
  94. package/src/tzero/tzero_mutation.py +358 -0
  95. package/src/tzero/tzero_packer.py +577 -0
  96. package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
  97. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
  98. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
  99. package/src/tzero/tzero_polyglot.py +799 -0
  100. package/src/tzero/tzero_proxy.py +127 -0
  101. package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
  102. package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
  103. package/src/tzero/tzero_rust_bridge.py +198 -0
  104. package/src/tzero/tzero_scip.py +368 -0
  105. package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
  106. package/src/tzero/tzero_semantic_merge.py +189 -0
  107. package/src/tzero/tzero_snapshot.py +471 -0
  108. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
  109. package/src/tzero/tzero_subagent_engine.py +459 -0
  110. package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
  111. package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
  112. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
  113. package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
  114. package/src/tzero/tzero_turbo.py +264 -0
  115. package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
  116. package/src/tzero.py +2 -54
  117. package/test/package.test.js +55 -43
  118. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  119. package/src/tzero_gateway.py +0 -885
  120. package/src/tzero_packer.py +0 -370
  121. package/src/tzero_polyglot.py +0 -422
  122. package/src/tzero_snapshot.py +0 -258
  123. /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
  124. /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
  125. /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
  126. /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
  127. /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
@@ -1,223 +1,223 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero Smart Micro-Patch Recommender & Semantic Diff Engine
4
- ===========================================================
5
- Generates unified, atomic, and idempotent GNU diff micro-patches
6
- for code issues diagnosed across software repositories.
7
-
8
- Features:
9
- - Idempotency verification: guarantees repeated patch applications are safe no-ops
10
- - Blast radius scoring (0-100): measures downstream impact on dependent modules
11
- - Pull Request markdown comment generation for automated code review bots
12
- - Reversible transactional patch formatting compatible with git apply
13
-
14
- Author: Siber Akademi T-Zero R&D Team
15
- License: MIT (100% Free, Local Offline, Zero-Leak)
16
- """
17
-
18
- from __future__ import annotations
19
-
20
- import difflib
21
- import hashlib
22
- import re
23
- import time
24
- from dataclasses import dataclass, field
25
- from pathlib import Path
26
- from typing import Any, Dict, List, Optional, Set, Tuple
27
-
28
- from tzero_fixer.models import (
29
- DiagnosticCategory,
30
- DiagnosticIssue,
31
- DiffHunk,
32
- HealAction,
33
- SeverityLevel,
34
- )
35
-
36
-
37
- @dataclass
38
- class MicroPatch:
39
- patch_id: str
40
- target_file: str
41
- line_number: Optional[int]
42
- unified_diff: str
43
- blast_radius_score: int
44
- idempotent: bool
45
- summary: str
46
- checksum: str
47
- generated_at: float = field(default_factory=time.time)
48
-
49
- def to_markdown(self) -> str:
50
- return f"""#### 🩹 T-Zero Micro-Patch: `{self.target_file}`
51
- - **Patch ID:** `{self.patch_id}` | **Blast Radius:** `{self.blast_radius_score}/100` | **Idempotent:** `{'Yes' if self.idempotent else 'No'}`
52
- - **Summary:** {self.summary}
53
-
54
- ```diff
55
- {self.unified_diff}
56
- ```
57
- """
58
-
59
-
60
- class SmartPatchRecommender:
61
- """
62
- Constructs surgical, atomic patch diffs from DiagnosticIssue instances.
63
- """
64
-
65
- @classmethod
66
- def calculate_blast_radius(cls, file_path: str, line_number: Optional[int], issue: DiagnosticIssue) -> int:
67
- """
68
- Computes blast radius score (0-100) based on issue category and scope:
69
- - Line-level syntax / smell fix: Low blast radius (5 - 15)
70
- - Function signature / mutable default: Moderate blast radius (20 - 40)
71
- - Type annotations: Low blast radius (5 - 10)
72
- - Security secret removal: Moderate blast radius (25 - 45)
73
- - Global environment / config: High blast radius (50 - 80)
74
- """
75
- base = 10
76
- if issue.category == DiagnosticCategory.SYNTAX.value:
77
- base = 10
78
- elif issue.category == DiagnosticCategory.TYPE_HINTS.value:
79
- base = 8
80
- elif issue.category == DiagnosticCategory.SMELLS.value:
81
- base = 20
82
- elif issue.category == DiagnosticCategory.IMPORTS.value:
83
- base = 35
84
- elif issue.category == DiagnosticCategory.SECURITY.value:
85
- base = 30
86
- elif issue.category == DiagnosticCategory.ENVIRONMENT.value:
87
- base = 60
88
- elif issue.category == DiagnosticCategory.POLYGLOT.value:
89
- base = 25
90
-
91
- if issue.severity == SeverityLevel.CRITICAL.value:
92
- base += 15
93
- elif issue.severity == SeverityLevel.WARNING.value:
94
- base += 5
95
-
96
- return min(100, max(0, base))
97
-
98
- @classmethod
99
- def generate_patch_from_hunk(
100
- cls,
101
- file_path: str,
102
- original_line: str,
103
- repaired_line: str,
104
- line_number: int,
105
- summary: str,
106
- issue: DiagnosticIssue,
107
- ) -> MicroPatch:
108
- """Constructs a MicroPatch object with standard unified diff header."""
109
- orig_seq = [original_line + "\n" if not original_line.endswith("\n") else original_line]
110
- rep_seq = [repaired_line + "\n" if not repaired_line.endswith("\n") else repaired_line]
111
-
112
- diff_lines = list(
113
- difflib.unified_diff(
114
- orig_seq,
115
- rep_seq,
116
- fromfile=f"a/{file_path}",
117
- tofile=f"b/{file_path}",
118
- lineterm="",
119
- )
120
- )
121
- diff_str = "\n".join(diff_lines)
122
-
123
- chk = hashlib.sha256(diff_str.encode("utf-8")).hexdigest()[:12]
124
- pid = f"patch_{chk}"
125
-
126
- radius = cls.calculate_blast_radius(file_path, line_number, issue)
127
- idempotent = original_line != repaired_line
128
-
129
- return MicroPatch(
130
- patch_id=pid,
131
- target_file=file_path,
132
- line_number=line_number,
133
- unified_diff=diff_str,
134
- blast_radius_score=radius,
135
- idempotent=idempotent,
136
- summary=summary,
137
- checksum=chk,
138
- )
139
-
140
- @classmethod
141
- def generate_pr_review_comment(cls, patches: List[MicroPatch]) -> str:
142
- """Formats a list of micro-patches into a professional GitHub PR review comment."""
143
- if not patches:
144
- return "✅ **T-Zero Quality Gate:** No automated micro-patches needed. Codebase is clean."
145
-
146
- avg_blast = sum(p.blast_radius_score for p in patches) // len(patches)
147
- lines = [
148
- f"### 🤖 T-Zero Autonomous Self-Healing Proposal ({len(patches)} Micro-Patches)",
149
- f"> **Average Blast Radius:** `{avg_blast}/100` | **Deterministic & Zero-Regression Verified**\n",
150
- "T-Zero detected defects in the modified files and prepared surgical micro-patches:",
151
- "",
152
- ]
153
-
154
- for p in patches:
155
- lines.append(p.to_markdown())
156
-
157
- lines.append(
158
- "\n💡 **How to Apply:**\n"
159
- "Run `tzero doctor --fix` locally or merge the suggestions directly in the GitHub PR."
160
- )
161
-
162
- return "\n".join(lines)
163
-
164
- @classmethod
165
- def apply_patch_in_memory(cls, original_content: str, patch: MicroPatch) -> Tuple[bool, str, str]:
166
- """
167
- Applies unified diff in-memory to verify patch safety and test idempotency.
168
- Returns: (success: bool, patched_content: str, error_message: str)
169
- """
170
- orig_lines = original_content.splitlines(keepends=True)
171
- diff_lines = patch.unified_diff.splitlines(keepends=True)
172
-
173
- # Basic hunk applier for single-file micro-patches
174
- patch_hunks: List[Tuple[int, int, List[str], List[str]]] = []
175
- old_lines: List[str] = []
176
- new_lines: List[str] = []
177
- start_line = 1
178
-
179
- for line in diff_lines:
180
- if line.startswith("@@"):
181
- m = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
182
- if m:
183
- start_line = int(m.group(1))
184
- elif line.startswith("-") and not line.startswith("---"):
185
- old_lines.append(line[1:])
186
- elif line.startswith("+") and not line.startswith("+++"):
187
- new_lines.append(line[1:])
188
- elif line.startswith(" "):
189
- old_lines.append(line[1:])
190
- new_lines.append(line[1:])
191
-
192
- try:
193
- # Check if target region matches old_lines
194
- idx = max(0, start_line - 1)
195
- target_slice = orig_lines[idx : idx + len(old_lines)]
196
- if "".join(target_slice).strip() == "".join(old_lines).strip():
197
- # Apply replacement
198
- result_lines = orig_lines[:idx] + new_lines + orig_lines[idx + len(old_lines) :]
199
- return True, "".join(result_lines), ""
200
- else:
201
- # Fallback line-level search
202
- content_str = "".join(orig_lines)
203
- search_str = "".join(old_lines)
204
- replace_str = "".join(new_lines)
205
- if search_str in content_str:
206
- return True, content_str.replace(search_str, replace_str, 1), ""
207
- return False, original_content, f"Hunk at line {start_line} does not match target file buffer"
208
- except Exception as e:
209
- return False, original_content, f"Patch application exception: {e}"
210
-
211
- @classmethod
212
- def verify_patch_idempotency(cls, original_content: str, patch: MicroPatch) -> bool:
213
- """
214
- Verifies that applying the patch once transforms the content,
215
- and applying it a second time is a clean no-op.
216
- """
217
- ok1, intermediate, _ = cls.apply_patch_in_memory(original_content, patch)
218
- if not ok1 or intermediate == original_content:
219
- return False
220
-
221
- # Second application should be rejected or produce no additional changes
222
- ok2, final, _ = cls.apply_patch_in_memory(intermediate, patch)
223
- return not ok2 or final == intermediate
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero Smart Micro-Patch Recommender & Semantic Diff Engine
4
+ ===========================================================
5
+ Generates unified, atomic, and idempotent GNU diff micro-patches
6
+ for code issues diagnosed across software repositories.
7
+
8
+ Features:
9
+ - Idempotency verification: guarantees repeated patch applications are safe no-ops
10
+ - Blast radius scoring (0-100): measures downstream impact on dependent modules
11
+ - Pull Request markdown comment generation for automated code review bots
12
+ - Reversible transactional patch formatting compatible with git apply
13
+
14
+ Author: Siber Akademi T-Zero R&D Team
15
+ License: MIT (100% Free, Local Offline, Zero-Leak)
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import difflib
21
+ import hashlib
22
+ import re
23
+ import time
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any, Dict, List, Optional, Set, Tuple
27
+
28
+ from tzero.tzero_fixer.models import (
29
+ DiagnosticCategory,
30
+ DiagnosticIssue,
31
+ DiffHunk,
32
+ HealAction,
33
+ SeverityLevel,
34
+ )
35
+
36
+
37
+ @dataclass
38
+ class MicroPatch:
39
+ patch_id: str
40
+ target_file: str
41
+ line_number: Optional[int]
42
+ unified_diff: str
43
+ blast_radius_score: int
44
+ idempotent: bool
45
+ summary: str
46
+ checksum: str
47
+ generated_at: float = field(default_factory=time.time)
48
+
49
+ def to_markdown(self) -> str:
50
+ return f"""#### 🩹 T-Zero Micro-Patch: `{self.target_file}`
51
+ - **Patch ID:** `{self.patch_id}` | **Blast Radius:** `{self.blast_radius_score}/100` | **Idempotent:** `{'Yes' if self.idempotent else 'No'}`
52
+ - **Summary:** {self.summary}
53
+
54
+ ```diff
55
+ {self.unified_diff}
56
+ ```
57
+ """
58
+
59
+
60
+ class SmartPatchRecommender:
61
+ """
62
+ Constructs surgical, atomic patch diffs from DiagnosticIssue instances.
63
+ """
64
+
65
+ @classmethod
66
+ def calculate_blast_radius(cls, file_path: str, line_number: Optional[int], issue: DiagnosticIssue) -> int:
67
+ """
68
+ Computes blast radius score (0-100) based on issue category and scope:
69
+ - Line-level syntax / smell fix: Low blast radius (5 - 15)
70
+ - Function signature / mutable default: Moderate blast radius (20 - 40)
71
+ - Type annotations: Low blast radius (5 - 10)
72
+ - Security secret removal: Moderate blast radius (25 - 45)
73
+ - Global environment / config: High blast radius (50 - 80)
74
+ """
75
+ base = 10
76
+ if issue.category == DiagnosticCategory.SYNTAX.value:
77
+ base = 10
78
+ elif issue.category == DiagnosticCategory.TYPE_HINTS.value:
79
+ base = 8
80
+ elif issue.category == DiagnosticCategory.SMELLS.value:
81
+ base = 20
82
+ elif issue.category == DiagnosticCategory.IMPORTS.value:
83
+ base = 35
84
+ elif issue.category == DiagnosticCategory.SECURITY.value:
85
+ base = 30
86
+ elif issue.category == DiagnosticCategory.ENVIRONMENT.value:
87
+ base = 60
88
+ elif issue.category == DiagnosticCategory.POLYGLOT.value:
89
+ base = 25
90
+
91
+ if issue.severity == SeverityLevel.CRITICAL.value:
92
+ base += 15
93
+ elif issue.severity == SeverityLevel.WARNING.value:
94
+ base += 5
95
+
96
+ return min(100, max(0, base))
97
+
98
+ @classmethod
99
+ def generate_patch_from_hunk(
100
+ cls,
101
+ file_path: str,
102
+ original_line: str,
103
+ repaired_line: str,
104
+ line_number: int,
105
+ summary: str,
106
+ issue: DiagnosticIssue,
107
+ ) -> MicroPatch:
108
+ """Constructs a MicroPatch object with standard unified diff header."""
109
+ orig_seq = [original_line + "\n" if not original_line.endswith("\n") else original_line]
110
+ rep_seq = [repaired_line + "\n" if not repaired_line.endswith("\n") else repaired_line]
111
+
112
+ diff_lines = list(
113
+ difflib.unified_diff(
114
+ orig_seq,
115
+ rep_seq,
116
+ fromfile=f"a/{file_path}",
117
+ tofile=f"b/{file_path}",
118
+ lineterm="",
119
+ )
120
+ )
121
+ diff_str = "\n".join(diff_lines)
122
+
123
+ chk = hashlib.sha256(diff_str.encode("utf-8")).hexdigest()[:12]
124
+ pid = f"patch_{chk}"
125
+
126
+ radius = cls.calculate_blast_radius(file_path, line_number, issue)
127
+ idempotent = original_line != repaired_line
128
+
129
+ return MicroPatch(
130
+ patch_id=pid,
131
+ target_file=file_path,
132
+ line_number=line_number,
133
+ unified_diff=diff_str,
134
+ blast_radius_score=radius,
135
+ idempotent=idempotent,
136
+ summary=summary,
137
+ checksum=chk,
138
+ )
139
+
140
+ @classmethod
141
+ def generate_pr_review_comment(cls, patches: List[MicroPatch]) -> str:
142
+ """Formats a list of micro-patches into a professional GitHub PR review comment."""
143
+ if not patches:
144
+ return "✅ **T-Zero Quality Gate:** No automated micro-patches needed. Codebase is clean."
145
+
146
+ avg_blast = sum(p.blast_radius_score for p in patches) // len(patches)
147
+ lines = [
148
+ f"### 🤖 T-Zero Autonomous Self-Healing Proposal ({len(patches)} Micro-Patches)",
149
+ f"> **Average Blast Radius:** `{avg_blast}/100` | **Deterministic & Zero-Regression Verified**\n",
150
+ "T-Zero detected defects in the modified files and prepared surgical micro-patches:",
151
+ "",
152
+ ]
153
+
154
+ for p in patches:
155
+ lines.append(p.to_markdown())
156
+
157
+ lines.append(
158
+ "\n💡 **How to Apply:**\n"
159
+ "Run `tzero doctor --fix` locally or merge the suggestions directly in the GitHub PR."
160
+ )
161
+
162
+ return "\n".join(lines)
163
+
164
+ @classmethod
165
+ def apply_patch_in_memory(cls, original_content: str, patch: MicroPatch) -> Tuple[bool, str, str]:
166
+ """
167
+ Applies unified diff in-memory to verify patch safety and test idempotency.
168
+ Returns: (success: bool, patched_content: str, error_message: str)
169
+ """
170
+ orig_lines = original_content.splitlines(keepends=True)
171
+ diff_lines = patch.unified_diff.splitlines(keepends=True)
172
+
173
+ # Basic hunk applier for single-file micro-patches
174
+ patch_hunks: List[Tuple[int, int, List[str], List[str]]] = []
175
+ old_lines: List[str] = []
176
+ new_lines: List[str] = []
177
+ start_line = 1
178
+
179
+ for line in diff_lines:
180
+ if line.startswith("@@"):
181
+ m = re.match(r"@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@", line)
182
+ if m:
183
+ start_line = int(m.group(1))
184
+ elif line.startswith("-") and not line.startswith("---"):
185
+ old_lines.append(line[1:])
186
+ elif line.startswith("+") and not line.startswith("+++"):
187
+ new_lines.append(line[1:])
188
+ elif line.startswith(" "):
189
+ old_lines.append(line[1:])
190
+ new_lines.append(line[1:])
191
+
192
+ try:
193
+ # Check if target region matches old_lines
194
+ idx = max(0, start_line - 1)
195
+ target_slice = orig_lines[idx : idx + len(old_lines)]
196
+ if "".join(target_slice).strip() == "".join(old_lines).strip():
197
+ # Apply replacement
198
+ result_lines = orig_lines[:idx] + new_lines + orig_lines[idx + len(old_lines) :]
199
+ return True, "".join(result_lines), ""
200
+ else:
201
+ # Fallback line-level search
202
+ content_str = "".join(orig_lines)
203
+ search_str = "".join(old_lines)
204
+ replace_str = "".join(new_lines)
205
+ if search_str in content_str:
206
+ return True, content_str.replace(search_str, replace_str, 1), ""
207
+ return False, original_content, f"Hunk at line {start_line} does not match target file buffer"
208
+ except Exception as e:
209
+ return False, original_content, f"Patch application exception: {e}"
210
+
211
+ @classmethod
212
+ def verify_patch_idempotency(cls, original_content: str, patch: MicroPatch) -> bool:
213
+ """
214
+ Verifies that applying the patch once transforms the content,
215
+ and applying it a second time is a clean no-op.
216
+ """
217
+ ok1, intermediate, _ = cls.apply_patch_in_memory(original_content, patch)
218
+ if not ok1 or intermediate == original_content:
219
+ return False
220
+
221
+ # Second application should be rejected or produce no additional changes
222
+ ok2, final, _ = cls.apply_patch_in_memory(intermediate, patch)
223
+ return not ok2 or final == intermediate