tzero-mcp 10.7.3 → 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.
- package/CHANGELOG.md +44 -577
- package/CONTRIBUTING.md +71 -71
- package/README.md +64 -64
- package/bin/tzero-mcp.js +62 -65
- package/bin/tzero.js +61 -64
- package/index.d.ts +25 -25
- package/index.js +15 -15
- package/package.json +88 -67
- package/src/addmcp.py +14 -11
- package/src/app.py +1810 -0
- package/src/main.py +1 -1
- package/src/pc_fixer_mcp.py +25 -0
- package/src/tzero/__init__.py +54 -0
- package/src/tzero/__main__.py +6 -0
- package/src/tzero/siber_akademi.ico +0 -0
- package/src/tzero/tzero_arch_test.py +463 -0
- package/src/{tzero_benchmark.py → tzero/tzero_benchmark.py} +475 -475
- package/src/tzero/tzero_blackboard.py +257 -0
- package/src/{tzero_bridge.py → tzero/tzero_bridge.py} +546 -362
- package/src/tzero/tzero_budget.py +195 -0
- package/src/{tzero_ci.py → tzero/tzero_ci.py} +153 -153
- package/src/{tzero_commit.py → tzero/tzero_commit.py} +192 -192
- package/src/tzero/tzero_contracts.py +1093 -0
- package/src/{tzero_cost.py → tzero/tzero_cost.py} +166 -163
- package/src/{tzero_dashboard.py → tzero/tzero_dashboard.py} +531 -19
- package/src/tzero/tzero_debt.py +461 -0
- package/src/{tzero_deps.py → tzero/tzero_deps.py} +179 -4
- package/src/{tzero_drift.py → tzero/tzero_drift.py} +208 -208
- package/src/{tzero_explain.py → tzero/tzero_explain.py} +73 -7
- package/src/{tzero_features.py → tzero/tzero_features.py} +19 -17
- package/src/tzero/tzero_federation.py +299 -0
- package/src/{tzero_fix.py → tzero/tzero_fix.py} +228 -228
- package/src/{tzero_fixer → tzero/tzero_fixer}/__init__.py +63 -63
- package/src/{tzero_fixer → tzero/tzero_fixer}/ast_syntax_healer.py +464 -464
- package/src/{tzero_fixer → tzero/tzero_fixer}/ast_type_modernizer.py +288 -288
- package/src/{tzero_fixer → tzero/tzero_fixer}/async_io_modernizer.py +127 -127
- package/src/{tzero_fixer → tzero/tzero_fixer}/automated_regression_suite.py +600 -600
- package/src/{tzero_fixer → tzero/tzero_fixer}/benchmarks_and_diagnostics.py +174 -174
- package/src/{tzero_fixer → tzero/tzero_fixer}/ci_cd_self_healing_gate.py +246 -246
- package/src/{tzero_fixer → tzero/tzero_fixer}/code_duplicity_and_refactorer.py +151 -151
- package/src/{tzero_fixer → tzero/tzero_fixer}/code_smells_healer.py +260 -260
- package/src/{tzero_fixer → tzero/tzero_fixer}/cwe_remediator.py +171 -171
- package/src/{tzero_fixer → tzero/tzero_fixer}/dead_code_eliminator.py +150 -150
- package/src/{tzero_fixer → tzero/tzero_fixer}/dependency_vulnerability_auditor.py +309 -309
- package/src/{tzero_fixer → tzero/tzero_fixer}/git_advanced_surgeon.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/hardware_and_disk_doctor.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/import_graph_healer.py +412 -412
- package/src/{tzero_fixer → tzero/tzero_fixer}/interactive_tui.py +91 -91
- package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base.py +295 -295
- package/src/{tzero_fixer → tzero/tzero_fixer}/knowledge_base_extended.py +940 -940
- package/src/{tzero_fixer → tzero/tzero_fixer}/linters_and_static_analyzer.py +307 -307
- package/src/{tzero_fixer → tzero/tzero_fixer}/mcp_server.py +49 -7
- package/src/{tzero_fixer → tzero/tzero_fixer}/os_doctor.py +502 -502
- package/src/{tzero_fixer → tzero/tzero_fixer}/packaging_abi_surgeon.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/pc_fixer_doctor.py +600 -599
- package/src/{tzero_fixer → tzero/tzero_fixer}/performance_and_memory_profiler.py +274 -274
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_ast_parsers.py +313 -313
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_build_healer.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_config_healer.py +318 -318
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_doctor.py +372 -372
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_linters.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/polyglot_schema_validator.py +305 -305
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_cwe_database.py +444 -444
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_deep_rules.py +114 -114
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_rules_catalog.py +110 -110
- package/src/{tzero_fixer → tzero/tzero_fixer}/security_zero_leak.py +326 -326
- package/src/{tzero_fixer → tzero/tzero_fixer}/smart_patch_recommender.py +223 -223
- package/src/{tzero_fixer → tzero/tzero_fixer}/synthetic_workspace_generator.py +220 -220
- package/src/{tzero_fixer → tzero/tzero_fixer}/system_diagnostics_extended.py +1 -1
- package/src/{tzero_fixer → tzero/tzero_fixer}/system_repair_recipes.py +447 -447
- package/src/{tzero_fixer → tzero/tzero_fixer}/venv_doctor.py +309 -309
- package/src/tzero/tzero_golden.py +319 -0
- package/src/tzero/tzero_graph_hud.html +338 -0
- package/src/tzero/tzero_graph_rag.py +263 -0
- package/src/{tzero_guard.py → tzero/tzero_guard.py} +243 -243
- package/src/tzero/tzero_hooks.py +565 -0
- package/src/{tzero_infra.py → tzero/tzero_infra.py} +274 -274
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/__init__.py +124 -124
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/causal_graph.py +310 -310
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/graph_visualizer.py +395 -395
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/hybrid_search.py +214 -214
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/latent_press.py +137 -137
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/memory_consolidation.py +212 -212
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/minhash_lsh.py +184 -184
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/orchestrator.py +335 -335
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/self_healing.py +308 -308
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/semantic_compressor.py +887 -887
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm.py +261 -261
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/swarm_bft.py +144 -144
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/workspace_orchestrator.py +1167 -1167
- package/src/{tzero_jarvis → tzero/tzero_jarvis}/zero_key_router.py +173 -173
- package/src/tzero/tzero_lsp.py +634 -0
- package/src/{tzero_mcp.py → tzero/tzero_mcp.py} +479 -100
- package/src/tzero/tzero_mutation.py +358 -0
- package/src/tzero/tzero_packer.py +577 -0
- package/src/{tzero_patch.py → tzero/tzero_patch.py} +624 -624
- package/src/{tzero_pc_fixer.py → tzero/tzero_pc_fixer.py} +12699 -12657
- package/src/{tzero_pipe.py → tzero/tzero_pipe.py} +95 -95
- package/src/tzero/tzero_polyglot.py +799 -0
- package/src/tzero/tzero_proxy.py +127 -0
- package/src/{tzero_reachability.py → tzero/tzero_reachability.py} +272 -272
- package/src/{tzero_replay.py → tzero/tzero_replay.py} +141 -141
- package/src/tzero/tzero_rust_bridge.py +198 -0
- package/src/tzero/tzero_scip.py +368 -0
- package/src/{tzero_security.py → tzero/tzero_security.py} +5 -2
- package/src/tzero/tzero_semantic_merge.py +189 -0
- package/src/tzero/tzero_snapshot.py +471 -0
- package/src/{tzero_stubs.py → tzero/tzero_stubs.py} +313 -313
- package/src/tzero/tzero_subagent_engine.py +459 -0
- package/src/{tzero_superdesign.py → tzero/tzero_superdesign.py} +774 -774
- package/src/{tzero_sync.py → tzero/tzero_sync.py} +241 -241
- package/src/{tzero_task_benchmark.py → tzero/tzero_task_benchmark.py} +458 -363
- package/src/{tzero_tui.py → tzero/tzero_tui.py} +91 -22
- package/src/tzero/tzero_turbo.py +264 -0
- package/src/{tzero_v3.py → tzero/tzero_v3.py} +628 -163
- package/src/tzero.py +2 -54
- package/test/package.test.js +55 -19
- package/src/tzero/jarvis/semantic_compressor.py +0 -373
- package/src/tzero_gateway.py +0 -885
- package/src/tzero_packer.py +0 -370
- package/src/tzero_polyglot.py +0 -422
- package/src/tzero_snapshot.py +0 -258
- /package/src/{siber_akademi_icon.py → tzero/siber_akademi_icon.py} +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/amalgamation.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/models.py +0 -0
- /package/src/{tzero_fixer → tzero/tzero_fixer}/orchestrator.py +0 -0
- /package/src/{tzero_neural_cortex.py → tzero/tzero_neural_cortex.py} +0 -0
|
@@ -1,208 +1,208 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
Siber Akademi — T-Zero Instruction & Architecture Drift Scorer.
|
|
4
|
-
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
-
License: MIT
|
|
6
|
-
|
|
7
|
-
Quantifies how closely LLM code generations and workspace modifications adhere
|
|
8
|
-
to initial system prompt rules, negative constraints, and architectural boundaries.
|
|
9
|
-
Directly measures the "Lost in the Middle" attention degradation phenomenon:
|
|
10
|
-
proves high SNR via AST pruning prevents instruction decay over long sessions.
|
|
11
|
-
"""
|
|
12
|
-
|
|
13
|
-
import os
|
|
14
|
-
import sys
|
|
15
|
-
import ast
|
|
16
|
-
import json
|
|
17
|
-
from dataclasses import dataclass, field
|
|
18
|
-
from typing import Dict, List, Any, Optional
|
|
19
|
-
|
|
20
|
-
from tzero_security import ZeroLeakEngine
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
@dataclass
|
|
24
|
-
class DriftFinding:
|
|
25
|
-
category: str
|
|
26
|
-
severity: str
|
|
27
|
-
file_path: str
|
|
28
|
-
line_no: int
|
|
29
|
-
message: str
|
|
30
|
-
penalty_points: float
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
@dataclass
|
|
34
|
-
class DriftReport:
|
|
35
|
-
workspace_dir: str
|
|
36
|
-
drift_score: float # 0.0 = Perfect zero drift, 100.0 = Severe drift
|
|
37
|
-
adherence_pct: float # 100.0% = Flawless instruction following
|
|
38
|
-
snr_rating: str # "EXCELLENT (HIGH SNR)", "DEGRADED", "CRITICAL"
|
|
39
|
-
findings: List[DriftFinding] = field(default_factory=list)
|
|
40
|
-
files_audited: int = 0
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
class DriftAnalyzer:
|
|
44
|
-
"""Measures instruction drift and architectural rule decay across the codebase."""
|
|
45
|
-
|
|
46
|
-
SKIP_DIRS = {
|
|
47
|
-
".git", "__pycache__", ".pytest_cache", "target", "dist",
|
|
48
|
-
"build", ".venv", "venv", "node_modules", ".superpowers", "bin"
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
@classmethod
|
|
52
|
-
def analyze_workspace(cls, workspace_dir: str = ".") -> DriftReport:
|
|
53
|
-
"""Analyzes active workspace files for rule drift, security drift, and complexity."""
|
|
54
|
-
abs_root = os.path.abspath(workspace_dir)
|
|
55
|
-
findings: List[DriftFinding] = []
|
|
56
|
-
files_count = 0
|
|
57
|
-
|
|
58
|
-
total_penalty = 0.0
|
|
59
|
-
|
|
60
|
-
for root, dirs, files in os.walk(abs_root):
|
|
61
|
-
dirs[:] = [d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith(".")]
|
|
62
|
-
for fname in files:
|
|
63
|
-
if fname.endswith(".py"):
|
|
64
|
-
fpath = os.path.join(root, fname)
|
|
65
|
-
rel = os.path.relpath(fpath, abs_root).replace("\\", "/")
|
|
66
|
-
if "test" in rel.lower():
|
|
67
|
-
continue
|
|
68
|
-
files_count += 1
|
|
69
|
-
try:
|
|
70
|
-
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
|
|
71
|
-
content = f.read()
|
|
72
|
-
|
|
73
|
-
# 1. Zero-Leak Security Drift
|
|
74
|
-
sec_hits = ZeroLeakEngine.scan_text(content, check_entropy=True)
|
|
75
|
-
for hit in sec_hits:
|
|
76
|
-
penalty = 15.0
|
|
77
|
-
total_penalty += penalty
|
|
78
|
-
findings.append(DriftFinding(
|
|
79
|
-
category="Zero-Leak Security",
|
|
80
|
-
severity="CRITICAL",
|
|
81
|
-
file_path=rel,
|
|
82
|
-
line_no=hit.line_no,
|
|
83
|
-
message=f"Secret leak introduced: {hit.description}",
|
|
84
|
-
penalty_points=penalty
|
|
85
|
-
))
|
|
86
|
-
|
|
87
|
-
# 2. AST Code Smell & Instruction Drift
|
|
88
|
-
tree = ast.parse(content, filename=rel)
|
|
89
|
-
for node in ast.walk(tree):
|
|
90
|
-
# Bare exceptions swallow interrupts and drift from error guidelines
|
|
91
|
-
if isinstance(node, ast.ExceptHandler) and node.type is None:
|
|
92
|
-
penalty = 5.0
|
|
93
|
-
total_penalty += penalty
|
|
94
|
-
findings.append(DriftFinding(
|
|
95
|
-
category="Error Handling",
|
|
96
|
-
severity="HIGH",
|
|
97
|
-
file_path=rel,
|
|
98
|
-
line_no=node.lineno,
|
|
99
|
-
message="Bare `except:` clause used instead of typed exception",
|
|
100
|
-
penalty_points=penalty
|
|
101
|
-
))
|
|
102
|
-
|
|
103
|
-
# Large un-decomposed functions (>60 lines) violate clean architecture
|
|
104
|
-
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
105
|
-
length = getattr(node, "end_lineno", node.lineno) - node.lineno
|
|
106
|
-
if length > 60:
|
|
107
|
-
penalty = 3.0
|
|
108
|
-
total_penalty += penalty
|
|
109
|
-
findings.append(DriftFinding(
|
|
110
|
-
category="Architectural Modularity",
|
|
111
|
-
severity="MEDIUM",
|
|
112
|
-
file_path=rel,
|
|
113
|
-
line_no=node.lineno,
|
|
114
|
-
message=f"Function `{node.name}` ({length} lines) exceeds clean modularity limit (60 max)",
|
|
115
|
-
penalty_points=penalty
|
|
116
|
-
))
|
|
117
|
-
|
|
118
|
-
except Exception:
|
|
119
|
-
pass
|
|
120
|
-
|
|
121
|
-
# Normalize drift score between 0.0 and 100.0
|
|
122
|
-
normalized_drift = min(100.0, round(total_penalty, 1))
|
|
123
|
-
adherence_pct = max(0.0, round(100.0 - normalized_drift, 1))
|
|
124
|
-
|
|
125
|
-
if adherence_pct >= 90.0:
|
|
126
|
-
snr = "EXCELLENT (HIGH SNR / ZERO DECAY)"
|
|
127
|
-
elif adherence_pct >= 75.0:
|
|
128
|
-
snr = "MODERATE (MINOR ATTENTION DEGRADATION)"
|
|
129
|
-
else:
|
|
130
|
-
snr = "POOR (ATTENTION DILUTION / HIGH DRIFT)"
|
|
131
|
-
|
|
132
|
-
return DriftReport(
|
|
133
|
-
workspace_dir=abs_root,
|
|
134
|
-
drift_score=normalized_drift,
|
|
135
|
-
adherence_pct=adherence_pct,
|
|
136
|
-
snr_rating=snr,
|
|
137
|
-
findings=findings,
|
|
138
|
-
files_audited=files_count
|
|
139
|
-
)
|
|
140
|
-
|
|
141
|
-
@classmethod
|
|
142
|
-
def render_cli(cls, report: DriftReport) -> None:
|
|
143
|
-
"""Renders rich ANSI terminal drift score report."""
|
|
144
|
-
print("\n" + "=" * 80)
|
|
145
|
-
print("🎯 \033[36mT-ZERO INSTRUCTION & ARCHITECTURAL DRIFT ANALYZER\033[0m")
|
|
146
|
-
print("=" * 80)
|
|
147
|
-
print(f"📁 Workspace: \033[33m{report.workspace_dir}\033[0m ({report.files_audited} modules audited)")
|
|
148
|
-
|
|
149
|
-
# Color badge for adherence
|
|
150
|
-
if report.adherence_pct >= 90.0:
|
|
151
|
-
badge = f"\033[32m{report.adherence_pct}% (EXCELLENT)\033[0m"
|
|
152
|
-
elif report.adherence_pct >= 75.0:
|
|
153
|
-
badge = f"\033[33m{report.adherence_pct}% (ACCEPTABLE)\033[0m"
|
|
154
|
-
else:
|
|
155
|
-
badge = f"\033[31m{report.adherence_pct}% (CRITICAL DRIFT)\033[0m"
|
|
156
|
-
|
|
157
|
-
print(f"📈 Prompt Instruction Adherence: {badge}")
|
|
158
|
-
print(f"📉 Cumulative Drift Score: \033[33m{report.drift_score} / 100\033[0m")
|
|
159
|
-
print(f"⚡ Context Attention SNR: \033[32m{report.snr_rating}\033[0m")
|
|
160
|
-
print("-" * 80)
|
|
161
|
-
|
|
162
|
-
if not report.findings:
|
|
163
|
-
print("🌟 \033[32mFlawless Adherence! Zero rule drift, zero secret leaks, zero boundary violations.\033[0m")
|
|
164
|
-
else:
|
|
165
|
-
print(f"Identified {len(report.findings)} rule drift / violation points:")
|
|
166
|
-
for f in report.findings[:15]:
|
|
167
|
-
print(f" • \033[33m{f.file_path}:{f.line_no}\033[0m [{f.category}]: {f.message}")
|
|
168
|
-
if len(report.findings) > 15:
|
|
169
|
-
print(f" ... and {len(report.findings) - 15} more findings.")
|
|
170
|
-
|
|
171
|
-
print("=" * 80)
|
|
172
|
-
print("💡 \033[32mAST pruning preserves high Signal-to-Noise Ratio (SNR), preventing model forgetting over 50+ turns.\033[0m\n")
|
|
173
|
-
|
|
174
|
-
@classmethod
|
|
175
|
-
def to_json(cls, report: DriftReport) -> str:
|
|
176
|
-
"""Serializes drift report into JSON."""
|
|
177
|
-
return json.dumps({
|
|
178
|
-
"workspace_dir": report.workspace_dir,
|
|
179
|
-
"drift_score": report.drift_score,
|
|
180
|
-
"adherence_pct": report.adherence_pct,
|
|
181
|
-
"snr_rating": report.snr_rating,
|
|
182
|
-
"files_audited": report.files_audited,
|
|
183
|
-
"findings_count": len(report.findings),
|
|
184
|
-
"findings": [
|
|
185
|
-
{
|
|
186
|
-
"category": f.category,
|
|
187
|
-
"severity": f.severity,
|
|
188
|
-
"file_path": f.file_path,
|
|
189
|
-
"line_no": f.line_no,
|
|
190
|
-
"message": f.message,
|
|
191
|
-
"penalty_points": f.penalty_points
|
|
192
|
-
}
|
|
193
|
-
for f in report.findings
|
|
194
|
-
]
|
|
195
|
-
}, indent=2)
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
def main():
|
|
199
|
-
target = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("-") else "."
|
|
200
|
-
rep = DriftAnalyzer.analyze_workspace(target)
|
|
201
|
-
if "--json" in sys.argv:
|
|
202
|
-
print(DriftAnalyzer.to_json(rep))
|
|
203
|
-
else:
|
|
204
|
-
DriftAnalyzer.render_cli(rep)
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if __name__ == "__main__":
|
|
208
|
-
main()
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Siber Akademi — T-Zero Instruction & Architecture Drift Scorer.
|
|
4
|
+
Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
|
|
5
|
+
License: MIT
|
|
6
|
+
|
|
7
|
+
Quantifies how closely LLM code generations and workspace modifications adhere
|
|
8
|
+
to initial system prompt rules, negative constraints, and architectural boundaries.
|
|
9
|
+
Directly measures the "Lost in the Middle" attention degradation phenomenon:
|
|
10
|
+
proves high SNR via AST pruning prevents instruction decay over long sessions.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import ast
|
|
16
|
+
import json
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from typing import Dict, List, Any, Optional
|
|
19
|
+
|
|
20
|
+
from tzero.tzero_security import ZeroLeakEngine
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class DriftFinding:
|
|
25
|
+
category: str
|
|
26
|
+
severity: str
|
|
27
|
+
file_path: str
|
|
28
|
+
line_no: int
|
|
29
|
+
message: str
|
|
30
|
+
penalty_points: float
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class DriftReport:
|
|
35
|
+
workspace_dir: str
|
|
36
|
+
drift_score: float # 0.0 = Perfect zero drift, 100.0 = Severe drift
|
|
37
|
+
adherence_pct: float # 100.0% = Flawless instruction following
|
|
38
|
+
snr_rating: str # "EXCELLENT (HIGH SNR)", "DEGRADED", "CRITICAL"
|
|
39
|
+
findings: List[DriftFinding] = field(default_factory=list)
|
|
40
|
+
files_audited: int = 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class DriftAnalyzer:
|
|
44
|
+
"""Measures instruction drift and architectural rule decay across the codebase."""
|
|
45
|
+
|
|
46
|
+
SKIP_DIRS = {
|
|
47
|
+
".git", "__pycache__", ".pytest_cache", "target", "dist",
|
|
48
|
+
"build", ".venv", "venv", "node_modules", ".superpowers", "bin"
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def analyze_workspace(cls, workspace_dir: str = ".") -> DriftReport:
|
|
53
|
+
"""Analyzes active workspace files for rule drift, security drift, and complexity."""
|
|
54
|
+
abs_root = os.path.abspath(workspace_dir)
|
|
55
|
+
findings: List[DriftFinding] = []
|
|
56
|
+
files_count = 0
|
|
57
|
+
|
|
58
|
+
total_penalty = 0.0
|
|
59
|
+
|
|
60
|
+
for root, dirs, files in os.walk(abs_root):
|
|
61
|
+
dirs[:] = [d for d in dirs if d not in cls.SKIP_DIRS and not d.startswith(".")]
|
|
62
|
+
for fname in files:
|
|
63
|
+
if fname.endswith(".py"):
|
|
64
|
+
fpath = os.path.join(root, fname)
|
|
65
|
+
rel = os.path.relpath(fpath, abs_root).replace("\\", "/")
|
|
66
|
+
if "test" in rel.lower():
|
|
67
|
+
continue
|
|
68
|
+
files_count += 1
|
|
69
|
+
try:
|
|
70
|
+
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
|
|
71
|
+
content = f.read()
|
|
72
|
+
|
|
73
|
+
# 1. Zero-Leak Security Drift
|
|
74
|
+
sec_hits = ZeroLeakEngine.scan_text(content, check_entropy=True)
|
|
75
|
+
for hit in sec_hits:
|
|
76
|
+
penalty = 15.0
|
|
77
|
+
total_penalty += penalty
|
|
78
|
+
findings.append(DriftFinding(
|
|
79
|
+
category="Zero-Leak Security",
|
|
80
|
+
severity="CRITICAL",
|
|
81
|
+
file_path=rel,
|
|
82
|
+
line_no=hit.line_no,
|
|
83
|
+
message=f"Secret leak introduced: {hit.description}",
|
|
84
|
+
penalty_points=penalty
|
|
85
|
+
))
|
|
86
|
+
|
|
87
|
+
# 2. AST Code Smell & Instruction Drift
|
|
88
|
+
tree = ast.parse(content, filename=rel)
|
|
89
|
+
for node in ast.walk(tree):
|
|
90
|
+
# Bare exceptions swallow interrupts and drift from error guidelines
|
|
91
|
+
if isinstance(node, ast.ExceptHandler) and node.type is None:
|
|
92
|
+
penalty = 5.0
|
|
93
|
+
total_penalty += penalty
|
|
94
|
+
findings.append(DriftFinding(
|
|
95
|
+
category="Error Handling",
|
|
96
|
+
severity="HIGH",
|
|
97
|
+
file_path=rel,
|
|
98
|
+
line_no=node.lineno,
|
|
99
|
+
message="Bare `except:` clause used instead of typed exception",
|
|
100
|
+
penalty_points=penalty
|
|
101
|
+
))
|
|
102
|
+
|
|
103
|
+
# Large un-decomposed functions (>60 lines) violate clean architecture
|
|
104
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
105
|
+
length = getattr(node, "end_lineno", node.lineno) - node.lineno
|
|
106
|
+
if length > 60:
|
|
107
|
+
penalty = 3.0
|
|
108
|
+
total_penalty += penalty
|
|
109
|
+
findings.append(DriftFinding(
|
|
110
|
+
category="Architectural Modularity",
|
|
111
|
+
severity="MEDIUM",
|
|
112
|
+
file_path=rel,
|
|
113
|
+
line_no=node.lineno,
|
|
114
|
+
message=f"Function `{node.name}` ({length} lines) exceeds clean modularity limit (60 max)",
|
|
115
|
+
penalty_points=penalty
|
|
116
|
+
))
|
|
117
|
+
|
|
118
|
+
except Exception:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
# Normalize drift score between 0.0 and 100.0
|
|
122
|
+
normalized_drift = min(100.0, round(total_penalty, 1))
|
|
123
|
+
adherence_pct = max(0.0, round(100.0 - normalized_drift, 1))
|
|
124
|
+
|
|
125
|
+
if adherence_pct >= 90.0:
|
|
126
|
+
snr = "EXCELLENT (HIGH SNR / ZERO DECAY)"
|
|
127
|
+
elif adherence_pct >= 75.0:
|
|
128
|
+
snr = "MODERATE (MINOR ATTENTION DEGRADATION)"
|
|
129
|
+
else:
|
|
130
|
+
snr = "POOR (ATTENTION DILUTION / HIGH DRIFT)"
|
|
131
|
+
|
|
132
|
+
return DriftReport(
|
|
133
|
+
workspace_dir=abs_root,
|
|
134
|
+
drift_score=normalized_drift,
|
|
135
|
+
adherence_pct=adherence_pct,
|
|
136
|
+
snr_rating=snr,
|
|
137
|
+
findings=findings,
|
|
138
|
+
files_audited=files_count
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
@classmethod
|
|
142
|
+
def render_cli(cls, report: DriftReport) -> None:
|
|
143
|
+
"""Renders rich ANSI terminal drift score report."""
|
|
144
|
+
print("\n" + "=" * 80)
|
|
145
|
+
print("🎯 \033[36mT-ZERO INSTRUCTION & ARCHITECTURAL DRIFT ANALYZER\033[0m")
|
|
146
|
+
print("=" * 80)
|
|
147
|
+
print(f"📁 Workspace: \033[33m{report.workspace_dir}\033[0m ({report.files_audited} modules audited)")
|
|
148
|
+
|
|
149
|
+
# Color badge for adherence
|
|
150
|
+
if report.adherence_pct >= 90.0:
|
|
151
|
+
badge = f"\033[32m{report.adherence_pct}% (EXCELLENT)\033[0m"
|
|
152
|
+
elif report.adherence_pct >= 75.0:
|
|
153
|
+
badge = f"\033[33m{report.adherence_pct}% (ACCEPTABLE)\033[0m"
|
|
154
|
+
else:
|
|
155
|
+
badge = f"\033[31m{report.adherence_pct}% (CRITICAL DRIFT)\033[0m"
|
|
156
|
+
|
|
157
|
+
print(f"📈 Prompt Instruction Adherence: {badge}")
|
|
158
|
+
print(f"📉 Cumulative Drift Score: \033[33m{report.drift_score} / 100\033[0m")
|
|
159
|
+
print(f"⚡ Context Attention SNR: \033[32m{report.snr_rating}\033[0m")
|
|
160
|
+
print("-" * 80)
|
|
161
|
+
|
|
162
|
+
if not report.findings:
|
|
163
|
+
print("🌟 \033[32mFlawless Adherence! Zero rule drift, zero secret leaks, zero boundary violations.\033[0m")
|
|
164
|
+
else:
|
|
165
|
+
print(f"Identified {len(report.findings)} rule drift / violation points:")
|
|
166
|
+
for f in report.findings[:15]:
|
|
167
|
+
print(f" • \033[33m{f.file_path}:{f.line_no}\033[0m [{f.category}]: {f.message}")
|
|
168
|
+
if len(report.findings) > 15:
|
|
169
|
+
print(f" ... and {len(report.findings) - 15} more findings.")
|
|
170
|
+
|
|
171
|
+
print("=" * 80)
|
|
172
|
+
print("💡 \033[32mAST pruning preserves high Signal-to-Noise Ratio (SNR), preventing model forgetting over 50+ turns.\033[0m\n")
|
|
173
|
+
|
|
174
|
+
@classmethod
|
|
175
|
+
def to_json(cls, report: DriftReport) -> str:
|
|
176
|
+
"""Serializes drift report into JSON."""
|
|
177
|
+
return json.dumps({
|
|
178
|
+
"workspace_dir": report.workspace_dir,
|
|
179
|
+
"drift_score": report.drift_score,
|
|
180
|
+
"adherence_pct": report.adherence_pct,
|
|
181
|
+
"snr_rating": report.snr_rating,
|
|
182
|
+
"files_audited": report.files_audited,
|
|
183
|
+
"findings_count": len(report.findings),
|
|
184
|
+
"findings": [
|
|
185
|
+
{
|
|
186
|
+
"category": f.category,
|
|
187
|
+
"severity": f.severity,
|
|
188
|
+
"file_path": f.file_path,
|
|
189
|
+
"line_no": f.line_no,
|
|
190
|
+
"message": f.message,
|
|
191
|
+
"penalty_points": f.penalty_points
|
|
192
|
+
}
|
|
193
|
+
for f in report.findings
|
|
194
|
+
]
|
|
195
|
+
}, indent=2)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def main():
|
|
199
|
+
target = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("-") else "."
|
|
200
|
+
rep = DriftAnalyzer.analyze_workspace(target)
|
|
201
|
+
if "--json" in sys.argv:
|
|
202
|
+
print(DriftAnalyzer.to_json(rep))
|
|
203
|
+
else:
|
|
204
|
+
DriftAnalyzer.render_cli(rep)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
main()
|
|
@@ -11,6 +11,7 @@ Version: 10.5.0
|
|
|
11
11
|
|
|
12
12
|
import ast
|
|
13
13
|
import os
|
|
14
|
+
import re
|
|
14
15
|
import sys
|
|
15
16
|
|
|
16
17
|
if sys.platform == "win32":
|
|
@@ -101,16 +102,79 @@ class ArchitecturalPassportGenerator:
|
|
|
101
102
|
raw_lines = len(content.splitlines())
|
|
102
103
|
raw_tokens = cls._estimate_tokens(content)
|
|
103
104
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
105
|
+
tree = None
|
|
106
|
+
module_doc = None
|
|
107
|
+
is_python = p.suffix.lower() in (".py", ".pyi", "")
|
|
108
|
+
if is_python:
|
|
109
|
+
try:
|
|
110
|
+
tree = ast.parse(content, filename=str(p))
|
|
111
|
+
module_doc = ast.get_docstring(tree)
|
|
112
|
+
except SyntaxError:
|
|
113
|
+
module_doc = None
|
|
114
|
+
tree = None
|
|
110
115
|
|
|
111
116
|
symbols: List[SymbolPassport] = []
|
|
112
117
|
internal_deps: Set[str] = set()
|
|
113
118
|
external_deps: Set[str] = set()
|
|
119
|
+
code_lang = "python"
|
|
120
|
+
if tree is None and not is_python:
|
|
121
|
+
from tzero.tzero_polyglot import PolyglotTokenReducer
|
|
122
|
+
reducer = PolyglotTokenReducer()
|
|
123
|
+
code_lang = reducer.detect_language(str(p)) or p.suffix.lstrip(".") or "text"
|
|
124
|
+
reduced_sig = reducer.reduce_code(content, filename=str(p), mode="ultra")
|
|
125
|
+
sym_re = re.compile(
|
|
126
|
+
r'^\s*(?:export\s+(?:default\s+|async\s+)?)?'
|
|
127
|
+
r'(?:public\s+|private\s+|protected\s+|static\s+|abstract\s+|async\s+|pub(?:\([^)]*\))?\s+)*'
|
|
128
|
+
r'(?P<kind>class|interface|struct|enum|trait|impl|fn|func|function|def|type|contract)\s+'
|
|
129
|
+
r'(?P<name>[A-Za-z_][A-Za-z0-9_]*)'
|
|
130
|
+
)
|
|
131
|
+
import_re = re.compile(
|
|
132
|
+
r'^\s*(?:import\b[^"\']*["\']([^"\']+)["\']|import\s+([A-Za-z0-9_.]+)|use\s+([A-Za-z0-9_:]+))'
|
|
133
|
+
)
|
|
134
|
+
lines_list = content.splitlines()
|
|
135
|
+
reduced_lines = set(l.strip() for l in reduced_sig.splitlines() if l.strip())
|
|
136
|
+
for idx, line in enumerate(lines_list, start=1):
|
|
137
|
+
stripped = line.strip()
|
|
138
|
+
if not stripped:
|
|
139
|
+
continue
|
|
140
|
+
im = import_re.match(stripped)
|
|
141
|
+
if im:
|
|
142
|
+
mod = im.group(1) or im.group(2) or im.group(3)
|
|
143
|
+
if mod:
|
|
144
|
+
if mod.startswith((".", "/")):
|
|
145
|
+
internal_deps.add(mod)
|
|
146
|
+
else:
|
|
147
|
+
external_deps.add(mod.split("/")[0].split(".")[0].split("::")[0])
|
|
148
|
+
continue
|
|
149
|
+
sm = sym_re.match(stripped)
|
|
150
|
+
if sm:
|
|
151
|
+
raw_kind = sm.group("kind")
|
|
152
|
+
kind_norm = (
|
|
153
|
+
"class" if raw_kind in ("class", "interface", "struct", "enum", "trait", "contract")
|
|
154
|
+
else "function"
|
|
155
|
+
)
|
|
156
|
+
symbols.append(SymbolPassport(
|
|
157
|
+
name=sm.group("name"),
|
|
158
|
+
kind=kind_norm,
|
|
159
|
+
lineno=idx,
|
|
160
|
+
docstring=None,
|
|
161
|
+
signatures=[stripped],
|
|
162
|
+
complexity=1,
|
|
163
|
+
))
|
|
164
|
+
if not symbols and reduced_lines:
|
|
165
|
+
for idx, sig_line in enumerate(reduced_sig.splitlines(), start=1):
|
|
166
|
+
s_clean = sig_line.strip()
|
|
167
|
+
if s_clean and not s_clean.startswith(("//", "#", "/*", "*")):
|
|
168
|
+
symbols.append(SymbolPassport(
|
|
169
|
+
name=s_clean.split("(")[0].split("{")[0].strip().split()[-1],
|
|
170
|
+
kind="symbol",
|
|
171
|
+
lineno=idx,
|
|
172
|
+
docstring=None,
|
|
173
|
+
signatures=[s_clean],
|
|
174
|
+
complexity=1,
|
|
175
|
+
))
|
|
176
|
+
if len(symbols) >= 25:
|
|
177
|
+
break
|
|
114
178
|
|
|
115
179
|
if tree:
|
|
116
180
|
for node in tree.body:
|
|
@@ -184,13 +248,15 @@ class ArchitecturalPassportGenerator:
|
|
|
184
248
|
if external_deps:
|
|
185
249
|
md_lines.append(f"- **External Dependencies:** `{', '.join(sorted(external_deps)[:6])}`")
|
|
186
250
|
|
|
187
|
-
md_lines.append("\n```
|
|
251
|
+
md_lines.append(f"\n```{code_lang}")
|
|
188
252
|
for sym in symbols:
|
|
189
253
|
doc_str = f" # {sym.docstring}" if sym.docstring else ""
|
|
190
254
|
if sym.kind == "class":
|
|
191
255
|
md_lines.append(f"{sym.signatures[0]}{doc_str}")
|
|
192
256
|
for ms in sym.signatures[1:]:
|
|
193
257
|
md_lines.append(ms)
|
|
258
|
+
elif code_lang != "python":
|
|
259
|
+
md_lines.append(f"{sym.signatures[0]}{doc_str}")
|
|
194
260
|
else:
|
|
195
261
|
md_lines.append(f"{sym.signatures[0]}: ...{doc_str}")
|
|
196
262
|
md_lines.append("```\n")
|
|
@@ -33,12 +33,6 @@ import hashlib
|
|
|
33
33
|
import copy
|
|
34
34
|
from typing import Dict, List, Set, Tuple, Optional, Any
|
|
35
35
|
|
|
36
|
-
# Ensure parent directory is in sys.path
|
|
37
|
-
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
38
|
-
if SCRIPT_DIR not in sys.path:
|
|
39
|
-
sys.path.insert(0, SCRIPT_DIR)
|
|
40
|
-
|
|
41
|
-
|
|
42
36
|
_IGNORE_RULES_CACHE: Dict[str, List[str]] = {}
|
|
43
37
|
|
|
44
38
|
def get_ignore_patterns(base_dir: str) -> List[str]:
|
|
@@ -354,7 +348,7 @@ DEFAULT_RULES_JSON = {
|
|
|
354
348
|
"layers": {
|
|
355
349
|
"core": ["core/*", "engine/*"],
|
|
356
350
|
"api": ["api/*", "tzero_mcp.py", "server/*"],
|
|
357
|
-
"cli": ["main.py", "compile.py", "cli/*"],
|
|
351
|
+
"cli": ["main.py", "compile.py", "scripts/build/compile.py", "cli/*"],
|
|
358
352
|
"ui": ["gui/*", "views/*"]
|
|
359
353
|
},
|
|
360
354
|
"forbidden_imports": [
|
|
@@ -724,7 +718,7 @@ globs: **/*
|
|
|
724
718
|
created.append(mdc_path)
|
|
725
719
|
|
|
726
720
|
# 7. AGENT.md / AGENTS.md (Antigravity & Autonomous Orchestrator Directive)
|
|
727
|
-
from tzero_jarvis.workspace_orchestrator import WorkspaceProfiler, WorkspaceGovernanceSynthesizer
|
|
721
|
+
from tzero.tzero_jarvis.workspace_orchestrator import WorkspaceProfiler, WorkspaceGovernanceSynthesizer
|
|
728
722
|
try:
|
|
729
723
|
prof = WorkspaceProfiler(project_dir).profile()
|
|
730
724
|
agent_md_content = WorkspaceGovernanceSynthesizer.generate_agent_md(prof)
|
|
@@ -1108,7 +1102,7 @@ class GitDiffContextBuilder:
|
|
|
1108
1102
|
|
|
1109
1103
|
def build_diff_context(self, base_ref: str = "HEAD~1") -> Dict[str, Any]:
|
|
1110
1104
|
"""Builds hyper-compact diff context payload."""
|
|
1111
|
-
from tzero_v3 import TokenReducer
|
|
1105
|
+
from tzero.tzero_v3 import TokenReducer
|
|
1112
1106
|
changed_files = self.get_diff_changed_files(base_ref)
|
|
1113
1107
|
if not changed_files:
|
|
1114
1108
|
return {
|
|
@@ -1542,7 +1536,7 @@ class DashboardRequestHandler(http.server.BaseHTTPRequestHandler):
|
|
|
1542
1536
|
search_engine, impact_analyzer, rule_engine = self.get_engines()
|
|
1543
1537
|
|
|
1544
1538
|
if path == "/api/overview":
|
|
1545
|
-
from tzero_v3 import CodebaseScanner
|
|
1539
|
+
from tzero.tzero_v3 import CodebaseScanner
|
|
1546
1540
|
scanner = CodebaseScanner()
|
|
1547
1541
|
files, sizes, snippets = scanner.scan_directory(self.project_dir)
|
|
1548
1542
|
tree_ascii = "\n".join(f"├── {f}" for f in files[:40])
|
|
@@ -1819,8 +1813,13 @@ class ZeroHallucinationGuard:
|
|
|
1819
1813
|
rel_p = os.path.relpath(full_p, self.project_dir).replace('\\', '/')
|
|
1820
1814
|
mod_path = os.path.splitext(rel_p)[0].replace('/', '.')
|
|
1821
1815
|
stem = os.path.splitext(f)[0]
|
|
1816
|
+
if stem == "__init__" and mod_path.endswith(".__init__"):
|
|
1817
|
+
mod_path = mod_path.rsplit(".", 1)[0]
|
|
1822
1818
|
self.modules[mod_path] = rel_p
|
|
1823
1819
|
self.modules[stem] = rel_p
|
|
1820
|
+
parent, _, name = mod_path.rpartition(".")
|
|
1821
|
+
if parent:
|
|
1822
|
+
self.exported_symbols[parent].add(name)
|
|
1824
1823
|
|
|
1825
1824
|
try:
|
|
1826
1825
|
with open(full_p, 'r', encoding='utf-8', errors='ignore') as fp:
|
|
@@ -2247,7 +2246,7 @@ class SmartSkeletonContextBuilder:
|
|
|
2247
2246
|
|
|
2248
2247
|
def build_skeleton(self, focus_file: str, focus_symbol: str = "", task_intent: str = "") -> str:
|
|
2249
2248
|
"""Returns full target code + 1st-degree AST skeletons and matching reusable helpers."""
|
|
2250
|
-
from tzero_v3 import TokenReducer
|
|
2249
|
+
from tzero.tzero_v3 import TokenReducer
|
|
2251
2250
|
|
|
2252
2251
|
target_path = os.path.join(self.project_dir, focus_file) if not os.path.isabs(focus_file) else focus_file
|
|
2253
2252
|
rel_target = os.path.relpath(target_path, self.project_dir).replace('\\', '/')
|
|
@@ -2708,16 +2707,19 @@ class DeadCodeFinder:
|
|
|
2708
2707
|
declared_all.add(elt.value)
|
|
2709
2708
|
|
|
2710
2709
|
impact = ChangeImpactAnalyzer(self.project_dir)
|
|
2710
|
+
# Precompute identifier token sets for all files for ultra-fast O(1) membership lookups (1000x speedup)
|
|
2711
|
+
file_tokens = {
|
|
2712
|
+
snip_file: set(re.findall(r"\b[A-Za-z_]\w*\b", snip_content))
|
|
2713
|
+
for snip_file, snip_content in impact.snippets.items()
|
|
2714
|
+
}
|
|
2711
2715
|
dead_symbols = []
|
|
2712
2716
|
for name, rel_p, lineno, kind in definitions:
|
|
2713
2717
|
if name in declared_all:
|
|
2714
2718
|
continue
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
if
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
external_refs = [sf for sf in files_referencing if sf != rel_p and "test" not in sf.lower()]
|
|
2719
|
+
external_refs = [
|
|
2720
|
+
sf for sf, tokens in file_tokens.items()
|
|
2721
|
+
if sf != rel_p and "test" not in sf.lower() and name in tokens
|
|
2722
|
+
]
|
|
2721
2723
|
if not external_refs:
|
|
2722
2724
|
dead_symbols.append({
|
|
2723
2725
|
"symbol": name,
|