tzero-mcp 11.15.3 → 12.2.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 (71) hide show
  1. package/CONTRIBUTING.md +4 -4
  2. package/README.md +5 -5
  3. package/bin/postinstall.js +10 -2
  4. package/bin/tzero-mcp.js +1 -1
  5. package/bin/tzero.js +17 -0
  6. package/package.json +1 -1
  7. package/src/addmcp.py +34 -23
  8. package/src/app.py +1 -1
  9. package/src/main.py +6 -0
  10. package/src/tzero/__init__.py +10 -0
  11. package/src/tzero/anti_rea/__init__.py +70 -0
  12. package/src/tzero/anti_rea/algebraic_mutator.py +86 -0
  13. package/src/tzero/anti_rea/anti_agent_guard.py +96 -0
  14. package/src/tzero/anti_rea/anti_debugger.py +239 -0
  15. package/src/tzero/anti_rea/anti_vm.py +160 -0
  16. package/src/tzero/anti_rea/asar_shield.py +99 -0
  17. package/src/tzero/anti_rea/auditor.py +158 -0
  18. package/src/tzero/anti_rea/bpe_disrupter.py +48 -0
  19. package/src/tzero/anti_rea/bytecode_trap.py +85 -0
  20. package/src/tzero/anti_rea/canary_beacon.py +187 -0
  21. package/src/tzero/anti_rea/cli.py +102 -0
  22. package/src/tzero/anti_rea/confusables.py +86 -0
  23. package/src/tzero/anti_rea/engine.py +204 -0
  24. package/src/tzero/anti_rea/extractor_shield.py +102 -0
  25. package/src/tzero/anti_rea/flattener.py +136 -0
  26. package/src/tzero/anti_rea/gui.py +267 -0
  27. package/src/tzero/anti_rea/honeypot.py +58 -0
  28. package/src/tzero/anti_rea/integrity_guard.py +66 -0
  29. package/src/tzero/anti_rea/jailbreak_decoy.py +77 -0
  30. package/src/tzero/anti_rea/mcp_poison.py +41 -0
  31. package/src/tzero/anti_rea/native_bridge.py +169 -0
  32. package/src/tzero/anti_rea/rdtsc_guard.py +64 -0
  33. package/src/tzero/anti_rea/string_vault.py +94 -0
  34. package/src/tzero/anti_rea/sybil_network.py +53 -0
  35. package/src/tzero/anti_rea/timing_guard.py +46 -0
  36. package/src/tzero/anti_rea/token_bomb.py +65 -0
  37. package/src/tzero/anti_rea/traps.py +76 -0
  38. package/src/tzero/anti_rea/vm_obfuscator.py +182 -0
  39. package/src/tzero/siber_akademi.ico +0 -0
  40. package/src/tzero/siber_akademi_icon.py +1 -1
  41. package/src/tzero/tzero_armor.py +165 -0
  42. package/src/tzero/tzero_bridge.py +28 -15
  43. package/src/tzero/tzero_budget.py +10 -3
  44. package/src/tzero/tzero_card.py +7 -5
  45. package/src/tzero/tzero_ci.py +1 -0
  46. package/src/tzero/tzero_contracts.py +30 -11
  47. package/src/tzero/tzero_dashboard.py +34 -14
  48. package/src/tzero/tzero_debt.py +14 -5
  49. package/src/tzero/tzero_federation.py +11 -6
  50. package/src/tzero/tzero_fixer/security_zero_leak.py +21 -3
  51. package/src/tzero/tzero_golden.py +11 -6
  52. package/src/tzero/tzero_graph_hud.html +1 -1
  53. package/src/tzero/tzero_growth.py +10 -10
  54. package/src/tzero/tzero_jarvis/agent_guard.py +16 -10
  55. package/src/tzero/tzero_jarvis/workspace_orchestrator.py +34 -23
  56. package/src/tzero/tzero_lsp.py +1 -1
  57. package/src/tzero/tzero_mcp.py +89 -31
  58. package/src/tzero/tzero_mutation.py +44 -16
  59. package/src/tzero/tzero_neural_cortex.py +1 -1
  60. package/src/tzero/tzero_pc_fixer.py +21 -3
  61. package/src/tzero/tzero_promo.py +196 -36
  62. package/src/tzero/tzero_rust_bridge.py +1086 -42
  63. package/src/tzero/tzero_scip.py +15 -2
  64. package/src/tzero/tzero_semantic_merge.py +34 -10
  65. package/src/tzero/tzero_task_benchmark.py +2 -2
  66. package/src/tzero/tzero_telemetry.py +146 -0
  67. package/src/tzero/tzero_terminal.py +366 -0
  68. package/src/tzero/tzero_traffic.py +350 -0
  69. package/src/tzero/tzero_tui.py +342 -133
  70. package/src/tzero/tzero_v3.py +652 -29
  71. package/src/tzero/tzero_welcome.py +72 -12
@@ -33,7 +33,7 @@ import ast
33
33
  import inspect
34
34
  import logging
35
35
 
36
- SERVER_VERSION = "11.15.2"
36
+ SERVER_VERSION = "12.2.0"
37
37
 
38
38
  # Version checks must not initialize the MCP SDK or dependency bootstrap. Besides
39
39
  # being needlessly expensive, that path may wait on package discovery/network
@@ -609,9 +609,9 @@ def create_mcp_server():
609
609
  "Generates a comprehensive system architecture specification document (ARCHITECTURE.md) with automated Mermaid topology diagrams, distinguishing from 'enforce_architecture_rules' and 'analyze_code_dependencies' by producing complete architectural documentation rather than validating boundary rules or tracing raw calls.\n"
610
610
  "\n"
611
611
  "Parameters:\n"
612
- "- `project_root`: Repository root directory path to analyze and document (default: current working directory).\n"
613
- "- `use_ai`: When False (default), generates 100% offline deterministic AST component topologies and Mermaid diagrams; when True, synthesizes natural language architectural narratives.\n"
614
- "- `model`: Optional AI model identifier override (e.g. 'claude-3-5-sonnet', 'gpt-4o') when use_ai is True; ignored in default offline AST mode.\n"
612
+ "- `project_root` (optional, default='.'): Repository root directory path to analyze and document (default: current working directory).\n"
613
+ "- `use_ai` (optional, default=False): When False (default: False), generates 100% offline deterministic AST component topologies and Mermaid diagrams; when True, synthesizes natural language architectural narratives.\n"
614
+ "- `model` (optional, default=''): Optional LLM model identifier string when use_ai is True; ignored in default offline AST mode.\n"
615
615
  "\n"
616
616
  "Behavior:\n"
617
617
  "- Mutability: Strictly read-only; returns formatted Markdown text without writing files to disk.\n"
@@ -952,9 +952,9 @@ def create_mcp_server():
952
952
  "Calculates exact token counts, comparative API billing costs across major model families, and cumulative financial ROI savings, distinguishing from 'build_project_context' and 'prune_code_snippet' by evaluating financial costs and token metrics rather than constructing context trees or pruning code.\n"
953
953
  "\n"
954
954
  "Parameters:\n"
955
- "- `text`: Raw text string, prompt payload, or code snippet to calculate token metrics and dollar costs for.\n"
956
- "- `project_root`: Directory path of the repository to calculate cumulative workspace token reduction and monthly financial ROI for.\n"
957
- "- `reduction_mode`: AST reduction tier ('ultra', 'balanced', 'none') applied when scanning project_root.\n"
955
+ "- `text` (optional, default=''): Raw text string, prompt payload, or code snippet to calculate token metrics and dollar costs for.\n"
956
+ "- `project_root` (optional, default='.'): Directory path of the repository to calculate cumulative workspace token reduction and monthly financial ROI for.\n"
957
+ "- `reduction_mode` (optional, default='ultra'): AST reduction tier ('ultra', 'balanced', 'none') applied when scanning project_root.\n"
958
958
  "\n"
959
959
  "Behavior:\n"
960
960
  "- Mutability: Strictly read-only; computes token counts and financial metrics without altering files or configurations.\n"
@@ -1031,12 +1031,12 @@ def create_mcp_server():
1031
1031
  name="analyze_change_impact",
1032
1032
  title="Calculate Symbol Modification Blast Radius",
1033
1033
  description=(
1034
- "Calculates the change blast radius score (0-100) and identifies downstream dependents before modifying or deleting a target symbol, distinguishing from 'analyze_code_dependencies' and 'audit_code_quality' by calculating targeted refactoring risk scores rather than mapping overall import graphs or profiling code complexity.\n"
1034
+ "Calculates the change blast radius score (0-100) and identifies downstream dependents before modifying or refactoring a target symbol, distinguishing from 'analyze_code_dependencies' and 'audit_code_quality' by calculating targeted refactoring risk scores rather than mapping overall import graphs or profiling code complexity.\n"
1035
1035
  "\n"
1036
1036
  "Parameters:\n"
1037
- "- `target_symbol`: Name of the function, class, or method scheduled for modification, renaming, or deletion.\n"
1038
- "- `project_root`: Root directory of the repository to trace dependent symbols across.\n"
1039
- "- `file_path`: Optional relative or absolute path of the file defining target_symbol to disambiguate overloaded or common names across modules.\n"
1037
+ "- `target_symbol` (required): Name of the function, class, or method scheduled for modification or refactoring.\n"
1038
+ "- `project_root` (optional, default='.'): Root directory of the repository to trace dependent symbols across.\n"
1039
+ "- `file_path` (optional, default=''): Optional relative or absolute path of the file defining target_symbol to disambiguate overloaded or common names across modules.\n"
1040
1040
  "\n"
1041
1041
  "Behavior:\n"
1042
1042
  "- Mutability: Strictly read-only; analyzes workspace dependency graphs without modifying disk state.\n"
@@ -1048,7 +1048,7 @@ def create_mcp_server():
1048
1048
  "- Error Handling: Gracefully reports score 0 and a helpful diagnostic notice if the specified symbol is not found in the codebase AST.\n"
1049
1049
  "\n"
1050
1050
  "Usage Guidelines:\n"
1051
- "- When to use: Run prior to editing, refactoring, or deleting a core function, interface, or shared utility to gauge downstream blast radius and identify required regression test targets.\n"
1051
+ "- When to use: Run prior to editing, refactoring, or updating a core function, interface, or shared utility to gauge downstream blast radius and identify required regression test targets.\n"
1052
1052
  "- When NOT to use: Do not use for whole-repository import dependency mapping or PageRank centrality (use 'analyze_code_dependencies' instead); do not use for checking static code smells and cyclomatic complexity (use 'audit_code_quality' instead).\n"
1053
1053
  "\n"
1054
1054
  "Returns: Markdown report with quantitative blast radius score (0-100), risk tier (LOW/MEDIUM/HIGH/CRITICAL), affected downstream modules, and test recommendations.\n"
@@ -1057,13 +1057,17 @@ def create_mcp_server():
1057
1057
  )
1058
1058
  def _legacy_analyze_change_impact(
1059
1059
  target_symbol: Annotated[str, Field(description="Name of the function, class, or method to analyze for change blast radius.")],
1060
- project_root: Annotated[str, Field(default=".", description="Workspace root directory containing target symbols (default: current directory).")] = "."
1060
+ project_root: Annotated[str, Field(default=".", description="Workspace root directory containing target symbols (default: current directory).")] = ".",
1061
+ file_path: Annotated[str, Field(default="", description="Optional file path to disambiguate target symbol.")] = ""
1061
1062
  ) -> str:
1062
1063
  """Traces symbol references, inbound dependents, and calculates blast radius score."""
1063
1064
  from tzero.tzero_features import ChangeImpactAnalyzer
1064
1065
  analyzer = ChangeImpactAnalyzer(project_root)
1065
1066
  analysis = analyzer.analyze_symbol(target_symbol)
1066
- return analyzer.format_report(analysis)
1067
+ res = analyzer.format_report(analysis)
1068
+ if file_path:
1069
+ return f"*(Focus file: `{file_path}`)*\n\n{res}"
1070
+ return res
1067
1071
 
1068
1072
  # -------------------------------------------------------------------------
1069
1073
  # TOOL 10: enforce_architecture_boundaries
@@ -1317,9 +1321,9 @@ def create_mcp_server():
1317
1321
  "Prunes implementation bodies from in-memory source code strings, API schemas, or unified diffs while preserving type signatures and AST interfaces, distinguishing from 'build_project_context' and 'audit_code_quality' by stripping bodies from memory buffers rather than scanning disk files or checking code smells.\n"
1318
1322
  "\n"
1319
1323
  "Parameters:\n"
1320
- "- `code`: Raw source code string, OpenAPI/JSON schema, or git diff text buffer to compress in memory.\n"
1321
- "- `file_path_or_ext`: File name or extension (e.g. 'service.ts', '.go', '.rs', 'schema.json') used to select the language-specific AST parser; defaults to Python grammar.\n"
1322
- "- `reduction_mode`: Pruning strategy: 'ultra' preserves class/function signatures, argument types, and docstrings; 'balanced' retains signatures and branch control headers; 'micro_patch' surgically compacts unified diff blocks down to changed AST symbols.\n"
1324
+ "- `code` (required): Raw source code string, OpenAPI/JSON schema, or git diff text buffer to compress in memory.\n"
1325
+ "- `file_path_or_ext` (optional, default='snippet.py'): File name or extension (e.g. 'service.ts', '.go', '.rs', 'schema.json') used to select the language-specific AST parser; defaults to Python grammar.\n"
1326
+ "- `reduction_mode` (optional, default='ultra'): Pruning strategy: 'ultra' preserves class/function signatures, argument types, and docstrings; 'balanced' retains signatures and branch control headers; 'micro_patch' surgically compacts unified diff blocks down to changed AST symbols.\n"
1323
1327
  "\n"
1324
1328
  "Behavior:\n"
1325
1329
  "- Mutability: Strictly read-only; processes in-memory string buffers with zero filesystem access or disk writes.\n"
@@ -4258,7 +4262,7 @@ def create_mcp_server():
4258
4262
  "\n"
4259
4263
  "Parameters:\n"
4260
4264
  "- `workspace_dir` (str, optional, default='.'): Target repository root directory containing source code and environment configurations to diagnose.\n"
4261
- "- `auto_repair` (bool, optional, default=True): When True, applies surgical AST syntax patches, BOM sanitization, and cache purges to disk.\n"
4265
+ "- `auto_repair` (bool, optional, default=True): When True, applies surgical AST syntax patches, BOM sanitization, and cache cleanup to disk.\n"
4262
4266
  "- `dry_run` (bool, optional, default=False): When True, evaluates diagnostics and previews repair diffs without modifying files on disk.\n"
4263
4267
  "\n"
4264
4268
  "Behavior:\n"
@@ -4271,7 +4275,7 @@ def create_mcp_server():
4271
4275
  "- Error Handling: Continues diagnostic sweep across entire workspace if individual files contain unrecoverable binary corruption.\n"
4272
4276
  "\n"
4273
4277
  "Usage Guidelines:\n"
4274
- "- When to use: Use when diagnosing overall workspace health, repairing Python syntax breakages (missing colons, Python 2 print), resolving missing standard imports, fixing virtualenv paths, or purging stale cache bloat.\n"
4278
+ "- When to use: Use when diagnosing overall workspace health, repairing Python syntax breakages (missing colons, Python 2 print), resolving missing standard imports, fixing virtualenv paths, or clearing stale cache bloat.\n"
4275
4279
  "- When NOT to use: Do not use for repairing hallucinated LLM method names in isolated code snippets (use 'heal_hallucinated_code' instead); do not use for static cyclomatic complexity code smell audits (use 'audit_code_quality' instead).\n"
4276
4280
  "\n"
4277
4281
  "Returns: Formatted Markdown report detailing initial health score, detected defects, surgical patch actions, and final post-healing health score."
@@ -4367,10 +4371,10 @@ def create_mcp_server():
4367
4371
  "Compatibility router for combined reports, distinguishing from 'build_project_context' and 'audit_code_quality' by combining analyses when action='auto'; for individual tasks use the dedicated tools directly.\n"
4368
4372
  "\n"
4369
4373
  "Parameters:\n"
4370
- "- `action`: Workflow operation: 'auto' runs comprehensive all-in-one audit & context pipeline; 'context' builds AST context tree; 'audit' checks code quality & smells; 'security' runs Zero-Leak secret scan; 'blueprint' generates Mermaid architecture; 'dependencies' maps import topology; 'impact' evaluates blast radius of modified symbols; 'search' performs hybrid BM25 code search; 'prune' strips in-memory AST bodies; 'heal' runs AST self-healing; 'memory' manages episodic memory; 'swarm' coordinates multi-agent consensus.\n"
4371
- "- `target`: Target repository root path, file path, git diff text buffer, or raw source code snippet to process.\n"
4372
- "- `query`: Free-text search term, focus symbol name, or goal prompt depending on selected action.\n"
4373
- "- `options`: Optional JSON string specifying extra configuration parameters (e.g. {\"reduction_mode\": \"ultra\", \"max_tokens\": 32000, \"depth\": 4}).\n"
4374
+ "- `action` (optional, default='auto'): Workflow operation: 'auto' runs comprehensive all-in-one audit & context pipeline; 'context' builds AST context tree; 'audit' checks code quality & smells; 'security' runs Zero-Leak secret scan; 'blueprint' generates Mermaid architecture; 'dependencies' maps import topology; 'impact' evaluates blast radius of modified symbols; 'search' performs hybrid BM25 code search; 'prune' strips in-memory AST bodies; 'heal' runs AST self-healing; 'memory' manages episodic memory; 'swarm' coordinates multi-agent consensus.\n"
4375
+ "- `target` (optional, default='.'): Target repository root path, file path, git diff text buffer, or raw source code snippet to process.\n"
4376
+ "- `query` (optional, default=''): Free-text search term, focus symbol name, or goal prompt depending on selected action.\n"
4377
+ "- `options` (optional, default=''): Optional JSON string specifying extra configuration parameters (e.g. {\"reduction_mode\": \"ultra\", \"max_tokens\": 32000, \"depth\": 4}).\n"
4374
4378
  "\n"
4375
4379
  "Behavior:\n"
4376
4380
  "- Mutability: Depends on action and options. Security may install hooks; rules, memory, sync, healing, merge, and generated tests can modify files.\n"
@@ -4741,7 +4745,7 @@ def create_mcp_server():
4741
4745
  sig = inspect.signature(handler)
4742
4746
  kwargs = {}
4743
4747
  for p_name in sig.parameters:
4744
- if p_name in ("project_root", "target_dir", "code_snippet", "diff_content"):
4748
+ if p_name in ("project_root", "target_dir", "target", "target_path", "code_snippet", "diff_content"):
4745
4749
  kwargs[p_name] = target
4746
4750
  elif p_name in ("query", "symbol_name", "goal", "prompt"):
4747
4751
  kwargs[p_name] = query or target
@@ -4755,7 +4759,8 @@ def create_mcp_server():
4755
4759
  f"❌ Unknown action '{act}'.\n"
4756
4760
  f"Supported actions: 'auto', 'context', 'audit', 'security', 'blueprint', 'dependencies', "
4757
4761
  f"'impact', 'search', 'prune', 'rules', 'enforce', 'cost', 'memory', 'swarm', 'heal', 'design', "
4758
- f"'patch', 'pagerank', 'dead_code', 'duplicity', 'call_chain', 'sync', 'roi', 'drift', 'ci', 'local_ci'."
4762
+ f"'patch', 'pagerank', 'dead_code', 'duplicity', 'call_chain', 'sync', 'roi', 'drift', 'ci', 'local_ci', "
4763
+ f"'armor', 'anti_rea', 'audit_rea'."
4759
4764
  )
4760
4765
 
4761
4766
  def run_local_ci(quick: bool = False, auto_fix: bool = False, install_hook: bool = False, uninstall_hook: bool = False, project_root: str = ".") -> str:
@@ -4778,9 +4783,63 @@ def create_mcp_server():
4778
4783
  + "\n".join([f"- [{'PASS' if s.passed else 'FAIL'}] **{s.name}** ({s.duration:.2f}s): {s.output or s.error}" for s in report.steps])
4779
4784
  )
4780
4785
 
4786
+ def armor_against_ai_reverse_engineering(target: str = ".", output_path: str = "") -> str:
4787
+ """Applies military-grade Anti-REA code and binary protection against AI reverse-engineering agents."""
4788
+ from tzero.tzero_armor import protect_path_with_armor
4789
+ res = protect_path_with_armor(target, output_path=output_path or None)
4790
+ if not res.get("success"):
4791
+ return f"❌ Anti-REA protection failed: {res.get('error', 'Unknown error')}"
4792
+
4793
+ if "score_after" in res:
4794
+ return (
4795
+ f"### 🛡️ T-Zero Anti-REA Military Armor Report\n"
4796
+ f"- **Target File:** `{res['output_file']}`\n"
4797
+ f"- **AI Resistance Score:** `{res['score_before']}/100` ➔ `{res['score_after']}/100`\n"
4798
+ f"- **Rating:** `{res['rating']}`\n"
4799
+ f"- **Status:** `ACTIVE` (Protected against morluto/rea, Ghidra MCP, pyinstxtractor)\n"
4800
+ )
4801
+ elif "files_protected" in res:
4802
+ return (
4803
+ f"### 🛡️ T-Zero Anti-REA Codebase Armor Report\n"
4804
+ f"- **Directory:** `{res['directory']}`\n"
4805
+ f"- **Files Protected:** `{res['files_protected']}`\n"
4806
+ f"- **Status:** `ACTIVE` (All Python modules hardened with Anti-REA defense matrix)\n"
4807
+ )
4808
+ return json.dumps(res, indent=2)
4809
+
4810
+ def audit_ai_decompilation_resistance(target: str = ".") -> str:
4811
+ """Audits target code or binary for resistance against AI reverse engineering (0-100 score)."""
4812
+ from tzero.tzero_armor import audit_path_rea_resistance
4813
+ audit = audit_path_rea_resistance(target)
4814
+ if not audit.get("success", True):
4815
+ return f"❌ Audit failed: {audit.get('error', 'Unknown error')}"
4816
+
4817
+ report = [
4818
+ f"### 🛡️ AI Reverse-Engineering Resistance Audit (TDQS-REA)",
4819
+ f"- **Target:** `{target}`",
4820
+ f"- **Resistance Score:** `{audit.get('score', 0)} / 100` (`{audit.get('rating', 'UNKNOWN')}`)",
4821
+ f"- **Status:** `{audit.get('status', 'N/A')}`\n",
4822
+ f"#### Active Defenses:",
4823
+ ]
4824
+ for k, v in audit.get("defenses_active", {}).items():
4825
+ report.append(f"- [{'✔' if v else ' '}] **{k}**")
4826
+
4827
+ recs = audit.get("sample_findings") or audit.get("findings", [])
4828
+ if recs:
4829
+ report.append("\n#### Hardening Recommendations:")
4830
+ for r in recs:
4831
+ report.append(f"- ⚠️ {r}")
4832
+
4833
+ return "\n".join(report)
4834
+
4781
4835
  # Register canonical mappings
4782
4836
  _CANONICAL_DISPATCH['execute_codebase_workflow'] = execute_codebase_workflow
4783
4837
  _CANONICAL_DISPATCH['run_codebase_autopilot'] = execute_codebase_workflow
4838
+ _CANONICAL_DISPATCH['armor_against_ai_reverse_engineering'] = armor_against_ai_reverse_engineering
4839
+ _CANONICAL_DISPATCH['armor'] = armor_against_ai_reverse_engineering
4840
+ _CANONICAL_DISPATCH['anti_rea'] = armor_against_ai_reverse_engineering
4841
+ _CANONICAL_DISPATCH['audit_ai_decompilation_resistance'] = audit_ai_decompilation_resistance
4842
+ _CANONICAL_DISPATCH['audit_rea'] = audit_ai_decompilation_resistance
4784
4843
  _CANONICAL_DISPATCH['build_project_context'] = build_project_context
4785
4844
  _CANONICAL_DISPATCH['prune_code_snippet'] = prune_code_snippet
4786
4845
  _CANONICAL_DISPATCH['manage_architecture_rules'] = manage_architecture_rules
@@ -4815,12 +4874,11 @@ def create_mcp_server():
4815
4874
  name="search_tools",
4816
4875
  title="Progressive T-Zero MCP Tool Discovery Catalog",
4817
4876
  description=(
4818
- "Progressively discover and search registered T-Zero tools by keyword or domain category rather than loading all 58 schemas at once "
4819
- "(unlike codebase searches; use 'search_codebase' for searching repository source files instead).\n\n"
4877
+ "Progressively discover and search registered T-Zero tools by keyword or domain category rather than loading all schemas at once, distinguishing from 'search_codebase' by discovering server tools and capabilities rather than searching repository source files.\n\n"
4820
4878
  "Parameters:\n"
4821
- "- `query`: Optional keyword query (e.g., 'secret audit', 'pagerank', 'diff', 'merge').\n"
4822
- "- `category`: Domain filter (`all`, `context`, `security`, `ast`, `memory`, `swarm`, `design`).\n"
4823
- "- `limit`: Maximum tool entries returned (integer 1-30; defaults to 10).\n\n"
4879
+ "- `query` (optional, default=''): Optional keyword query (e.g., 'secret audit', 'pagerank', 'diff', 'merge').\n"
4880
+ "- `category` (optional, default='all'): Domain filter category: 'all', 'context', 'security', 'ast', 'memory', 'swarm', 'design'.\n"
4881
+ "- `limit` (optional, default=10): Maximum tool entries returned (integer 1-30; default: 10).\n\n"
4824
4882
  "Behavior:\n"
4825
4883
  "- Mutability & Speed: Read-only, idempotent catalog lookup executing in <5ms.\n"
4826
4884
  "- Auth & Boundaries: Zero authentication, external credentials, or network access required.\n\n"
@@ -4851,7 +4909,7 @@ def create_mcp_server():
4851
4909
 
4852
4910
  def _classify(t_name: str, summary: str) -> str:
4853
4911
  blob = f"{t_name} {summary}".lower()
4854
- if any(k in blob for k in ("secret", "leak", "hallucinat", "guard", "security", "audit", "contract", "arch")):
4912
+ if any(k in blob for k in ("secret", "leak", "hallucinat", "guard", "security", "audit", "contract", "arch", "armor", "anti-rea", "anti_rea", "shield", "decompil")):
4855
4913
  return "security"
4856
4914
  if any(k in blob for k in ("jarvis", "memory", "graph", "minhash", "latent", "causal")):
4857
4915
  return "memory"
@@ -17,6 +17,7 @@ Part of T-Zero Context Architect v10.8.0 Master Edition.
17
17
  import ast
18
18
  import copy
19
19
  import os
20
+ import shlex
20
21
  import subprocess
21
22
  import sys
22
23
  import tempfile
@@ -211,6 +212,17 @@ class ASTMutationEngine:
211
212
 
212
213
  return mutants
213
214
 
215
+ @staticmethod
216
+ def _sanitize_target_path(target_path: str) -> str:
217
+ if not target_path or "\x00" in target_path:
218
+ raise ValueError("Invalid target path.")
219
+ ws_root = os.path.realpath(".")
220
+ tmp_root = os.path.realpath(tempfile.gettempdir())
221
+ real_target = os.path.normpath(os.path.realpath(os.path.abspath(target_path)))
222
+ if not real_target.startswith(ws_root + os.sep) and not real_target.startswith(tmp_root + os.sep):
223
+ raise ValueError(f"Path outside allowed workspace or temp scope: {target_path}")
224
+ return real_target
225
+
214
226
  @classmethod
215
227
  def run_mutation_analysis(
216
228
  cls,
@@ -221,7 +233,7 @@ class ASTMutationEngine:
221
233
  ) -> MutationReport:
222
234
  """Executes full mutation testing on target_file against test_command."""
223
235
  start_time = time.time()
224
- abs_target = os.path.abspath(target_file)
236
+ abs_target = cls._sanitize_target_path(target_file)
225
237
  if not os.path.isfile(abs_target):
226
238
  raise FileNotFoundError(f"Target file not found: {target_file}")
227
239
 
@@ -242,31 +254,47 @@ class ASTMutationEngine:
242
254
  mutants=[]
243
255
  )
244
256
 
245
- # Infer test command if not provided
257
+ # Build argv safely without shell=True
246
258
  if not test_command:
247
- base_name = os.path.splitext(os.path.basename(target_file))[0]
248
- # Check for candidate test file
249
- candidate_test = os.path.join(os.path.dirname(abs_target), "tests", f"test_{base_name}.py")
250
- if not os.path.isfile(candidate_test):
251
- candidate_test = os.path.join(".", "tests", f"test_{base_name}.py")
252
-
253
- if os.path.isfile(candidate_test):
254
- test_command = f"{sys.executable} -m unittest {candidate_test}"
259
+ base_name = os.path.splitext(os.path.basename(abs_target))[0]
260
+ candidate_a = os.path.join(os.path.dirname(abs_target), "tests", f"test_{base_name}.py")
261
+ candidate_b = os.path.realpath(os.path.join(".", "tests", f"test_{base_name}.py"))
262
+ if os.path.isfile(candidate_a):
263
+ test_cmd_args = [sys.executable, "-m", "unittest", candidate_a]
264
+ elif os.path.isfile(candidate_b):
265
+ test_cmd_args = [sys.executable, "-m", "unittest", candidate_b]
266
+ else:
267
+ test_cmd_args = [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-p", "test_*.py"]
268
+ else:
269
+ if any(tok in test_command for tok in (";", "&&", "||", "|", "`", "$(", ">", "<", "\n", "\r")):
270
+ raise ValueError("Unsafe shell metacharacters detected in test_command.")
271
+ parsed_args = [
272
+ tok.strip('"').strip("'")
273
+ for tok in shlex.split(test_command, posix=(os.name != "nt"))
274
+ if tok.strip()
275
+ ]
276
+ if not parsed_args:
277
+ raise ValueError("Empty test_command.")
278
+ bin_name = os.path.basename(parsed_args[0]).lower()
279
+ if bin_name.startswith("python"):
280
+ test_cmd_args = [sys.executable] + parsed_args[1:]
281
+ elif bin_name in ("pytest", "pytest.exe"):
282
+ test_cmd_args = [sys.executable, "-m", "pytest"] + parsed_args[1:]
255
283
  else:
256
- test_command = f"{sys.executable} -m unittest discover -s tests -p 'test_*.py'"
284
+ raise ValueError(f"Unsupported test runner executable: {parsed_args[0]}")
257
285
 
258
286
  killed = 0
259
287
  survived = 0
260
288
  timeouts = 0
261
289
  errors = 0
262
290
 
263
- # Backup original content
264
- backup_path = abs_target + ".tzero_mut_bak"
291
+ target_dir = os.path.dirname(abs_target)
292
+ safe_bak_name = os.path.basename(abs_target) + ".tzero_mut_bak"
293
+ backup_path = os.path.join(target_dir, safe_bak_name)
265
294
  with open(backup_path, "w", encoding="utf-8") as f:
266
295
  f.write(original_code)
267
296
 
268
297
  env = os.environ.copy()
269
- target_dir = os.path.dirname(abs_target)
270
298
  existing_pythonpath = env.get("PYTHONPATH", "")
271
299
  env["PYTHONPATH"] = f"{target_dir}{os.pathsep}{existing_pythonpath}" if existing_pythonpath else target_dir
272
300
 
@@ -278,8 +306,8 @@ class ASTMutationEngine:
278
306
 
279
307
  try:
280
308
  proc = subprocess.run(
281
- test_command,
282
- shell=True,
309
+ test_cmd_args,
310
+ shell=False,
283
311
  capture_output=True,
284
312
  text=True,
285
313
  timeout=timeout_seconds,
@@ -1244,7 +1244,7 @@ name: {role_clean}
1244
1244
  description: Autonomous T-Zero Subagent specialized in {task}
1245
1245
  ---
1246
1246
 
1247
- # 🤖 Subagent Persona: {role}
1247
+ # Subagent Persona: {role}
1248
1248
  **Mission Objective:** {task}
1249
1249
  **Context Tier:** {tier_level} (Ultra-compact AST Signatures)
1250
1250
  **Security Rating:** 100% Zero-Leak Certified
@@ -6109,10 +6109,28 @@ class SecurityZeroLeakDoctor:
6109
6109
  with open(p, "w", encoding="utf-8", newline="\n") as f:
6110
6110
  f.writelines(lines)
6111
6111
 
6112
- # Append to .env safely
6113
- env_entry = f"{env_var}={raw_sec}\n"
6112
+ # Store secret in OS keyring when available and write non-sensitive .env stub
6113
+ stored_in_keyring = False
6114
+ try:
6115
+ import keyring # type: ignore
6116
+ keyring.set_password("tzero-vault", env_var, raw_sec)
6117
+ stored_in_keyring = True
6118
+ except Exception:
6119
+ pass
6120
+
6121
+ stub_note = (
6122
+ f"# {env_var} stored in OS Keyring service 'tzero-vault'\n"
6123
+ if stored_in_keyring
6124
+ else f"# {env_var} migrated from source — populate securely\n"
6125
+ )
6126
+ env_stub = f"{stub_note}{env_var}=\n"
6114
6127
  with open(env_file, "a", encoding="utf-8") as ef:
6115
- ef.write(env_entry)
6128
+ ef.write(env_stub)
6129
+ if os.name != "nt":
6130
+ try:
6131
+ os.chmod(env_file, 0o600)
6132
+ except OSError:
6133
+ pass
6116
6134
 
6117
6135
  actions.append(HealAction(
6118
6136
  category=DiagnosticCategory.SECURITY.value,