tzero-mcp 10.7.4 → 11.11.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 (131) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -3
  4. package/bin/tzero-mcp.js +7 -11
  5. package/bin/tzero.js +7 -11
  6. package/index.js +3 -3
  7. package/package.json +3 -2
  8. package/src/addmcp.py +1203 -1194
  9. package/src/app.py +1810 -0
  10. package/src/main.py +60 -60
  11. package/src/pc_fixer_mcp.py +25 -0
  12. package/src/tzero/__init__.py +54 -0
  13. package/src/tzero/__main__.py +6 -0
  14. package/src/tzero/siber_akademi.ico +0 -0
  15. package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +77 -77
  16. package/src/tzero/tzero_arch_test.py +463 -0
  17. package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +2 -2
  18. package/src/tzero/tzero_blackboard.py +257 -0
  19. package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +184 -0
  20. package/src/tzero/tzero_budget.py +195 -0
  21. package/src/tzero/tzero_card.py +431 -0
  22. package/src/{tzero_ci.py → tzero/tzero_ci.py} +7 -7
  23. package/src/{tzero_commit.py → tzero/tzero_commit.py} +1 -1
  24. package/src/tzero/tzero_contracts.py +1093 -0
  25. package/src/{tzero_cost.py → tzero/tzero_cost.py} +4 -1
  26. package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +1960 -1448
  27. package/src/tzero/tzero_debt.py +461 -0
  28. package/src/{tzero_deps.py → tzero/tzero_deps.py} +462 -287
  29. package/src/{tzero_drift.py → tzero/tzero_drift.py} +1 -1
  30. package/src/{tzero_explain.py → tzero/tzero_explain.py} +306 -240
  31. package/src/{tzero_features.py → tzero/tzero_features.py} +3024 -3022
  32. package/src/tzero/tzero_federation.py +299 -0
  33. package/src/tzero/tzero_fix.py +557 -0
  34. package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +334 -334
  35. package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +1 -1
  36. package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +8 -8
  37. package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +1 -1
  38. package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +1 -1
  39. package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +1 -1
  40. package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +1 -1
  41. package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +1 -1
  42. package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +280 -280
  43. package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +325 -325
  44. package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +489 -447
  45. package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +385 -385
  46. package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +375 -375
  47. package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +323 -323
  48. package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +2 -1
  49. package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +1 -1
  50. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +1 -1
  51. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +364 -364
  52. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +619 -619
  53. package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +1 -1
  54. package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +1 -1
  55. package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +2 -2
  56. package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +493 -493
  57. package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +1 -1
  58. package/src/tzero/tzero_golden.py +319 -0
  59. package/src/tzero/tzero_graph_hud.html +338 -0
  60. package/src/tzero/tzero_graph_rag.py +263 -0
  61. package/src/tzero/tzero_growth.py +415 -0
  62. package/src/{tzero_guard.py → tzero/tzero_guard.py} +11 -3
  63. package/src/tzero/tzero_hooks.py +565 -0
  64. package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +11 -1
  65. package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +1 -1
  66. package/src/tzero/tzero_jarvis/creative_director.py +333 -0
  67. package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +1 -1
  68. package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +2 -2
  69. package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +1 -1
  70. package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +1 -1
  71. package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +2 -2
  72. package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +1 -1
  73. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +3 -3
  74. package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +1 -1
  75. package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +6 -6
  76. package/src/tzero/tzero_lsp.py +634 -0
  77. package/src/tzero/tzero_mcp.py +5314 -0
  78. package/src/tzero/tzero_mutation.py +358 -0
  79. package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +1425 -1425
  80. package/src/tzero/tzero_packer.py +577 -0
  81. package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +42 -0
  82. package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +1 -1
  83. package/src/tzero/tzero_polyglot.py +799 -0
  84. package/src/tzero/tzero_proxy.py +127 -0
  85. package/src/tzero/tzero_rust_bridge.py +198 -0
  86. package/src/tzero/tzero_scip.py +368 -0
  87. package/src/{tzero_security.py → tzero/tzero_security.py} +573 -570
  88. package/src/tzero/tzero_semantic_merge.py +189 -0
  89. package/src/tzero/tzero_snapshot.py +471 -0
  90. package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +1 -1
  91. package/src/tzero/tzero_subagent_engine.py +459 -0
  92. package/src/{tzero_sync.py → tzero/tzero_sync.py} +2 -2
  93. package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +174 -31
  94. package/src/{tzero_tui.py → tzero/tzero_tui.py} +313 -244
  95. package/src/tzero/tzero_turbo.py +264 -0
  96. package/src/{tzero_v3.py → tzero/tzero_v3.py} +9997 -9435
  97. package/src/tzero.py +6 -58
  98. package/src/tzero_mcp.py +25 -4858
  99. package/test/package.test.js +14 -2
  100. package/src/tzero/jarvis/semantic_compressor.py +0 -373
  101. package/src/tzero_fix.py +0 -228
  102. package/src/tzero_gateway.py +0 -885
  103. package/src/tzero_packer.py +0 -370
  104. package/src/tzero_polyglot.py +0 -422
  105. package/src/tzero_snapshot.py +0 -258
  106. /package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +0 -0
  107. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +0 -0
  108. /package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +0 -0
  109. /package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +0 -0
  110. /package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +0 -0
  111. /package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +0 -0
  112. /package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +0 -0
  113. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +0 -0
  114. /package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +0 -0
  115. /package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +0 -0
  116. /package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +0 -0
  117. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +0 -0
  118. /package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +0 -0
  119. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +0 -0
  120. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +0 -0
  121. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +0 -0
  122. /package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +0 -0
  123. /package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +0 -0
  124. /package/src/{tzero_infra.py → tzero/tzero_infra.py} +0 -0
  125. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +0 -0
  126. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +0 -0
  127. /package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +0 -0
  128. /package/src/{tzero_patch.py → tzero/tzero_patch.py} +0 -0
  129. /package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +0 -0
  130. /package/src/{tzero_replay.py → tzero/tzero_replay.py} +0 -0
  131. /package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +0 -0
@@ -24,7 +24,7 @@ from dataclasses import dataclass
24
24
  from pathlib import Path
25
25
  from typing import Any, Dict, List, Optional, Tuple
26
26
 
27
- from tzero_fixer.models import (
27
+ from tzero.tzero_fixer.models import (
28
28
  DiagnosticCategory,
29
29
  DiagnosticIssue,
30
30
  HealAction,
@@ -26,19 +26,19 @@ import tempfile
26
26
  from typing import Dict, List, Optional, Tuple, Any, Callable
27
27
  from dataclasses import dataclass, field
28
28
 
29
- from tzero_fixer.models import (
29
+ from tzero.tzero_fixer.models import (
30
30
  DiagnosticCategory,
31
31
  DiagnosticIssue,
32
32
  HealAction,
33
33
  SeverityLevel,
34
34
  )
35
- from tzero_fixer.ast_syntax_healer import ASTSyntaxHealer
36
- from tzero_fixer.ast_type_modernizer import ASTTypeModernizer
37
- from tzero_fixer.code_smells_healer import CodeSmellsHealer
38
- from tzero_fixer.import_graph_healer import ImportGraphHealer
39
- from tzero_fixer.security_zero_leak import SecurityZeroLeakDoctor
40
- from tzero_fixer.polyglot_config_healer import PolyglotConfigHealer
41
- from tzero_fixer.polyglot_linters import (
35
+ from tzero.tzero_fixer.ast_syntax_healer import ASTSyntaxHealer
36
+ from tzero.tzero_fixer.ast_type_modernizer import ASTTypeModernizer
37
+ from tzero.tzero_fixer.code_smells_healer import CodeSmellsHealer
38
+ from tzero.tzero_fixer.import_graph_healer import ImportGraphHealer
39
+ from tzero.tzero_fixer.security_zero_leak import SecurityZeroLeakDoctor
40
+ from tzero.tzero_fixer.polyglot_config_healer import PolyglotConfigHealer
41
+ from tzero.tzero_fixer.polyglot_linters import (
42
42
  MarkdownLinterHealer,
43
43
  TomlLinterHealer,
44
44
  YamlCiCdLinterHealer,
@@ -24,7 +24,7 @@ from dataclasses import dataclass, field
24
24
  from pathlib import Path
25
25
  from typing import Any, Dict, List, Optional, Set, Tuple
26
26
 
27
- from tzero_fixer.models import (
27
+ from tzero.tzero_fixer.models import (
28
28
  DiagnosticCategory,
29
29
  DiagnosticIssue,
30
30
  DiagnosticReport,
@@ -21,7 +21,7 @@ from dataclasses import dataclass, field
21
21
  from pathlib import Path
22
22
  from typing import Any, Dict, List, Optional, Set, Tuple
23
23
 
24
- from tzero_fixer.models import (
24
+ from tzero.tzero_fixer.models import (
25
25
  DiagnosticCategory,
26
26
  DiagnosticIssue,
27
27
  DiffHunk,
@@ -30,7 +30,7 @@ from dataclasses import dataclass
30
30
  from pathlib import Path
31
31
  from typing import Any, Dict, List, Optional, Tuple
32
32
 
33
- from tzero_fixer.models import (
33
+ from tzero.tzero_fixer.models import (
34
34
  DiagnosticCategory,
35
35
  DiagnosticIssue,
36
36
  HealAction,
@@ -23,7 +23,7 @@ from dataclasses import dataclass
23
23
  from pathlib import Path
24
24
  from typing import Any, Dict, List, Optional, Set, Tuple
25
25
 
26
- from tzero_fixer.models import (
26
+ from tzero.tzero_fixer.models import (
27
27
  DiagnosticCategory,
28
28
  DiagnosticIssue,
29
29
  HealAction,
@@ -25,7 +25,7 @@ from dataclasses import dataclass, field
25
25
  from pathlib import Path
26
26
  from typing import Any, Dict, List, Optional, Set, Tuple
27
27
 
28
- from tzero_fixer.models import (
28
+ from tzero.tzero_fixer.models import (
29
29
  DiagnosticCategory,
30
30
  DiagnosticIssue,
31
31
  HealAction,
@@ -1,280 +1,280 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- T-Zero Git Advanced Surgeon & VCS Integrity Healer
4
- =================================================
5
- Deep surgical recovery and diagnostics for Git version control repositories,
6
- stale lockfiles, detached HEAD states, stalled rebase/merge operations,
7
- uninitialized submodules, and cross-platform line ending conflicts.
8
-
9
- Key Capabilities:
10
- - Stale lock detection & surgical removal (.git/index.lock, refs/heads/*.lock, HEAD.lock)
11
- - Stalled rebase/merge state diagnostic (.git/rebase-merge, .git/MERGE_HEAD, CHERRY_PICK_HEAD)
12
- - Detached HEAD state detection and branch rescue
13
- - Submodule alignment & uninitialized repository recovery
14
- - Cross-platform line-ending (.gitattributes) standardizer
15
- - Large binary file commit warning (>50MB) to prevent repo bloat
16
-
17
- Author: Siber Akademi T-Zero R&D Team
18
- Version: 10.5.0 | 100% Free & Local Offline | Zero-Leak Certified
19
- """
20
-
21
- from __future__ import annotations
22
-
23
- import os
24
- import re
25
- import shutil
26
- import subprocess
27
- import time
28
- from dataclasses import dataclass, field
29
- from pathlib import Path
30
- from typing import Any, Dict, List, Optional, Set, Tuple
31
-
32
- from tzero_fixer.models import (
33
- DiagnosticCategory,
34
- DiagnosticIssue,
35
- HealAction,
36
- SeverityLevel,
37
- SystemPlatform,
38
- )
39
-
40
-
41
- @dataclass
42
- class GitLockInfo:
43
- lock_path: str
44
- age_seconds: float
45
- is_stale: bool
46
-
47
-
48
- @dataclass
49
- class GitRebaseState:
50
- in_rebase: bool
51
- in_merge: bool
52
- in_cherry_pick: bool
53
- head_hash: Optional[str] = None
54
-
55
-
56
- class GitAdvancedSurgeon:
57
- """Diagnostic and surgical engine for Git repositories and VCS integrity."""
58
-
59
- STALE_LOCK_THRESHOLD_SECONDS = 300.0 # 5 minutes
60
-
61
- @classmethod
62
- def diagnose_workspace(cls, workspace_path: str) -> List[DiagnosticIssue]:
63
- """Diagnose all Git VCS issues in the workspace."""
64
- issues: List[DiagnosticIssue] = []
65
- root = Path(workspace_path).resolve()
66
- git_dir = root / ".git"
67
-
68
- if not git_dir.is_dir():
69
- # Check if this should be a git repo
70
- if (root / ".gitignore").is_file() or (root / "pyproject.toml").is_file():
71
- issues.append(DiagnosticIssue(
72
- category=DiagnosticCategory.WORKSPACE,
73
- severity=SeverityLevel.INFO,
74
- description="Workspace contains project files but is not initialized as a Git repository",
75
- file_path=str(root),
76
- suggested_fix="Initialize repository with 'git init'",
77
- metadata={"issue_type": "git_not_initialized"},
78
- ))
79
- return issues
80
-
81
- # 1. Stale locks (.git/index.lock, .git/HEAD.lock, refs locks)
82
- locks = cls._find_git_locks(git_dir)
83
- for lock in locks:
84
- if lock.is_stale:
85
- issues.append(DiagnosticIssue(
86
- category=DiagnosticCategory.WORKSPACE,
87
- severity=SeverityLevel.ERROR,
88
- description=f"Stale Git lock file detected ({int(lock.age_seconds)}s old): '{Path(lock.lock_path).name}' blocking git operations",
89
- file_path=lock.lock_path,
90
- suggested_fix="Safely remove orphaned lock file to unblock git",
91
- metadata={"issue_type": "stale_git_lock", "lock_path": lock.lock_path},
92
- ))
93
-
94
- # 2. Stalled rebase / merge / cherry-pick
95
- rebase_state = cls._check_rebase_state(git_dir)
96
- if rebase_state.in_rebase:
97
- issues.append(DiagnosticIssue(
98
- category=DiagnosticCategory.WORKSPACE,
99
- severity=SeverityLevel.WARNING,
100
- description="Git repository is stuck in an active or stalled rebase state (.git/rebase-merge or rebase-apply)",
101
- file_path=str(git_dir),
102
- suggested_fix="Abort stalled rebase with 'git rebase --abort' or complete with '--continue'",
103
- metadata={"issue_type": "stalled_rebase"},
104
- ))
105
- if rebase_state.in_merge:
106
- issues.append(DiagnosticIssue(
107
- category=DiagnosticCategory.WORKSPACE,
108
- severity=SeverityLevel.WARNING,
109
- description="Git repository has an unresolved merge in progress (.git/MERGE_HEAD)",
110
- file_path=str(git_dir),
111
- suggested_fix="Abort unresolved merge with 'git merge --abort'",
112
- metadata={"issue_type": "unresolved_merge"},
113
- ))
114
-
115
- # 3. Submodule synchronization
116
- gitmodules_file = root / ".gitmodules"
117
- if gitmodules_file.is_file():
118
- submodule_issues = cls._audit_submodules(root)
119
- issues.extend(submodule_issues)
120
-
121
- # 4. .gitattributes cross-platform line ending check
122
- gitattributes_file = root / ".gitattributes"
123
- if not gitattributes_file.is_file():
124
- issues.append(DiagnosticIssue(
125
- category=DiagnosticCategory.WORKSPACE,
126
- severity=SeverityLevel.INFO,
127
- description="Missing '.gitattributes' configuration for standardized cross-platform line endings (CRLF vs LF)",
128
- file_path=str(gitattributes_file),
129
- suggested_fix="Generate standardized .gitattributes file with auto-normalization",
130
- metadata={"issue_type": "missing_gitattributes"},
131
- ))
132
-
133
- # 5. Detached HEAD check
134
- if cls._is_detached_head(root):
135
- issues.append(DiagnosticIssue(
136
- category=DiagnosticCategory.WORKSPACE,
137
- severity=SeverityLevel.WARNING,
138
- description="Repository is in a 'detached HEAD' state (commits may become orphaned if not branched)",
139
- file_path=str(git_dir),
140
- suggested_fix="Create a safety rescue branch from current commit: 'git branch rescue-detached-head'",
141
- metadata={"issue_type": "detached_head"},
142
- ))
143
-
144
- return issues
145
-
146
- @classmethod
147
- def _find_git_locks(cls, git_dir: Path) -> List[GitLockInfo]:
148
- """Find any lock files in .git directory and compute their age."""
149
- locks: List[GitLockInfo] = []
150
- now = time.time()
151
-
152
- for lock_file in git_dir.glob("**/*.lock"):
153
- try:
154
- mtime = lock_file.stat().st_mtime
155
- age = now - mtime
156
- is_stale = age > cls.STALE_LOCK_THRESHOLD_SECONDS
157
- locks.append(GitLockInfo(
158
- lock_path=str(lock_file),
159
- age_seconds=age,
160
- is_stale=is_stale,
161
- ))
162
- except Exception:
163
- pass
164
-
165
- return locks
166
-
167
- @classmethod
168
- def _check_rebase_state(cls, git_dir: Path) -> GitRebaseState:
169
- """Check if Git is currently in rebase, merge, or cherry-pick states."""
170
- in_rebase = (git_dir / "rebase-merge").is_dir() or (git_dir / "rebase-apply").is_dir()
171
- in_merge = (git_dir / "MERGE_HEAD").is_file()
172
- in_cherry = (git_dir / "CHERRY_PICK_HEAD").is_file()
173
- return GitRebaseState(
174
- in_rebase=in_rebase,
175
- in_merge=in_merge,
176
- in_cherry_pick=in_cherry,
177
- )
178
-
179
- @classmethod
180
- def _is_detached_head(cls, repo_root: Path) -> bool:
181
- """Determine if HEAD is currently detached."""
182
- head_file = repo_root / ".git" / "HEAD"
183
- if head_file.is_file():
184
- try:
185
- content = head_file.read_text(encoding="utf-8", errors="replace").strip()
186
- return not content.startswith("ref:")
187
- except Exception:
188
- pass
189
- return False
190
-
191
- @classmethod
192
- def _audit_submodules(cls, repo_root: Path) -> List[DiagnosticIssue]:
193
- """Audit submodules listed in .gitmodules."""
194
- issues: List[DiagnosticIssue] = []
195
- gitmodules_path = repo_root / ".gitmodules"
196
- try:
197
- content = gitmodules_path.read_text(encoding="utf-8", errors="replace")
198
- # Parse path = ...
199
- paths = re.findall(r"path\s*=\s*(.+)", content)
200
- for sub_rel_path in paths:
201
- sub_rel_path = sub_rel_path.strip()
202
- sub_dir = repo_root / sub_rel_path
203
- if not sub_dir.is_dir() or not any(sub_dir.iterdir()):
204
- issues.append(DiagnosticIssue(
205
- category=DiagnosticCategory.WORKSPACE,
206
- severity=SeverityLevel.WARNING,
207
- description=f"Submodule '{sub_rel_path}' is uninitialized or empty directory",
208
- file_path=str(sub_dir),
209
- suggested_fix="Run 'git submodule update --init --recursive'",
210
- metadata={"issue_type": "uninitialized_submodule", "submodule_path": sub_rel_path},
211
- ))
212
- except Exception:
213
- pass
214
- return issues
215
-
216
- @classmethod
217
- def heal_issue(cls, issue: DiagnosticIssue, dry_run: bool = False) -> HealAction:
218
- """Autonomously heal Git repository issues."""
219
- itype = issue.metadata.get("issue_type")
220
- file_path = issue.file_path
221
-
222
- if itype == "stale_git_lock" and file_path:
223
- p = Path(file_path)
224
- if dry_run:
225
- return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would delete stale git lock: {p.name}")
226
- if p.is_file():
227
- try:
228
- p.unlink()
229
- return HealAction(issue=issue, success=True, details=f"Removed stale Git lock file: {p.name}")
230
- except Exception as e:
231
- return HealAction(issue=issue, success=False, details=f"Failed to remove lock: {e}")
232
-
233
- if itype == "missing_gitattributes" and file_path:
234
- p = Path(file_path)
235
- if dry_run:
236
- return HealAction(issue=issue, success=True, details="[Dry-Run] Would create standardized .gitattributes")
237
-
238
- gitattrs = (
239
- "# Auto normalize text files to LF on checkout\n"
240
- "* text=auto eol=lf\n\n"
241
- "# Python and config files\n"
242
- "*.py text eol=lf\n"
243
- "*.json text eol=lf\n"
244
- "*.yaml text eol=lf\n"
245
- "*.yml text eol=lf\n"
246
- "*.toml text eol=lf\n"
247
- "*.md text eol=lf\n\n"
248
- "# Binary files\n"
249
- "*.pyd binary\n"
250
- "*.so binary\n"
251
- "*.dll binary\n"
252
- "*.exe binary\n"
253
- "*.whl binary\n"
254
- )
255
- p.write_text(gitattrs, encoding="utf-8")
256
- return HealAction(issue=issue, success=True, details="Generated standardized .gitattributes with universal LF normalization")
257
-
258
- if itype == "detached_head":
259
- root = Path(file_path).parent if file_path and file_path.endswith(".git") else Path(".")
260
- branch_name = f"rescue-detached-head-{int(time.time())}"
261
- if dry_run:
262
- return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would create safety rescue branch '{branch_name}'")
263
- try:
264
- subprocess.run(["git", "branch", branch_name], cwd=str(root), check=True, capture_output=True)
265
- return HealAction(issue=issue, success=True, details=f"Created safety rescue branch '{branch_name}' from detached HEAD")
266
- except Exception as e:
267
- return HealAction(issue=issue, success=False, details=f"Failed to create rescue branch: {e}")
268
-
269
- if itype == "uninitialized_submodule":
270
- root = Path(file_path).parent
271
- if dry_run:
272
- return HealAction(issue=issue, success=True, details="[Dry-Run] Would run git submodule update --init --recursive")
273
- try:
274
- subprocess.run(["git", "submodule", "update", "--init", "--recursive"], cwd=str(root), check=True, capture_output=True)
275
- return HealAction(issue=issue, success=True, details="Synchronized and initialized Git submodules")
276
- except Exception as e:
277
- return HealAction(issue=issue, success=False, details=f"Submodule sync failed: {e}")
278
-
279
- return HealAction(issue=issue, success=False, details=f"No automated repair for issue type '{itype}'")
280
-
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero Git Advanced Surgeon & VCS Integrity Healer
4
+ =================================================
5
+ Deep surgical recovery and diagnostics for Git version control repositories,
6
+ stale lockfiles, detached HEAD states, stalled rebase/merge operations,
7
+ uninitialized submodules, and cross-platform line ending conflicts.
8
+
9
+ Key Capabilities:
10
+ - Stale lock detection & surgical removal (.git/index.lock, refs/heads/*.lock, HEAD.lock)
11
+ - Stalled rebase/merge state diagnostic (.git/rebase-merge, .git/MERGE_HEAD, CHERRY_PICK_HEAD)
12
+ - Detached HEAD state detection and branch rescue
13
+ - Submodule alignment & uninitialized repository recovery
14
+ - Cross-platform line-ending (.gitattributes) standardizer
15
+ - Large binary file commit warning (>50MB) to prevent repo bloat
16
+
17
+ Author: Siber Akademi T-Zero R&D Team
18
+ Version: 10.5.0 | 100% Free & Local Offline | Zero-Leak Certified
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import os
24
+ import re
25
+ import shutil
26
+ import subprocess
27
+ import time
28
+ from dataclasses import dataclass, field
29
+ from pathlib import Path
30
+ from typing import Any, Dict, List, Optional, Set, Tuple
31
+
32
+ from tzero.tzero_fixer.models import (
33
+ DiagnosticCategory,
34
+ DiagnosticIssue,
35
+ HealAction,
36
+ SeverityLevel,
37
+ SystemPlatform,
38
+ )
39
+
40
+
41
+ @dataclass
42
+ class GitLockInfo:
43
+ lock_path: str
44
+ age_seconds: float
45
+ is_stale: bool
46
+
47
+
48
+ @dataclass
49
+ class GitRebaseState:
50
+ in_rebase: bool
51
+ in_merge: bool
52
+ in_cherry_pick: bool
53
+ head_hash: Optional[str] = None
54
+
55
+
56
+ class GitAdvancedSurgeon:
57
+ """Diagnostic and surgical engine for Git repositories and VCS integrity."""
58
+
59
+ STALE_LOCK_THRESHOLD_SECONDS = 300.0 # 5 minutes
60
+
61
+ @classmethod
62
+ def diagnose_workspace(cls, workspace_path: str) -> List[DiagnosticIssue]:
63
+ """Diagnose all Git VCS issues in the workspace."""
64
+ issues: List[DiagnosticIssue] = []
65
+ root = Path(workspace_path).resolve()
66
+ git_dir = root / ".git"
67
+
68
+ if not git_dir.is_dir():
69
+ # Check if this should be a git repo
70
+ if (root / ".gitignore").is_file() or (root / "pyproject.toml").is_file():
71
+ issues.append(DiagnosticIssue(
72
+ category=DiagnosticCategory.WORKSPACE,
73
+ severity=SeverityLevel.INFO,
74
+ description="Workspace contains project files but is not initialized as a Git repository",
75
+ file_path=str(root),
76
+ suggested_fix="Initialize repository with 'git init'",
77
+ metadata={"issue_type": "git_not_initialized"},
78
+ ))
79
+ return issues
80
+
81
+ # 1. Stale locks (.git/index.lock, .git/HEAD.lock, refs locks)
82
+ locks = cls._find_git_locks(git_dir)
83
+ for lock in locks:
84
+ if lock.is_stale:
85
+ issues.append(DiagnosticIssue(
86
+ category=DiagnosticCategory.WORKSPACE,
87
+ severity=SeverityLevel.ERROR,
88
+ description=f"Stale Git lock file detected ({int(lock.age_seconds)}s old): '{Path(lock.lock_path).name}' blocking git operations",
89
+ file_path=lock.lock_path,
90
+ suggested_fix="Safely remove orphaned lock file to unblock git",
91
+ metadata={"issue_type": "stale_git_lock", "lock_path": lock.lock_path},
92
+ ))
93
+
94
+ # 2. Stalled rebase / merge / cherry-pick
95
+ rebase_state = cls._check_rebase_state(git_dir)
96
+ if rebase_state.in_rebase:
97
+ issues.append(DiagnosticIssue(
98
+ category=DiagnosticCategory.WORKSPACE,
99
+ severity=SeverityLevel.WARNING,
100
+ description="Git repository is stuck in an active or stalled rebase state (.git/rebase-merge or rebase-apply)",
101
+ file_path=str(git_dir),
102
+ suggested_fix="Abort stalled rebase with 'git rebase --abort' or complete with '--continue'",
103
+ metadata={"issue_type": "stalled_rebase"},
104
+ ))
105
+ if rebase_state.in_merge:
106
+ issues.append(DiagnosticIssue(
107
+ category=DiagnosticCategory.WORKSPACE,
108
+ severity=SeverityLevel.WARNING,
109
+ description="Git repository has an unresolved merge in progress (.git/MERGE_HEAD)",
110
+ file_path=str(git_dir),
111
+ suggested_fix="Abort unresolved merge with 'git merge --abort'",
112
+ metadata={"issue_type": "unresolved_merge"},
113
+ ))
114
+
115
+ # 3. Submodule synchronization
116
+ gitmodules_file = root / ".gitmodules"
117
+ if gitmodules_file.is_file():
118
+ submodule_issues = cls._audit_submodules(root)
119
+ issues.extend(submodule_issues)
120
+
121
+ # 4. .gitattributes cross-platform line ending check
122
+ gitattributes_file = root / ".gitattributes"
123
+ if not gitattributes_file.is_file():
124
+ issues.append(DiagnosticIssue(
125
+ category=DiagnosticCategory.WORKSPACE,
126
+ severity=SeverityLevel.INFO,
127
+ description="Missing '.gitattributes' configuration for standardized cross-platform line endings (CRLF vs LF)",
128
+ file_path=str(gitattributes_file),
129
+ suggested_fix="Generate standardized .gitattributes file with auto-normalization",
130
+ metadata={"issue_type": "missing_gitattributes"},
131
+ ))
132
+
133
+ # 5. Detached HEAD check
134
+ if cls._is_detached_head(root):
135
+ issues.append(DiagnosticIssue(
136
+ category=DiagnosticCategory.WORKSPACE,
137
+ severity=SeverityLevel.WARNING,
138
+ description="Repository is in a 'detached HEAD' state (commits may become orphaned if not branched)",
139
+ file_path=str(git_dir),
140
+ suggested_fix="Create a safety rescue branch from current commit: 'git branch rescue-detached-head'",
141
+ metadata={"issue_type": "detached_head"},
142
+ ))
143
+
144
+ return issues
145
+
146
+ @classmethod
147
+ def _find_git_locks(cls, git_dir: Path) -> List[GitLockInfo]:
148
+ """Find any lock files in .git directory and compute their age."""
149
+ locks: List[GitLockInfo] = []
150
+ now = time.time()
151
+
152
+ for lock_file in git_dir.glob("**/*.lock"):
153
+ try:
154
+ mtime = lock_file.stat().st_mtime
155
+ age = now - mtime
156
+ is_stale = age > cls.STALE_LOCK_THRESHOLD_SECONDS
157
+ locks.append(GitLockInfo(
158
+ lock_path=str(lock_file),
159
+ age_seconds=age,
160
+ is_stale=is_stale,
161
+ ))
162
+ except Exception:
163
+ pass
164
+
165
+ return locks
166
+
167
+ @classmethod
168
+ def _check_rebase_state(cls, git_dir: Path) -> GitRebaseState:
169
+ """Check if Git is currently in rebase, merge, or cherry-pick states."""
170
+ in_rebase = (git_dir / "rebase-merge").is_dir() or (git_dir / "rebase-apply").is_dir()
171
+ in_merge = (git_dir / "MERGE_HEAD").is_file()
172
+ in_cherry = (git_dir / "CHERRY_PICK_HEAD").is_file()
173
+ return GitRebaseState(
174
+ in_rebase=in_rebase,
175
+ in_merge=in_merge,
176
+ in_cherry_pick=in_cherry,
177
+ )
178
+
179
+ @classmethod
180
+ def _is_detached_head(cls, repo_root: Path) -> bool:
181
+ """Determine if HEAD is currently detached."""
182
+ head_file = repo_root / ".git" / "HEAD"
183
+ if head_file.is_file():
184
+ try:
185
+ content = head_file.read_text(encoding="utf-8", errors="replace").strip()
186
+ return not content.startswith("ref:")
187
+ except Exception:
188
+ pass
189
+ return False
190
+
191
+ @classmethod
192
+ def _audit_submodules(cls, repo_root: Path) -> List[DiagnosticIssue]:
193
+ """Audit submodules listed in .gitmodules."""
194
+ issues: List[DiagnosticIssue] = []
195
+ gitmodules_path = repo_root / ".gitmodules"
196
+ try:
197
+ content = gitmodules_path.read_text(encoding="utf-8", errors="replace")
198
+ # Parse path = ...
199
+ paths = re.findall(r"path\s*=\s*(.+)", content)
200
+ for sub_rel_path in paths:
201
+ sub_rel_path = sub_rel_path.strip()
202
+ sub_dir = repo_root / sub_rel_path
203
+ if not sub_dir.is_dir() or not any(sub_dir.iterdir()):
204
+ issues.append(DiagnosticIssue(
205
+ category=DiagnosticCategory.WORKSPACE,
206
+ severity=SeverityLevel.WARNING,
207
+ description=f"Submodule '{sub_rel_path}' is uninitialized or empty directory",
208
+ file_path=str(sub_dir),
209
+ suggested_fix="Run 'git submodule update --init --recursive'",
210
+ metadata={"issue_type": "uninitialized_submodule", "submodule_path": sub_rel_path},
211
+ ))
212
+ except Exception:
213
+ pass
214
+ return issues
215
+
216
+ @classmethod
217
+ def heal_issue(cls, issue: DiagnosticIssue, dry_run: bool = False) -> HealAction:
218
+ """Autonomously heal Git repository issues."""
219
+ itype = issue.metadata.get("issue_type")
220
+ file_path = issue.file_path
221
+
222
+ if itype == "stale_git_lock" and file_path:
223
+ p = Path(file_path)
224
+ if dry_run:
225
+ return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would delete stale git lock: {p.name}")
226
+ if p.is_file():
227
+ try:
228
+ p.unlink()
229
+ return HealAction(issue=issue, success=True, details=f"Removed stale Git lock file: {p.name}")
230
+ except Exception as e:
231
+ return HealAction(issue=issue, success=False, details=f"Failed to remove lock: {e}")
232
+
233
+ if itype == "missing_gitattributes" and file_path:
234
+ p = Path(file_path)
235
+ if dry_run:
236
+ return HealAction(issue=issue, success=True, details="[Dry-Run] Would create standardized .gitattributes")
237
+
238
+ gitattrs = (
239
+ "# Auto normalize text files to LF on checkout\n"
240
+ "* text=auto eol=lf\n\n"
241
+ "# Python and config files\n"
242
+ "*.py text eol=lf\n"
243
+ "*.json text eol=lf\n"
244
+ "*.yaml text eol=lf\n"
245
+ "*.yml text eol=lf\n"
246
+ "*.toml text eol=lf\n"
247
+ "*.md text eol=lf\n\n"
248
+ "# Binary files\n"
249
+ "*.pyd binary\n"
250
+ "*.so binary\n"
251
+ "*.dll binary\n"
252
+ "*.exe binary\n"
253
+ "*.whl binary\n"
254
+ )
255
+ p.write_text(gitattrs, encoding="utf-8")
256
+ return HealAction(issue=issue, success=True, details="Generated standardized .gitattributes with universal LF normalization")
257
+
258
+ if itype == "detached_head":
259
+ root = Path(file_path).parent if file_path and file_path.endswith(".git") else Path(".")
260
+ branch_name = f"rescue-detached-head-{int(time.time())}"
261
+ if dry_run:
262
+ return HealAction(issue=issue, success=True, details=f"[Dry-Run] Would create safety rescue branch '{branch_name}'")
263
+ try:
264
+ subprocess.run(["git", "branch", branch_name], cwd=str(root), check=True, capture_output=True)
265
+ return HealAction(issue=issue, success=True, details=f"Created safety rescue branch '{branch_name}' from detached HEAD")
266
+ except Exception as e:
267
+ return HealAction(issue=issue, success=False, details=f"Failed to create rescue branch: {e}")
268
+
269
+ if itype == "uninitialized_submodule":
270
+ root = Path(file_path).parent
271
+ if dry_run:
272
+ return HealAction(issue=issue, success=True, details="[Dry-Run] Would run git submodule update --init --recursive")
273
+ try:
274
+ subprocess.run(["git", "submodule", "update", "--init", "--recursive"], cwd=str(root), check=True, capture_output=True)
275
+ return HealAction(issue=issue, success=True, details="Synchronized and initialized Git submodules")
276
+ except Exception as e:
277
+ return HealAction(issue=issue, success=False, details=f"Submodule sync failed: {e}")
278
+
279
+ return HealAction(issue=issue, success=False, details=f"No automated repair for issue type '{itype}'")
280
+