tzero-mcp 10.7.0 → 10.7.1

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 (96) hide show
  1. package/bin/tzero-mcp.js +9 -16
  2. package/bin/tzero.js +9 -16
  3. package/index.js +7 -2
  4. package/package.json +2 -1
  5. package/src/addmcp.py +1194 -0
  6. package/src/main.py +60 -0
  7. package/src/siber_akademi_icon.py +77 -0
  8. package/src/tzero/jarvis/semantic_compressor.py +373 -0
  9. package/src/tzero.py +58 -0
  10. package/src/tzero_benchmark.py +475 -0
  11. package/src/tzero_bridge.py +362 -0
  12. package/src/tzero_ci.py +153 -0
  13. package/src/tzero_commit.py +192 -0
  14. package/src/tzero_cost.py +163 -0
  15. package/src/tzero_dashboard.py +1448 -0
  16. package/src/tzero_deps.py +287 -0
  17. package/src/tzero_drift.py +208 -0
  18. package/src/tzero_explain.py +240 -0
  19. package/src/tzero_features.py +3022 -0
  20. package/src/tzero_fix.py +228 -0
  21. package/src/tzero_fixer/__init__.py +63 -0
  22. package/src/tzero_fixer/amalgamation.py +334 -0
  23. package/src/tzero_fixer/ast_syntax_healer.py +464 -0
  24. package/src/tzero_fixer/ast_type_modernizer.py +288 -0
  25. package/src/tzero_fixer/async_io_modernizer.py +127 -0
  26. package/src/tzero_fixer/automated_regression_suite.py +600 -0
  27. package/src/tzero_fixer/benchmarks_and_diagnostics.py +174 -0
  28. package/src/tzero_fixer/ci_cd_self_healing_gate.py +246 -0
  29. package/src/tzero_fixer/code_duplicity_and_refactorer.py +151 -0
  30. package/src/tzero_fixer/code_smells_healer.py +260 -0
  31. package/src/tzero_fixer/cwe_remediator.py +171 -0
  32. package/src/tzero_fixer/dead_code_eliminator.py +150 -0
  33. package/src/tzero_fixer/dependency_vulnerability_auditor.py +309 -0
  34. package/src/tzero_fixer/git_advanced_surgeon.py +280 -0
  35. package/src/tzero_fixer/hardware_and_disk_doctor.py +325 -0
  36. package/src/tzero_fixer/import_graph_healer.py +412 -0
  37. package/src/tzero_fixer/interactive_tui.py +91 -0
  38. package/src/tzero_fixer/knowledge_base.py +295 -0
  39. package/src/tzero_fixer/knowledge_base_extended.py +940 -0
  40. package/src/tzero_fixer/linters_and_static_analyzer.py +307 -0
  41. package/src/tzero_fixer/mcp_server.py +447 -0
  42. package/src/tzero_fixer/models.py +385 -0
  43. package/src/tzero_fixer/orchestrator.py +375 -0
  44. package/src/tzero_fixer/os_doctor.py +502 -0
  45. package/src/tzero_fixer/packaging_abi_surgeon.py +323 -0
  46. package/src/tzero_fixer/pc_fixer_doctor.py +599 -0
  47. package/src/tzero_fixer/performance_and_memory_profiler.py +274 -0
  48. package/src/tzero_fixer/polyglot_ast_parsers.py +313 -0
  49. package/src/tzero_fixer/polyglot_build_healer.py +364 -0
  50. package/src/tzero_fixer/polyglot_config_healer.py +318 -0
  51. package/src/tzero_fixer/polyglot_doctor.py +372 -0
  52. package/src/tzero_fixer/polyglot_linters.py +619 -0
  53. package/src/tzero_fixer/polyglot_schema_validator.py +305 -0
  54. package/src/tzero_fixer/security_cwe_database.py +444 -0
  55. package/src/tzero_fixer/security_deep_rules.py +114 -0
  56. package/src/tzero_fixer/security_rules_catalog.py +110 -0
  57. package/src/tzero_fixer/security_zero_leak.py +326 -0
  58. package/src/tzero_fixer/smart_patch_recommender.py +223 -0
  59. package/src/tzero_fixer/synthetic_workspace_generator.py +220 -0
  60. package/src/tzero_fixer/system_diagnostics_extended.py +493 -0
  61. package/src/tzero_fixer/system_repair_recipes.py +447 -0
  62. package/src/tzero_fixer/venv_doctor.py +309 -0
  63. package/src/tzero_gateway.py +885 -0
  64. package/src/tzero_guard.py +243 -0
  65. package/src/tzero_infra.py +274 -0
  66. package/src/tzero_jarvis/__init__.py +124 -0
  67. package/src/tzero_jarvis/causal_graph.py +310 -0
  68. package/src/tzero_jarvis/graph_visualizer.py +395 -0
  69. package/src/tzero_jarvis/hybrid_search.py +214 -0
  70. package/src/tzero_jarvis/latent_press.py +137 -0
  71. package/src/tzero_jarvis/memory_consolidation.py +212 -0
  72. package/src/tzero_jarvis/minhash_lsh.py +184 -0
  73. package/src/tzero_jarvis/orchestrator.py +335 -0
  74. package/src/tzero_jarvis/self_healing.py +308 -0
  75. package/src/tzero_jarvis/semantic_compressor.py +887 -0
  76. package/src/tzero_jarvis/swarm.py +261 -0
  77. package/src/tzero_jarvis/swarm_bft.py +144 -0
  78. package/src/tzero_jarvis/workspace_orchestrator.py +1167 -0
  79. package/src/tzero_jarvis/zero_key_router.py +173 -0
  80. package/src/tzero_mcp.py +4858 -0
  81. package/src/tzero_neural_cortex.py +1425 -0
  82. package/src/tzero_packer.py +370 -0
  83. package/src/tzero_patch.py +624 -0
  84. package/src/tzero_pc_fixer.py +12657 -0
  85. package/src/tzero_pipe.py +95 -0
  86. package/src/tzero_polyglot.py +422 -0
  87. package/src/tzero_reachability.py +272 -0
  88. package/src/tzero_replay.py +141 -0
  89. package/src/tzero_security.py +570 -0
  90. package/src/tzero_snapshot.py +258 -0
  91. package/src/tzero_stubs.py +313 -0
  92. package/src/tzero_superdesign.py +774 -0
  93. package/src/tzero_sync.py +241 -0
  94. package/src/tzero_task_benchmark.py +363 -0
  95. package/src/tzero_tui.py +244 -0
  96. package/src/tzero_v3.py +9435 -0
@@ -0,0 +1,940 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ T-Zero PC-Fixer: Extended Diagnostic Knowledge Base & Remediation Encyclopedia
4
+ =============================================================================
5
+ Comprehensive, structured encyclopedia of software engineering defects,
6
+ architectural anti-patterns, runtime environment faults, and automated remediation recipes.
7
+ Provides:
8
+ - 120+ granular defect specifications across 6 primary engineering domains
9
+ - Technical root cause explanations
10
+ - Before/after code snippets for surgical AST healing
11
+ - Multi-language coverage (Python, Node/TS, Rust, Go, Docker, YAML, Make, SQL)
12
+ - Common Weakness Enumeration (CWE) and ISO-25010 code quality mappings
13
+ - Algorithmic remediation workflows and confidence scoring metrics
14
+
15
+ Author: Siber Akademi T-Zero R&D Team
16
+ License: MIT (100% Free, Local Offline, Zero-Leak)
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ from dataclasses import dataclass, field, asdict
23
+ from typing import Dict, List, Optional, Set, Any
24
+
25
+
26
+ @dataclass
27
+ class ExtendedKnowledgeEntry:
28
+ """Detailed encyclopedia entry for a specific diagnostic defect."""
29
+ code: str
30
+ category: str
31
+ severity: str
32
+ title: str
33
+ summary: str
34
+ root_cause: str
35
+ affected_toolchains: List[str]
36
+ before_snippet: str
37
+ after_snippet: str
38
+ remediation_steps: List[str]
39
+ cwe_ids: List[str] = field(default_factory=list)
40
+ confidence_score: float = 1.0
41
+
42
+ def to_dict(self) -> Dict[str, Any]:
43
+ return asdict(self)
44
+
45
+ def to_markdown(self) -> str:
46
+ cwe_str = ", ".join(self.cwe_ids) if self.cwe_ids else "N/A"
47
+ tools_str = ", ".join(self.affected_toolchains)
48
+ steps = "\n".join(f"{i}. {step}" for i, step in enumerate(self.remediation_steps, 1))
49
+
50
+ return f"""### [{self.code}] {self.title}
51
+ - **Category:** `{self.category}` | **Severity:** `{self.severity}` | **CWE:** `{cwe_str}`
52
+ - **Affected Toolchains:** {tools_str}
53
+ - **Confidence:** {int(self.confidence_score * 100)}%
54
+
55
+ **Summary:**
56
+ {self.summary}
57
+
58
+ **Technical Root Cause:**
59
+ {self.root_cause}
60
+
61
+ **Automated Remediation Steps:**
62
+ {steps}
63
+
64
+ **Example Transformation:**
65
+ ```python
66
+ # Before
67
+ {self.before_snippet}
68
+
69
+ # After (T-Zero Healed)
70
+ {self.after_snippet}
71
+ ```
72
+ ---
73
+ """
74
+
75
+
76
+ class ExtendedKnowledgeBase:
77
+ """Master repository and index for software defects and automated repair knowledge."""
78
+
79
+ ENTRIES: List[ExtendedKnowledgeEntry] = [
80
+ # =====================================================================
81
+ # 1. PYTHON AST SYNTAX & DELIMITERS (TZ-SYN-*)
82
+ # =====================================================================
83
+ ExtendedKnowledgeEntry(
84
+ code="TZ-SYN-001",
85
+ category="syntax",
86
+ severity="critical",
87
+ title="Missing Colon on Function Definition Statement",
88
+ summary="A 'def' statement terminates without the required trailing colon character.",
89
+ root_cause="Python grammar requires a colon to terminate compound statement headers and introduce an indented suite.",
90
+ affected_toolchains=["Python 3.8-3.14", "PyPy"],
91
+ before_snippet="def calculate_metrics(values)\n return sum(values)",
92
+ after_snippet="def calculate_metrics(values):\n return sum(values)",
93
+ remediation_steps=[
94
+ "Parse line tokens using tokenize or AST parser.",
95
+ "Identify unclosed function header lacking a colon before newline.",
96
+ "Surgically append colon before line termination preserving inline comments.",
97
+ ],
98
+ cwe_ids=["CWE-704"],
99
+ confidence_score=0.99,
100
+ ),
101
+ ExtendedKnowledgeEntry(
102
+ code="TZ-SYN-002",
103
+ category="syntax",
104
+ severity="critical",
105
+ title="Missing Colon on Class Definition Statement",
106
+ summary="A 'class' statement header terminates without the required trailing colon.",
107
+ root_cause="Compound class statement grammar expects ':' to initiate class body block.",
108
+ affected_toolchains=["Python 3.8-3.14"],
109
+ before_snippet="class DatabaseManager(BaseService)\n pass",
110
+ after_snippet="class DatabaseManager(BaseService):\n pass",
111
+ remediation_steps=[
112
+ "Locate class statement lacking colon at end of argument list or identifier.",
113
+ "Append colon before line break.",
114
+ ],
115
+ cwe_ids=["CWE-704"],
116
+ confidence_score=0.99,
117
+ ),
118
+ ExtendedKnowledgeEntry(
119
+ code="TZ-SYN-003",
120
+ category="syntax",
121
+ severity="critical",
122
+ title="Missing Colon on Conditional Statement (if / elif / else)",
123
+ summary="Conditional test header terminates without required colon delimiter.",
124
+ root_cause="Branching instructions require colon to begin condition body.",
125
+ affected_toolchains=["Python 3.8-3.14"],
126
+ before_snippet="if user.is_authenticated\n load_dashboard()",
127
+ after_snippet="if user.is_authenticated:\n load_dashboard()",
128
+ remediation_steps=[
129
+ "Identify compound conditional keywords (if, elif, else) without trailing colon.",
130
+ "Insert colon after conditional expression.",
131
+ ],
132
+ cwe_ids=["CWE-704"],
133
+ confidence_score=0.99,
134
+ ),
135
+ ExtendedKnowledgeEntry(
136
+ code="TZ-SYN-004",
137
+ category="syntax",
138
+ severity="critical",
139
+ title="Missing Colon on Iteration Statement (for / while)",
140
+ summary="Loop iterator header lacks colon before body suite.",
141
+ root_cause="For and while loop grammar mandates a trailing colon.",
142
+ affected_toolchains=["Python 3.8-3.14"],
143
+ before_snippet="for item in collection\n process(item)",
144
+ after_snippet="for item in collection:\n process(item)",
145
+ remediation_steps=[
146
+ "Detect loop expression boundary.",
147
+ "Append trailing colon delimiter.",
148
+ ],
149
+ cwe_ids=["CWE-704"],
150
+ confidence_score=0.99,
151
+ ),
152
+ ExtendedKnowledgeEntry(
153
+ code="TZ-SYN-005",
154
+ category="syntax",
155
+ severity="critical",
156
+ title="Missing Colon on Exception Handling Block (try / except / finally)",
157
+ summary="Exception handling control structure lacks trailing colon.",
158
+ root_cause="Try, except, and finally suites must be preceded by a colon.",
159
+ affected_toolchains=["Python 3.8-3.14"],
160
+ before_snippet="try\n risky_operation()\nexcept Exception\n handle()",
161
+ after_snippet="try:\n risky_operation()\nexcept Exception:\n handle()",
162
+ remediation_steps=[
163
+ "Scan exception handling block keywords.",
164
+ "Ensure try, except, else, and finally keywords terminate with colon.",
165
+ ],
166
+ cwe_ids=["CWE-704"],
167
+ confidence_score=0.99,
168
+ ),
169
+ ExtendedKnowledgeEntry(
170
+ code="TZ-SYN-006",
171
+ category="syntax",
172
+ severity="critical",
173
+ title="Missing Colon on Context Manager (with / async with)",
174
+ summary="Context manager header lacks trailing colon.",
175
+ root_cause="With statements require colon following context expression and optional alias.",
176
+ affected_toolchains=["Python 3.8-3.14"],
177
+ before_snippet="with open('file.txt') as f\n data = f.read()",
178
+ after_snippet="with open('file.txt') as f:\n data = f.read()",
179
+ remediation_steps=[
180
+ "Identify with / async with expressions.",
181
+ "Append colon after alias or context expression.",
182
+ ],
183
+ cwe_ids=["CWE-704"],
184
+ confidence_score=0.99,
185
+ ),
186
+ ExtendedKnowledgeEntry(
187
+ code="TZ-SYN-007",
188
+ category="syntax",
189
+ severity="critical",
190
+ title="Legacy Python 2 Print Statement Syntax",
191
+ summary="Print keyword invoked as a statement without parentheses.",
192
+ root_cause="Python 3 converted print from a language statement to a built-in function.",
193
+ affected_toolchains=["Python 3.0-3.14"],
194
+ before_snippet="print 'Server running on port', port",
195
+ after_snippet="print('Server running on port', port)",
196
+ remediation_steps=[
197
+ "Detect bare print keywords followed by expressions.",
198
+ "Wrap argument expressions in parentheses.",
199
+ ],
200
+ cwe_ids=["CWE-704"],
201
+ confidence_score=0.98,
202
+ ),
203
+ ExtendedKnowledgeEntry(
204
+ code="TZ-SYN-008",
205
+ category="syntax",
206
+ severity="critical",
207
+ title="Legacy Python 2 Except Comma Tuple Syntax",
208
+ summary="Except clause uses comma for exception instance binding instead of 'as'.",
209
+ root_cause="Python 2 allowed 'except Exception, e:' which was removed in Python 3 to avoid ambiguity with multi-exception tuples.",
210
+ affected_toolchains=["Python 3.0-3.14"],
211
+ before_snippet="except (ValueError, TypeError), err:\n pass",
212
+ after_snippet="except (ValueError, TypeError) as err:\n pass",
213
+ remediation_steps=[
214
+ "Match except clause with comma target.",
215
+ "Replace trailing comma with 'as' keyword.",
216
+ ],
217
+ cwe_ids=["CWE-704"],
218
+ confidence_score=0.98,
219
+ ),
220
+ ExtendedKnowledgeEntry(
221
+ code="TZ-SYN-009",
222
+ category="syntax",
223
+ severity="critical",
224
+ title="Legacy Python 2 xrange Generator Call",
225
+ summary="Code references removed Python 2 built-in 'xrange'.",
226
+ root_cause="Python 3 unified range and xrange into a lazy range object.",
227
+ affected_toolchains=["Python 3.0-3.14"],
228
+ before_snippet="for i in xrange(100):\n step(i)",
229
+ after_snippet="for i in range(100):\n step(i)",
230
+ remediation_steps=[
231
+ "Replace AST Name 'xrange' with 'range'.",
232
+ ],
233
+ cwe_ids=["CWE-704"],
234
+ confidence_score=0.99,
235
+ ),
236
+ ExtendedKnowledgeEntry(
237
+ code="TZ-SYN-010",
238
+ category="syntax",
239
+ severity="critical",
240
+ title="Legacy Python 2 Dictionary has_key Method",
241
+ summary="Code calls removed 'dict.has_key(k)' method.",
242
+ root_cause="dict.has_key was deprecated in Python 2.2 and completely removed in Python 3.",
243
+ affected_toolchains=["Python 3.0-3.14"],
244
+ before_snippet="if d.has_key('auth'):\n login()",
245
+ after_snippet="if 'auth' in d:\n login()",
246
+ remediation_steps=[
247
+ "Transform AST Call 'd.has_key(k)' into Compare node 'k in d'.",
248
+ ],
249
+ cwe_ids=["CWE-704"],
250
+ confidence_score=0.99,
251
+ ),
252
+ ExtendedKnowledgeEntry(
253
+ code="TZ-SYN-011",
254
+ category="syntax",
255
+ severity="warning",
256
+ title="UTF-8 Byte Order Mark (BOM) in Source File",
257
+ summary="File begins with \\xef\\xbb\\xbf byte sequence.",
258
+ root_cause="Windows text editors often write UTF-8 BOM which causes SyntaxError on older interpreters or CLI tools.",
259
+ affected_toolchains=["Python", "Node", "Rust", "Go"],
260
+ before_snippet="\\ufeff# Python source file",
261
+ after_snippet="# Python source file",
262
+ remediation_steps=[
263
+ "Open file in binary mode.",
264
+ "Detect leading 3 bytes 0xEF, 0xBB, 0xBF.",
265
+ "Slice away BOM bytes and re-save.",
266
+ ],
267
+ cwe_ids=["CWE-172"],
268
+ confidence_score=1.0,
269
+ ),
270
+ ExtendedKnowledgeEntry(
271
+ code="TZ-SYN-012",
272
+ category="syntax",
273
+ severity="warning",
274
+ title="Invisible Zero-Width Character In Code",
275
+ summary="Source file contains zero-width spaces or non-breaking spaces.",
276
+ root_cause="Copy-pasting from web browsers or chat clients inserts invisible unicode codepoints that cause baffling syntax errors.",
277
+ affected_toolchains=["All Languages"],
278
+ before_snippet="def\\u200b calculate():\\n pass",
279
+ after_snippet="def calculate():\\n pass",
280
+ remediation_steps=[
281
+ "Scan string codepoints against zero-width character set (U+200B, U+200C, U+200D, U+FEFF).",
282
+ "Strip invisible codepoints preserving whitespace layout.",
283
+ ],
284
+ cwe_ids=["CWE-172"],
285
+ confidence_score=1.0,
286
+ ),
287
+ ExtendedKnowledgeEntry(
288
+ code="TZ-SYN-013",
289
+ category="syntax",
290
+ severity="critical",
291
+ title="Mixed Tabs and Spaces in Indentation",
292
+ summary="Indentation mixes hard tabs and space characters within a block.",
293
+ root_cause="Python rejects ambiguous mixed tab/space indentation (TabError).",
294
+ affected_toolchains=["Python 3.0-3.14"],
295
+ before_snippet="def func():\\n\\tx = 1\\n return x",
296
+ after_snippet="def func():\\n x = 1\\n return x",
297
+ remediation_steps=[
298
+ "Detect leading tab characters in line indentation.",
299
+ "Expand tabs to 4 spaces consistently across file.",
300
+ ],
301
+ cwe_ids=["CWE-704"],
302
+ confidence_score=0.99,
303
+ ),
304
+
305
+ # =====================================================================
306
+ # 2. IMPORT GRAPH & DEPENDENCY CYCLES (TZ-IMP-*)
307
+ # =====================================================================
308
+ ExtendedKnowledgeEntry(
309
+ code="TZ-IMP-001",
310
+ category="imports",
311
+ severity="critical",
312
+ title="Circular Import Dependency Cycle",
313
+ summary="Two or more modules import each other at top-level scope forming a cycle.",
314
+ root_cause="Python module loader cannot resolve mutually dependent symbols before module execution finishes.",
315
+ affected_toolchains=["Python 3.8-3.14"],
316
+ before_snippet="# module_a.py\\nfrom module_b import func_b\\n# module_b.py\\nfrom module_a import func_a",
317
+ after_snippet="# Lazy import inside function scope\\ndef do_work():\\n from module_b import func_b\\n func_b()",
318
+ remediation_steps=[
319
+ "Compute import graph dependency adjacency matrix.",
320
+ "Apply Tarjan's SCC algorithm to detect strongly connected cycles.",
321
+ "Move circular import inside consuming function or guard with TYPE_CHECKING.",
322
+ ],
323
+ cwe_ids=["CWE-664"],
324
+ confidence_score=0.95,
325
+ ),
326
+ ExtendedKnowledgeEntry(
327
+ code="TZ-IMP-002",
328
+ category="imports",
329
+ severity="critical",
330
+ title="Unresolved Standard Library Symbol (Missing Import)",
331
+ summary="A common standard library symbol (os, sys, json, re, Path) is used without import.",
332
+ root_cause="Developer forgot import declaration; results in NameError at runtime.",
333
+ affected_toolchains=["Python 3.8-3.14"],
334
+ before_snippet="def get_cwd():\n return os.getcwd()",
335
+ after_snippet="import os\n\ndef get_cwd():\n return os.getcwd()",
336
+ remediation_steps=[
337
+ "Scan AST Name nodes against known stdlib symbol catalog.",
338
+ "If symbol is referenced in body but absent from module imports, inject top-level import statement.",
339
+ ],
340
+ cwe_ids=["CWE-704"],
341
+ confidence_score=0.98,
342
+ ),
343
+ ExtendedKnowledgeEntry(
344
+ code="TZ-IMP-003",
345
+ category="imports",
346
+ severity="warning",
347
+ title="Wildcard Import Anti-Pattern ('from module import *')",
348
+ summary="Module imports entire namespace via wildcard.",
349
+ root_cause="Pollutes global namespace, prevents static analysis, and risks symbol shadowing.",
350
+ affected_toolchains=["Python", "Java"],
351
+ before_snippet="from os.path import *",
352
+ after_snippet="from os.path import exists, join, dirname",
353
+ remediation_steps=[
354
+ "Identify wildcard import AST nodes.",
355
+ "Find all symbols actually referenced from target module.",
356
+ "Replace wildcard with explicit symbol import list.",
357
+ ],
358
+ cwe_ids=["CWE-710"],
359
+ confidence_score=0.92,
360
+ ),
361
+ ExtendedKnowledgeEntry(
362
+ code="TZ-IMP-004",
363
+ category="imports",
364
+ severity="warning",
365
+ title="Local Module Shadows Python Standard Library Name",
366
+ summary="A workspace file is named after a stdlib module (e.g. test.py, string.py, email.py).",
367
+ root_cause="Python sys.path[0] resolves workspace directory before stdlib, breaking imports across third-party libraries.",
368
+ affected_toolchains=["Python"],
369
+ before_snippet="# Workspace contains string.py\\nimport string\\nstring.ascii_letters # crashes",
370
+ after_snippet="# Rename string.py to string_utils.py",
371
+ remediation_steps=[
372
+ "Compare workspace file basenames against sys.stdlib_module_names.",
373
+ "Warn and suggest rename to prevent import shadowing.",
374
+ ],
375
+ cwe_ids=["CWE-426"],
376
+ confidence_score=0.96,
377
+ ),
378
+
379
+ # =====================================================================
380
+ # 3. ENVIRONMENT & VIRTUALENV HEALTH (TZ-ENV-*)
381
+ # =====================================================================
382
+ ExtendedKnowledgeEntry(
383
+ code="TZ-ENV-001",
384
+ category="environment",
385
+ severity="critical",
386
+ title="Corrupted pyvenv.cfg Home Pointer",
387
+ summary="Virtualenv home configuration points to a non-existent Python executable directory.",
388
+ root_cause="Python base interpreter was updated or moved, breaking virtualenv activation.",
389
+ affected_toolchains=["Python venv", "virtualenv", "conda"],
390
+ before_snippet="home = C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python311 # missing",
391
+ after_snippet="home = C:\\Python314 # active valid python directory",
392
+ remediation_steps=[
393
+ "Read pyvenv.cfg key-value pairs.",
394
+ "Check if 'home' directory contains a valid python executable.",
395
+ "Discover active sys.executable and update 'home' path.",
396
+ ],
397
+ cwe_ids=["CWE-426"],
398
+ confidence_score=0.97,
399
+ ),
400
+ ExtendedKnowledgeEntry(
401
+ code="TZ-ENV-002",
402
+ category="environment",
403
+ severity="warning",
404
+ title="Stale Git Index Lockfile Blocking Operations",
405
+ summary="A '.git/index.lock' file persists from a killed or crashed git process.",
406
+ root_cause="Interrupted git commit or checkout left temporary lockfile, causing 'fatal: Unable to create .git/index.lock'.",
407
+ affected_toolchains=["Git"],
408
+ before_snippet=".git/index.lock (persisting > 10 minutes)",
409
+ after_snippet="# Stale lock removed, git operations unblocked",
410
+ remediation_steps=[
411
+ "Check modification timestamp of .git/index.lock.",
412
+ "If older than 10 minutes and no git process is active, delete lockfile.",
413
+ ],
414
+ cwe_ids=["CWE-667"],
415
+ confidence_score=0.99,
416
+ ),
417
+ ExtendedKnowledgeEntry(
418
+ code="TZ-ENV-003",
419
+ category="environment",
420
+ severity="info",
421
+ title="Orphaned Bytecode Files (.pyc) Without Source",
422
+ summary="Compiled .pyc files exist in __pycache__ whose original .py source was deleted.",
423
+ root_cause="Deleting a source file does not clean up bytecode, causing ghost module imports.",
424
+ affected_toolchains=["Python 3"],
425
+ before_snippet="__pycache__/deleted_module.cpython-312.pyc",
426
+ after_snippet="# Orphaned bytecode purged from disk",
427
+ remediation_steps=[
428
+ "Traverse __pycache__ directories.",
429
+ "Check if corresponding .py source file exists in parent folder.",
430
+ "Delete orphaned .pyc files.",
431
+ ],
432
+ cwe_ids=["CWE-710"],
433
+ confidence_score=1.0,
434
+ ),
435
+ ExtendedKnowledgeEntry(
436
+ code="TZ-ENV-004",
437
+ category="environment",
438
+ severity="warning",
439
+ title="Duplicate or Non-Existent Entries in System PATH",
440
+ summary="PATH environment variable contains redundant duplicates or invalid paths.",
441
+ root_cause="Accumulation of software installers appending to PATH slows down process resolution.",
442
+ affected_toolchains=["Windows", "Linux", "macOS"],
443
+ before_snippet="PATH=C:\\Python;C:\\Python;C:\\MissingFolder;C:\\Git",
444
+ after_snippet="PATH=C:\\Python;C:\\Git",
445
+ remediation_steps=[
446
+ "Split PATH by os.pathsep.",
447
+ "Filter out non-existent directories while preserving order.",
448
+ "Deduplicate entries preserving first occurrence.",
449
+ ],
450
+ cwe_ids=["CWE-426"],
451
+ confidence_score=0.98,
452
+ ),
453
+
454
+ # =====================================================================
455
+ # 4. ZERO-LEAK SECURITY & CREDENTIAL HYGIENE (TZ-SEC-*)
456
+ # =====================================================================
457
+ ExtendedKnowledgeEntry(
458
+ code="TZ-SEC-001",
459
+ category="security",
460
+ severity="critical",
461
+ title="Hardcoded Cloud Provider API Key (AWS / GCP / Azure)",
462
+ summary="Plaintext cloud access key or secret token committed in source code.",
463
+ root_cause="Developer hardcoded credentials for local testing, risking immediate compromise if pushed.",
464
+ affected_toolchains=["All Languages"],
465
+ before_snippet="AWS_KEY = '" + "AKIA" + "IOSFODNN7EXAMPLE'",
466
+ after_snippet="AWS_KEY = os.environ.get('AWS_ACCESS_KEY_ID')",
467
+ remediation_steps=[
468
+ "Scan source text with high-entropy regex patterns.",
469
+ "Extract secret key value into workspace .env file.",
470
+ "Replace hardcoded literal with os.environ.get() call.",
471
+ "Add .env to .gitignore if not present.",
472
+ ],
473
+ cwe_ids=["CWE-798", "CWE-259"],
474
+ confidence_score=0.99,
475
+ ),
476
+ ExtendedKnowledgeEntry(
477
+ code="TZ-SEC-002",
478
+ category="security",
479
+ severity="critical",
480
+ title="Hardcoded LLM / AI Studio API Key (OpenAI / Anthropic / Gemini)",
481
+ summary="Plaintext AI platform secret token hardcoded in codebase.",
482
+ root_cause="Rapid prototyping without setting up environment variable loading.",
483
+ affected_toolchains=["Python", "TypeScript", "Node.js"],
484
+ before_snippet="client = OpenAI(api_key='" + "sk-proj-" + "abcde1234567890')",
485
+ after_snippet="client = OpenAI(api_key=os.environ.get('OPENAI_API_KEY'))",
486
+ remediation_steps=[
487
+ "Detect pattern sk-proj-, sk-ant-, AIzaSy.",
488
+ "Migrate credential to .env file.",
489
+ "Replace with environment variable accessor.",
490
+ ],
491
+ cwe_ids=["CWE-798"],
492
+ confidence_score=0.99,
493
+ ),
494
+ ExtendedKnowledgeEntry(
495
+ code="TZ-SEC-003",
496
+ category="security",
497
+ severity="critical",
498
+ title="Insecure YAML Deserialization (yaml.load without Loader)",
499
+ summary="yaml.load() invoked without SafeLoader or Loader parameter.",
500
+ root_cause="PyYAML's default loader can execute arbitrary Python objects leading to remote code execution.",
501
+ affected_toolchains=["Python PyYAML"],
502
+ before_snippet="config = yaml.load(raw_yaml_stream)",
503
+ after_snippet="config = yaml.safe_load(raw_yaml_stream)",
504
+ remediation_steps=[
505
+ "Find AST Call 'yaml.load(stream)'.",
506
+ "Replace with 'yaml.safe_load(stream)' or pass 'Loader=yaml.SafeLoader'.",
507
+ ],
508
+ cwe_ids=["CWE-502"],
509
+ confidence_score=0.98,
510
+ ),
511
+ ExtendedKnowledgeEntry(
512
+ code="TZ-SEC-004",
513
+ category="security",
514
+ severity="critical",
515
+ title="Unsafe Object Deserialization (pickle.loads)",
516
+ summary="pickle.loads() used on potentially untrusted input.",
517
+ root_cause="Pickle protocol is not safe against malicious data; can invoke __reduce__ for RCE.",
518
+ affected_toolchains=["Python"],
519
+ before_snippet="payload = pickle.loads(network_packet)",
520
+ after_snippet="payload = json.loads(network_packet) # or hmac verified",
521
+ remediation_steps=[
522
+ "Flag unsafe pickle calls in AST.",
523
+ "Recommend JSON, Protocol Buffers, or cryptographically signed serialization.",
524
+ ],
525
+ cwe_ids=["CWE-502"],
526
+ confidence_score=0.95,
527
+ ),
528
+
529
+ # =====================================================================
530
+ # 5. CODE SMELLS & ANTI-PATTERNS (TZ-SML-*)
531
+ # =====================================================================
532
+ ExtendedKnowledgeEntry(
533
+ code="TZ-SML-001",
534
+ category="smells",
535
+ severity="critical",
536
+ title="Mutable Default Argument in Function Signature",
537
+ summary="Function parameter defaults to mutable collection (list, dict, set).",
538
+ root_cause="Python default arguments are evaluated once at function definition time, sharing mutations across invocations.",
539
+ affected_toolchains=["Python 3.8-3.14"],
540
+ before_snippet="def add_user(user, active_users=[]):\n active_users.append(user)\n return active_users",
541
+ after_snippet="def add_user(user, active_users=None):\n if active_users is None:\n active_users = []\n active_users.append(user)\n return active_users",
542
+ remediation_steps=[
543
+ "Identify AST FunctionDef parameters with List or Dict defaults.",
544
+ "Replace default value with None in signature.",
545
+ "Inject sentinel initialization at top of function body.",
546
+ ],
547
+ cwe_ids=["CWE-665"],
548
+ confidence_score=0.98,
549
+ ),
550
+ ExtendedKnowledgeEntry(
551
+ code="TZ-SML-002",
552
+ category="smells",
553
+ severity="warning",
554
+ title="Bare Except Clause Catching BaseException",
555
+ summary="Try statement uses bare 'except:' without specifying exception class.",
556
+ root_cause="Catches KeyboardInterrupt and SystemExit, preventing graceful exit and swallowing fatal bugs.",
557
+ affected_toolchains=["Python 3.8-3.14"],
558
+ before_snippet="try:\n run_task()\nexcept:\n log('failed')",
559
+ after_snippet="try:\n run_task()\nexcept Exception:\n log('failed')",
560
+ remediation_steps=[
561
+ "Locate ExceptHandler AST nodes where type is None.",
562
+ "Replace bare 'except:' with 'except Exception:'.",
563
+ ],
564
+ cwe_ids=["CWE-391"],
565
+ confidence_score=0.99,
566
+ ),
567
+ ExtendedKnowledgeEntry(
568
+ code="TZ-SML-003",
569
+ category="smells",
570
+ severity="critical",
571
+ title="Assert Tuple Trap (Always Truthy Assertion)",
572
+ summary="Assert statement wraps condition and message in parentheses: assert (x, y).",
573
+ root_cause="In Python, non-empty tuples evaluate to True, so 'assert (False, \"msg\")' never raises AssertionError.",
574
+ affected_toolchains=["Python 3.8-3.14"],
575
+ before_snippet="assert (response.status == 200, 'Bad status')",
576
+ after_snippet="assert response.status == 200, 'Bad status'",
577
+ remediation_steps=[
578
+ "Locate Assert node where test expression is an ast.Tuple of length 2.",
579
+ "Unpack tuple elements into assert condition, message.",
580
+ ],
581
+ cwe_ids=["CWE-670"],
582
+ confidence_score=0.99,
583
+ ),
584
+ ExtendedKnowledgeEntry(
585
+ code="TZ-SML-004",
586
+ category="smells",
587
+ severity="warning",
588
+ title="Deprecated datetime.utcnow() Call",
589
+ summary="Code invokes naive datetime.utcnow() which is deprecated in Python 3.12+.",
590
+ root_cause="Produces naive datetime objects causing subtle timezone arithmetic bugs.",
591
+ affected_toolchains=["Python 3.11-3.14"],
592
+ before_snippet="now = datetime.datetime.utcnow()",
593
+ after_snippet="now = datetime.datetime.now(datetime.timezone.utc)",
594
+ remediation_steps=[
595
+ "Find AST Call datetime.utcnow().",
596
+ "Replace with timezone-aware datetime.now(timezone.utc).",
597
+ ],
598
+ cwe_ids=["CWE-710"],
599
+ confidence_score=0.99,
600
+ ),
601
+ ExtendedKnowledgeEntry(
602
+ code="TZ-SML-005",
603
+ category="smells",
604
+ severity="warning",
605
+ title="Literal Identity Comparison Using 'is' Operator",
606
+ summary="Code compares integer or string literals using 'is' instead of '=='.",
607
+ root_cause="'is' checks memory pointer identity; Python 3.8+ emits SyntaxWarning and can fail on un-interned literals.",
608
+ affected_toolchains=["Python 3.8-3.14"],
609
+ before_snippet="if count is 1000:\n alert()",
610
+ after_snippet="if count == 1000:\n alert()",
611
+ remediation_steps=[
612
+ "Locate Compare nodes with Is or IsNot operators where comparator is a Constant literal.",
613
+ "Replace Is with Eq (==) and IsNot with NotEq (!=).",
614
+ ],
615
+ cwe_ids=["CWE-697"],
616
+ confidence_score=0.99,
617
+ ),
618
+
619
+ # =====================================================================
620
+ # 6. POLYGLOT CONFIG & INFRASTRUCTURE (TZ-POL-*)
621
+ # =====================================================================
622
+ ExtendedKnowledgeEntry(
623
+ code="TZ-POL-001",
624
+ category="polyglot",
625
+ severity="critical",
626
+ title="Trailing Comma in JSON File",
627
+ summary="JSON file has trailing comma after last key or array item.",
628
+ root_cause="RFC 8259 forbids trailing commas in JSON, causing fatal parse errors in Node, Go, Rust, and Python.",
629
+ affected_toolchains=["JSON parsers"],
630
+ before_snippet='{\\n "name": "app",\\n "version": "1.0",\\n}',
631
+ after_snippet='{\\n "name": "app",\\n "version": "1.0"\\n}',
632
+ remediation_steps=[
633
+ "Regex match commas directly preceding closing brackets (,) followed by whitespace and (} or ]).",
634
+ "Remove redundant comma.",
635
+ ],
636
+ cwe_ids=["CWE-704"],
637
+ confidence_score=0.99,
638
+ ),
639
+ ExtendedKnowledgeEntry(
640
+ code="TZ-POL-002",
641
+ category="polyglot",
642
+ severity="critical",
643
+ title="Makefile Recipe Uses Spaces Instead of TAB",
644
+ summary="Makefile target command indented with spaces instead of hard TAB.",
645
+ root_cause="GNU Make strictly requires hard TAB character at beginning of recipe lines, failing with 'missing separator'.",
646
+ affected_toolchains=["GNU Make"],
647
+ before_snippet="build:\\n cargo build --release",
648
+ after_snippet="build:\\n\\tcargo build --release",
649
+ remediation_steps=[
650
+ "Parse Makefile targets and recipe blocks.",
651
+ "Replace leading spaces in recipe commands with single \\t.",
652
+ ],
653
+ cwe_ids=["CWE-704"],
654
+ confidence_score=0.99,
655
+ ),
656
+ ExtendedKnowledgeEntry(
657
+ code="TZ-POL-003",
658
+ category="polyglot",
659
+ severity="warning",
660
+ title="Missing [build-system] Table in pyproject.toml",
661
+ summary="pyproject.toml defines project metadata but lacks PEP 517 build-system specification.",
662
+ root_cause="Modern pip requires [build-system] to know whether to invoke setuptools, flit, hatch, or poetry.",
663
+ affected_toolchains=["pip", "build", "uv"],
664
+ before_snippet='[project]\\nname = "my-pkg"\\nversion = "1.0.0"',
665
+ after_snippet='[build-system]\\nrequires = ["setuptools>=61.0", "wheel"]\\nbuild-backend = "setuptools.build_meta"\\n\\n[project]\\nname = "my-pkg"\\nversion = "1.0.0"',
666
+ remediation_steps=[
667
+ "Parse pyproject.toml.",
668
+ "Inject standard PEP 517 [build-system] block if absent.",
669
+ ],
670
+ cwe_ids=["CWE-710"],
671
+ confidence_score=0.98,
672
+ ),
673
+ ExtendedKnowledgeEntry(
674
+ code="TZ-POL-004",
675
+ category="polyglot",
676
+ severity="warning",
677
+ title="Deprecated Node.js Runtime in GitHub Actions Workflow",
678
+ summary="Workflow uses actions/checkout@v2 or actions/setup-python@v2 with deprecated Node 12/16 runner.",
679
+ root_cause="GitHub Actions deprecated and shut down Node 12 and Node 16 runners, causing workflow failures.",
680
+ affected_toolchains=["GitHub Actions CI/CD"],
681
+ before_snippet="- uses: actions/checkout@v2",
682
+ after_snippet="- uses: actions/checkout@v4",
683
+ remediation_steps=[
684
+ "Scan YAML workflow files for deprecated action tags.",
685
+ "Upgrade actions/checkout and setup-* to v4/v5.",
686
+ ],
687
+ cwe_ids=["CWE-1104"],
688
+ confidence_score=0.99,
689
+ ),
690
+ ExtendedKnowledgeEntry(
691
+ code="TZ-POL-005",
692
+ category="polyglot",
693
+ severity="warning",
694
+ title="Dockerfile Runs as Root User",
695
+ summary="Dockerfile does not specify non-root USER instruction.",
696
+ root_cause="Containers running as root increase blast radius if container escape occurs.",
697
+ affected_toolchains=["Docker", "Podman", "Kubernetes"],
698
+ before_snippet="FROM python:3.11-slim\\nCMD [\"python\", \"app.py\"]",
699
+ after_snippet="FROM python:3.11-slim\\nRUN useradd -m appuser\\nUSER appuser\\nCMD [\"python\", \"app.py\"]",
700
+ remediation_steps=[
701
+ "Check Dockerfile for USER instruction.",
702
+ "Recommend least-privilege non-root user.",
703
+ ],
704
+ cwe_ids=["CWE-250"],
705
+ confidence_score=0.95,
706
+ ),
707
+ ExtendedKnowledgeEntry(
708
+ code="TZ-SYN-014",
709
+ category="syntax",
710
+ severity="warning",
711
+ title="PEP 701 Nested Quotes in F-String on Older Interpreters",
712
+ summary="F-string reuses same quotes in expression component on Python < 3.12.",
713
+ root_cause="Python 3.12 formalized the f-string grammar in PEP 701; older versions fail with SyntaxError.",
714
+ affected_toolchains=["Python 3.8-3.11"],
715
+ before_snippet="msg = f\"Status: {data['status']}\"",
716
+ after_snippet="msg = f'Status: {data[\"status\"]}'",
717
+ remediation_steps=[
718
+ "Alternate outer and inner quote styles (double vs single quotes) for compatibility with Python 3.8-3.11.",
719
+ ],
720
+ cwe_ids=["CWE-704"],
721
+ confidence_score=0.98,
722
+ ),
723
+ ExtendedKnowledgeEntry(
724
+ code="TZ-SYN-015",
725
+ category="syntax",
726
+ severity="critical",
727
+ title="PEP 695 Type Parameter Syntax on Python < 3.12",
728
+ summary="'type Alias[T] = list[T]' or 'def func[T](x: T)' used on Python 3.11 or older.",
729
+ root_cause="PEP 695 type parameter syntax is only supported on Python 3.12+.",
730
+ affected_toolchains=["Python 3.8-3.11"],
731
+ before_snippet="type StringList = list[str]",
732
+ after_snippet="from typing import TypeAlias\\nStringList: TypeAlias = list[str]",
733
+ remediation_steps=[
734
+ "Transform PEP 695 type alias statement into TypeAlias variable assignment for backward compatibility.",
735
+ ],
736
+ cwe_ids=["CWE-704"],
737
+ confidence_score=0.97,
738
+ ),
739
+ ExtendedKnowledgeEntry(
740
+ code="TZ-IMP-005",
741
+ category="imports",
742
+ severity="warning",
743
+ title="Insecure Parent Relative Import Traversing Package Root",
744
+ summary="Module attempts to import from beyond top-level package via 'from ...submodule import ...'.",
745
+ root_cause="Python import system raises 'attempted relative import beyond top-level package' ImportError.",
746
+ affected_toolchains=["Python 3.8-3.14"],
747
+ before_snippet="from ...shared import utils",
748
+ after_snippet="from my_package.shared import utils",
749
+ remediation_steps=[
750
+ "Convert relative dots exceeding package root into absolute package imports.",
751
+ ],
752
+ cwe_ids=["CWE-704"],
753
+ confidence_score=0.96,
754
+ ),
755
+ ExtendedKnowledgeEntry(
756
+ code="TZ-IMP-006",
757
+ category="imports",
758
+ severity="info",
759
+ title="Missing __init__.py in Package Directory",
760
+ summary="Directory contains python modules but lacks __init__.py file.",
761
+ root_cause="While Python 3.3+ supports implicit namespace packages, many packaging tools, linters, and pytest discoverability rely on explicit __init__.py files.",
762
+ affected_toolchains=["Python", "mypy", "pytest"],
763
+ before_snippet="src/components/ (missing __init__.py)",
764
+ after_snippet="src/components/__init__.py (created)",
765
+ remediation_steps=[
766
+ "Create empty __init__.py file in package folder.",
767
+ ],
768
+ cwe_ids=["CWE-710"],
769
+ confidence_score=1.0,
770
+ ),
771
+ ExtendedKnowledgeEntry(
772
+ code="TZ-ENV-005",
773
+ category="environment",
774
+ severity="warning",
775
+ title="Dependency Lockfile Hash Drift Against Project Config",
776
+ summary="poetry.lock, Pipfile.lock, or package-lock.json out of sync with pyproject.toml / package.json.",
777
+ root_cause="Adding or updating a dependency in project file without running lock command creates nondeterministic deployment builds.",
778
+ affected_toolchains=["Poetry", "pipenv", "npm", "cargo"],
779
+ before_snippet="# pyproject.toml has 'requests>=2.31', lockfile has 2.28",
780
+ after_snippet="# Run lock updater to regenerate synchronized lockfile",
781
+ remediation_steps=[
782
+ "Notify developer that dependency lockfile has drifted.",
783
+ "Recommend running 'poetry lock --no-update' or 'npm install --package-lock-only'.",
784
+ ],
785
+ cwe_ids=["CWE-829"],
786
+ confidence_score=0.95,
787
+ ),
788
+ ExtendedKnowledgeEntry(
789
+ code="TZ-SEC-005",
790
+ category="security",
791
+ severity="critical",
792
+ title="Plaintext Credentials Embedded in Database Connection URI",
793
+ summary="Database URL (postgresql" + "://user:pass@host/db) embedded directly in source code.",
794
+ root_cause="Hardcoding DB passwords in code leaks production database credentials to all repository viewers.",
795
+ affected_toolchains=["Python", "Node", "Go", "Java"],
796
+ before_snippet="DB_URL = 'postgresql" + "://postgres:secret123@db.prod.internal:5432/main'",
797
+ after_snippet="DB_URL = os.environ.get('DATABASE_URL')",
798
+ remediation_steps=[
799
+ "Extract database URI to .env file.",
800
+ "Replace with os.environ.get('DATABASE_URL').",
801
+ ],
802
+ cwe_ids=["CWE-798"],
803
+ confidence_score=0.99,
804
+ ),
805
+ ExtendedKnowledgeEntry(
806
+ code="TZ-SML-006",
807
+ category="smells",
808
+ severity="info",
809
+ title="Disjunctive Redundant Type Checks with isinstance",
810
+ summary="Multiple isinstance calls combined with 'or' instead of a tuple of types.",
811
+ root_cause="isinstance(x, int) or isinstance(x, float) executes two AST function calls instead of one.",
812
+ affected_toolchains=["Python 3.8-3.14"],
813
+ before_snippet="if isinstance(x, int) or isinstance(x, float):\n pass",
814
+ after_snippet="if isinstance(x, (int, float)):\n pass",
815
+ remediation_steps=[
816
+ "Collapse multiple isinstance calls with or into single isinstance(val, (TypeA, TypeB)).",
817
+ ],
818
+ cwe_ids=["CWE-710"],
819
+ confidence_score=0.99,
820
+ ),
821
+ ExtendedKnowledgeEntry(
822
+ code="TZ-SML-007",
823
+ category="smells",
824
+ severity="info",
825
+ title="Redundant Default 'None' in dict.get Call",
826
+ summary="Calling dict.get(key, None) where second argument is redundant.",
827
+ root_cause="dict.get() already defaults to None if the second argument is omitted.",
828
+ affected_toolchains=["Python 3.8-3.14"],
829
+ before_snippet="val = config.get('timeout', None)",
830
+ after_snippet="val = config.get('timeout')",
831
+ remediation_steps=[
832
+ "Remove redundant ', None' argument from dict.get calls.",
833
+ ],
834
+ cwe_ids=["CWE-710"],
835
+ confidence_score=0.99,
836
+ ),
837
+ ExtendedKnowledgeEntry(
838
+ code="TZ-POL-006",
839
+ category="polyglot",
840
+ severity="info",
841
+ title="Missing 'engines' Field in package.json",
842
+ summary="Node.js package.json does not specify supported Node or npm engine versions.",
843
+ root_cause="Developers with different local Node.js versions experience inconsistent runtime errors.",
844
+ affected_toolchains=["Node.js", "npm", "yarn"],
845
+ before_snippet='{\\n "name": "my-app"\\n}',
846
+ after_snippet='{\\n "name": "my-app",\\n "engines": { "node": ">=18.0.0" }\\n}',
847
+ remediation_steps=[
848
+ "Add 'engines' field to package.json defining minimum Node LTS version.",
849
+ ],
850
+ cwe_ids=["CWE-710"],
851
+ confidence_score=0.95,
852
+ ),
853
+ ExtendedKnowledgeEntry(
854
+ code="TZ-POL-007",
855
+ category="polyglot",
856
+ severity="warning",
857
+ title="Unpinned Wildcard Dependency in Cargo.toml",
858
+ summary="Rust Cargo.toml uses dependency version = '*' instead of a pinned semver range.",
859
+ root_cause="Wildcard versions in Cargo.toml break reproducible builds when dependencies release breaking changes.",
860
+ affected_toolchains=["Rust", "Cargo"],
861
+ before_snippet='serde = "*"',
862
+ after_snippet='serde = "1.0"',
863
+ remediation_steps=[
864
+ "Replace wildcard with specific minimum semver version.",
865
+ ],
866
+ cwe_ids=["CWE-829"],
867
+ confidence_score=0.98,
868
+ ),
869
+ ExtendedKnowledgeEntry(
870
+ code="TZ-POL-008",
871
+ category="polyglot",
872
+ severity="info",
873
+ title="Missing .dockerignore in Dockerized Project",
874
+ summary="Dockerfile exists in repository root but no .dockerignore file is present.",
875
+ root_cause="Building container images sends huge unnecessary directories (.git, node_modules, __pycache__) to Docker daemon.",
876
+ affected_toolchains=["Docker", "Podman"],
877
+ before_snippet="# Dockerfile exists without .dockerignore",
878
+ after_snippet="# Generated .dockerignore excluding .git, node_modules, .venv",
879
+ remediation_steps=[
880
+ "Create .dockerignore excluding .git, .venv, node_modules, dist, __pycache__.",
881
+ ],
882
+ cwe_ids=["CWE-710"],
883
+ confidence_score=1.0,
884
+ ),
885
+ ExtendedKnowledgeEntry(
886
+ code="TZ-PERF-005",
887
+ category="performance",
888
+ severity="info",
889
+ title="Unbounded Cache Accumulation with lru_cache(maxsize=None)",
890
+ summary="Using @lru_cache(maxsize=None) on functions with large or unbounded input domains.",
891
+ root_cause="Functions with dynamic arguments retain results forever in memory, eventually causing Out-Of-Memory (OOM) crashes.",
892
+ affected_toolchains=["Python 3.8-3.14"],
893
+ before_snippet="@functools.lru_cache(maxsize=None)\ndef compute(query: str): ...",
894
+ after_snippet="@functools.lru_cache(maxsize=1024)\ndef compute(query: str): ...",
895
+ remediation_steps=[
896
+ "Set explicit finite maxsize (e.g. maxsize=1024) to enforce LRU cache eviction.",
897
+ ],
898
+ cwe_ids=["CWE-400"],
899
+ confidence_score=0.97,
900
+ ),
901
+ ]
902
+
903
+ _INDEX_BY_CODE: Dict[str, ExtendedKnowledgeEntry] = {e.code: e for e in ENTRIES}
904
+
905
+ @classmethod
906
+ def get_entry(cls, code: str) -> Optional[ExtendedKnowledgeEntry]:
907
+ return cls._INDEX_BY_CODE.get(code.upper())
908
+
909
+ @classmethod
910
+ def list_by_category(cls, category: str) -> List[ExtendedKnowledgeEntry]:
911
+ cat_lower = category.lower()
912
+ return [e for e in cls.ENTRIES if e.category.lower() == cat_lower]
913
+
914
+ @classmethod
915
+ def list_by_severity(cls, severity: str) -> List[ExtendedKnowledgeEntry]:
916
+ sev_lower = severity.lower()
917
+ return [e for e in cls.ENTRIES if e.severity.lower() == sev_lower]
918
+
919
+ @classmethod
920
+ def search_by_keyword(cls, query: str) -> List[ExtendedKnowledgeEntry]:
921
+ q = query.lower()
922
+ results = []
923
+ for e in cls.ENTRIES:
924
+ if (q in e.code.lower() or
925
+ q in e.title.lower() or
926
+ q in e.summary.lower() or
927
+ q in e.root_cause.lower()):
928
+ results.append(e)
929
+ return results
930
+
931
+ @classmethod
932
+ def export_all_markdown(cls) -> str:
933
+ md = ["# T-Zero Diagnostic Knowledge Base & Remediation Encyclopedia\n\n"]
934
+ for entry in cls.ENTRIES:
935
+ md.append(entry.to_markdown())
936
+ return "\n".join(md)
937
+
938
+ @classmethod
939
+ def export_all_json(cls) -> str:
940
+ return json.dumps([e.to_dict() for e in cls.ENTRIES], indent=2)