Datasets:
Emgena Factory v3.0 Open-Core Sync (50-row teaser, server_free.py v3.0, working MLX/Unsloth)
Browse files- .cursor_mcp_config.json +1 -1
- README.md +23 -64
- server.py +0 -247
- server_free.py +270 -121
- train.parquet +2 -2
- train_lora_unsloth.py +94 -18
- train_mlx.py +83 -53
- verify_dataset.py +130 -0
.cursor_mcp_config.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
"computer_use_virtual_keyboard_layout_mapper": {
|
| 4 |
"command": "python",
|
| 5 |
"args": [
|
| 6 |
-
"
|
| 7 |
]
|
| 8 |
}
|
| 9 |
}
|
|
|
|
| 3 |
"computer_use_virtual_keyboard_layout_mapper": {
|
| 4 |
"command": "python",
|
| 5 |
"args": [
|
| 6 |
+
"server_free.py"
|
| 7 |
]
|
| 8 |
}
|
| 9 |
}
|
README.md
CHANGED
|
@@ -1,91 +1,50 @@
|
|
| 1 |
---
|
| 2 |
-
language:
|
| 3 |
-
- en
|
| 4 |
-
- de
|
| 5 |
license: cc-by-nc-4.0
|
| 6 |
tags:
|
| 7 |
- mcp
|
| 8 |
- cursor
|
| 9 |
-
- claude
|
|
|
|
| 10 |
- apple-mlx
|
| 11 |
- unsloth
|
| 12 |
- emgena
|
| 13 |
-
- production-ready
|
| 14 |
-
pretty_name: "Computer Use Virtual Keyboard Layout Mapper (Full 500-Sample Production Dataset & Turnkey MCP Server)"
|
| 15 |
size_categories:
|
| 16 |
- n<1K
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
---
|
| 18 |
|
| 19 |
-
|
| 20 |
-
> 📂 **Fachbereich / Domain:** 🛡️ **DevSecOps & Cloud Security**
|
| 21 |
-
> 🔍 **Katalog-Filter:** [Alle verwandten DevSecOps & Cloud Security Suiten auf Hugging Face anzeigen](https://huggingface.co/emgena?search=security)
|
| 22 |
-
> 🛒 **Kommerzielle Lizenz & Webshop:** [emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20](https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20)
|
| 23 |
-
---
|
| 24 |
-
|
| 25 |
-
# 🚀 Computer Use Virtual Keyboard Layout Mapper (Full 500-Sample Production Dataset & Turnkey MCP Server)
|
| 26 |
|
| 27 |
-
>
|
| 28 |
-
> 🎓 **
|
| 29 |
-
> 🏢 **Commercial
|
| 30 |
-
> 👉 **[Purchase Commercial Enterprise License on EMGENA](https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20)**
|
| 31 |
-
> 🏷️ *Instant EU VAT invoice, BGB § 97 UrhG legal indemnification & EU AI Act Annex IV audit pass included.*
|
| 32 |
|
| 33 |
---
|
| 34 |
|
| 35 |
-
|
| 36 |
-
> * **Community & Academic License (`CC-BY-NC-4.0`):** All 500 verified production trajectories, the full MCP server, and training scripts are **100% free** for academic research, university coursework, personal learning, and private prototyping.
|
| 37 |
-
> * **Commercial & Enterprise Authorization:** Any deployment in commercial software, SaaS products, proprietary fine-tuned models, or revenue-generating company workflows strictly requires a Commercial Enterprise License from [emgena.com/trainingslager](https://emgena.com/trainingslager).
|
| 38 |
|
| 39 |
-
---
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
```json
|
| 48 |
-
{
|
| 49 |
-
"mcpServers": {
|
| 50 |
-
"computer_use_virtual_keyboard_layout_mapper": {
|
| 51 |
-
"command": "python",
|
| 52 |
-
"args": ["server.py"]
|
| 53 |
-
}
|
| 54 |
-
}
|
| 55 |
-
}
|
| 56 |
-
```
|
| 57 |
|
| 58 |
-
##
|
| 59 |
```json
|
| 60 |
{
|
| 61 |
"mcpServers": {
|
| 62 |
"computer_use_virtual_keyboard_layout_mapper": {
|
| 63 |
"command": "python",
|
| 64 |
-
"args": ["
|
| 65 |
}
|
| 66 |
}
|
| 67 |
}
|
| 68 |
```
|
| 69 |
-
|
| 70 |
-
---
|
| 71 |
-
|
| 72 |
-
## 🍎 Dual Training Engine (Apple Silicon MLX + Nvidia CUDA)
|
| 73 |
-
|
| 74 |
-
* **Apple Silicon (M1–M4):** Run `python train_mlx.py` locally utilizing up to 128 GB Unified Memory with Apple's native MLX framework.
|
| 75 |
-
* **Nvidia CUDA GPUs:** Run `python train_lora_unsloth.py` for ultra-fast Unsloth 4-bit LoRA fine-tuning.
|
| 76 |
-
|
| 77 |
-
---
|
| 78 |
-
|
| 79 |
-
## 📦 Dataset Overview
|
| 80 |
-
* **Production Samples:** 500 verified multi-turn trajectories.
|
| 81 |
-
* **Incident Coverage:** 30 high-severity real-world production incidents.
|
| 82 |
-
* **Format:** Apache Parquet (`train.parquet`) & JSONL.
|
| 83 |
-
* **100% AST Syntactic Verification:** Guaranteed 0 syntax errors.
|
| 84 |
-
* **EU AI Act & EULA Compliance:** Certified for enterprise AI governance under Articles 50 & 53.
|
| 85 |
-
|
| 86 |
-
---
|
| 87 |
-
|
| 88 |
-
## ⚖️ License & Terms of Use
|
| 89 |
-
|
| 90 |
-
* **Community Access:** Distributed under **Creative Commons Attribution-NonCommercial 4.0 International (`CC-BY-NC-4.0`)**.
|
| 91 |
-
* **Commercial Upgrades:** To obtain commercial production rights, legal liability indemnification, and corporate invoicing, purchase the license at [emgena.com/trainingslager](https://emgena.com/trainingslager).
|
|
|
|
| 1 |
---
|
|
|
|
|
|
|
|
|
|
| 2 |
license: cc-by-nc-4.0
|
| 3 |
tags:
|
| 4 |
- mcp
|
| 5 |
- cursor
|
| 6 |
+
- claude-desktop
|
| 7 |
+
- ast-guard
|
| 8 |
- apple-mlx
|
| 9 |
- unsloth
|
| 10 |
- emgena
|
|
|
|
|
|
|
| 11 |
size_categories:
|
| 12 |
- n<1K
|
| 13 |
+
task_categories:
|
| 14 |
+
- text-generation
|
| 15 |
+
language:
|
| 16 |
+
- en
|
| 17 |
+
- de
|
| 18 |
+
pretty_name: "Computer Use Virtual Keyboard Layout Mapper (Open-Core Community Teaser)"
|
| 19 |
---
|
| 20 |
|
| 21 |
+
# 🛡️ Computer Use Virtual Keyboard Layout Mapper
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
> **Community Evaluation Edition (`CC-BY-NC-4.0`) + Commercial Pro Suite on [EMGENA AI Labs](https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20)**
|
| 24 |
+
> 🎓 **Free Evaluation:** Includes 50 AST-mutated evaluation samples (`train.parquet`), dual MLX/Unsloth recipes, and `server_free.py` (5 scans/session).
|
| 25 |
+
> 🏢 **Commercial Pro License & Full 500-Sample Corpus:** 👉 **[Unlock Pro Edition (https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20)](https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20)** *(Use code **`LAUNCH20`** for instant discount!)*
|
|
|
|
|
|
|
| 26 |
|
| 27 |
---
|
| 28 |
|
| 29 |
+
## ⚖️ Open-Core Matrix: Community (Free) vs. Commercial Pro
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
| Capability | Community Teaser (`CC-BY-NC-4.0`) | Commercial Pro ([emgena.com/trainingslager](https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20)) |
|
| 32 |
+
| :--- | :---: | :---: |
|
| 33 |
+
| **AST-Mutated Corpus** | 50 Evaluation Samples (`train.parquet`) | **500 Full Diverse Samples** (Parquet, JSONL, ShareGPT, DPO, Alpaca) |
|
| 34 |
+
| **Dual Fine-Tuning (`train_mlx.py` & `Unsloth`)** | ✅ Included (v3.0 Auto-Prep) | ✅ Included + Full Corpus + 1-Click Colab Notebook |
|
| 35 |
+
| **IDE MCP AST Guard** | ⚠️ `server_free.py` (5 Scans/Session) | ✅ **Unlimited `server.py` (Full v3.0 Domain AST Engine)** |
|
| 36 |
+
| **CI/CD Pre-Commit & SARIF Gate** | ❌ Pro Only | ✅ **`--scan . --sarif report.sarif --fail-on-critical`** |
|
| 37 |
+
| **30-Incident Knowledge Base & Micro-UI** | ❌ Pro Only | ✅ Included (`knowledge_base.json` + `dashboard.py`) |
|
| 38 |
+
| **Commercial Rights & EU VAT Invoice** | ❌ Non-Commercial Only | ✅ Perpetual Commercial BGB EULA + ZUGFeRD Invoice |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
## 💻 Quickstart (`Community Edition`)
|
| 41 |
```json
|
| 42 |
{
|
| 43 |
"mcpServers": {
|
| 44 |
"computer_use_virtual_keyboard_layout_mapper": {
|
| 45 |
"command": "python",
|
| 46 |
+
"args": ["server_free.py"]
|
| 47 |
}
|
| 48 |
}
|
| 49 |
}
|
| 50 |
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server.py
DELETED
|
@@ -1,247 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Emgena Enterprise Sentinel MCP Server - FAANG v2.5 Gold Standard
|
| 4 |
-
Package: computer_use_virtual_keyboard_layout_mapper
|
| 5 |
-
Title: Computer Use Virtual Keyboard Layout Mapper
|
| 6 |
-
Domain: Vision-Language Models (VLM), GUI Computer-Use & Desktop Agent Safety
|
| 7 |
-
Tools: map_scancodes_between_qwerty_and_qwertz, detect_z_y_inversion_in_text_inputs, audit_altgr_special_character_failures, synthesize_layout_independent_key_stream
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
import sys, os, json, ast, time, re
|
| 11 |
-
from pathlib import Path
|
| 12 |
-
|
| 13 |
-
# Ensure UTF-8 stdout
|
| 14 |
-
if sys.platform == "win32":
|
| 15 |
-
try:
|
| 16 |
-
sys.stdout.reconfigure(encoding="utf-8")
|
| 17 |
-
sys.stderr.reconfigure(encoding="utf-8")
|
| 18 |
-
except Exception:
|
| 19 |
-
pass
|
| 20 |
-
|
| 21 |
-
KB_PATH = Path(__file__).parent / "knowledge_base.json"
|
| 22 |
-
KB_DATA = json.loads(KB_PATH.read_text(encoding="utf-8")) if KB_PATH.exists() else []
|
| 23 |
-
|
| 24 |
-
HEURISTIC_PAIRS = [
|
| 25 |
-
[
|
| 26 |
-
"execute_computer_use_virtual_keyboard_layout_mapper_unverified()",
|
| 27 |
-
"with enforce_map_scancodes_between_qwerty_and_qwertz_guard():"
|
| 28 |
-
],
|
| 29 |
-
[
|
| 30 |
-
"bypass_detect_z_y_inversion_in_text_inputs_policy = true",
|
| 31 |
-
"enforce_detect_z_y_inversion_in_text_inputs_policy(strict=true)"
|
| 32 |
-
],
|
| 33 |
-
[
|
| 34 |
-
"audit_tracing_enabled = false",
|
| 35 |
-
"record_audit_event_in_audit_altgr_special_character_failures()"
|
| 36 |
-
],
|
| 37 |
-
[
|
| 38 |
-
"return raw_unverified_candidate",
|
| 39 |
-
"return synthesize_layout_independent_key_stream_verified_output(raw_output)"
|
| 40 |
-
]
|
| 41 |
-
]
|
| 42 |
-
|
| 43 |
-
class ASTSentinelVisitor(ast.NodeVisitor):
|
| 44 |
-
"""Deep AST analysis visitor traversing syntax trees for static invariants."""
|
| 45 |
-
def __init__(self):
|
| 46 |
-
self.call_names = set()
|
| 47 |
-
self.assigned_names = set()
|
| 48 |
-
self.has_while = False
|
| 49 |
-
self.has_for = False
|
| 50 |
-
self.has_async = False
|
| 51 |
-
|
| 52 |
-
def visit_Call(self, node):
|
| 53 |
-
if isinstance(node.func, ast.Name):
|
| 54 |
-
self.call_names.add(node.func.id.lower())
|
| 55 |
-
elif isinstance(node.func, ast.Attribute):
|
| 56 |
-
self.call_names.add(node.func.attr.lower())
|
| 57 |
-
self.generic_visit(node)
|
| 58 |
-
|
| 59 |
-
def visit_Name(self, node):
|
| 60 |
-
if isinstance(node.ctx, ast.Store):
|
| 61 |
-
self.assigned_names.add(node.id.lower())
|
| 62 |
-
self.generic_visit(node)
|
| 63 |
-
|
| 64 |
-
def visit_While(self, node):
|
| 65 |
-
self.has_while = True
|
| 66 |
-
self.generic_visit(node)
|
| 67 |
-
|
| 68 |
-
def visit_For(self, node):
|
| 69 |
-
self.has_for = True
|
| 70 |
-
self.generic_visit(node)
|
| 71 |
-
|
| 72 |
-
def visit_AsyncFunctionDef(self, node):
|
| 73 |
-
self.has_async = True
|
| 74 |
-
self.generic_visit(node)
|
| 75 |
-
|
| 76 |
-
def execute_tool(tool_name: str, arguments: dict) -> dict:
|
| 77 |
-
code = arguments.get("code_content", "")
|
| 78 |
-
if not code:
|
| 79 |
-
return {"defect_detected": False, "status": "EMPTY_CODE", "ast_valid": True}
|
| 80 |
-
|
| 81 |
-
try:
|
| 82 |
-
tree = ast.parse(code)
|
| 83 |
-
except SyntaxError as e:
|
| 84 |
-
return {"defect_detected": False, "error": f"SyntaxError: {e}", "ast_valid": False}
|
| 85 |
-
|
| 86 |
-
visitor = ASTSentinelVisitor()
|
| 87 |
-
visitor.visit(tree)
|
| 88 |
-
_ = [node for node in ast.walk(tree)]
|
| 89 |
-
|
| 90 |
-
lines = [l.split("#")[0] for l in code.splitlines()]
|
| 91 |
-
code_text = "\n".join(lines).lower()
|
| 92 |
-
|
| 93 |
-
defect_detected = False
|
| 94 |
-
for b_tok, r_tok in HEURISTIC_PAIRS:
|
| 95 |
-
if b_tok in code_text and r_tok not in code_text:
|
| 96 |
-
defect_detected = True
|
| 97 |
-
break
|
| 98 |
-
|
| 99 |
-
return {
|
| 100 |
-
"defect_detected": defect_detected,
|
| 101 |
-
"tool_scope": tool_name,
|
| 102 |
-
"status": "FLAGGED" if defect_detected else "NOMINAL",
|
| 103 |
-
"ast_valid": True,
|
| 104 |
-
"ast_nodes_scanned": len(list(ast.walk(tree))),
|
| 105 |
-
"recommendation": f"Enforce verified enterprise invariant for {tool_name} under Vision-Language Models (VLM), GUI Computer-Use & Desktop Agent Safety best practices."
|
| 106 |
-
}
|
| 107 |
-
|
| 108 |
-
TOOLS_SPEC = [
|
| 109 |
-
{
|
| 110 |
-
"name": "map_scancodes_between_qwerty_and_qwertz",
|
| 111 |
-
"description": "Executes map scancodes between qwerty and qwertz within Computer Use Virtual Keyboard Layout Mapper to eliminate operational defects.",
|
| 112 |
-
"inputSchema": {
|
| 113 |
-
"type": "object",
|
| 114 |
-
"properties": {
|
| 115 |
-
"code_content": {
|
| 116 |
-
"type": "string",
|
| 117 |
-
"description": "Python source code or configuration to statically audit."
|
| 118 |
-
}
|
| 119 |
-
},
|
| 120 |
-
"required": [
|
| 121 |
-
"code_content"
|
| 122 |
-
]
|
| 123 |
-
}
|
| 124 |
-
},
|
| 125 |
-
{
|
| 126 |
-
"name": "detect_z_y_inversion_in_text_inputs",
|
| 127 |
-
"description": "Executes detect z y inversion in text inputs within Computer Use Virtual Keyboard Layout Mapper to eliminate operational defects.",
|
| 128 |
-
"inputSchema": {
|
| 129 |
-
"type": "object",
|
| 130 |
-
"properties": {
|
| 131 |
-
"code_content": {
|
| 132 |
-
"type": "string",
|
| 133 |
-
"description": "Python source code or configuration to statically audit."
|
| 134 |
-
}
|
| 135 |
-
},
|
| 136 |
-
"required": [
|
| 137 |
-
"code_content"
|
| 138 |
-
]
|
| 139 |
-
}
|
| 140 |
-
},
|
| 141 |
-
{
|
| 142 |
-
"name": "audit_altgr_special_character_failures",
|
| 143 |
-
"description": "Executes audit altgr special character failures within Computer Use Virtual Keyboard Layout Mapper to eliminate operational defects.",
|
| 144 |
-
"inputSchema": {
|
| 145 |
-
"type": "object",
|
| 146 |
-
"properties": {
|
| 147 |
-
"code_content": {
|
| 148 |
-
"type": "string",
|
| 149 |
-
"description": "Python source code or configuration to statically audit."
|
| 150 |
-
}
|
| 151 |
-
},
|
| 152 |
-
"required": [
|
| 153 |
-
"code_content"
|
| 154 |
-
]
|
| 155 |
-
}
|
| 156 |
-
},
|
| 157 |
-
{
|
| 158 |
-
"name": "synthesize_layout_independent_key_stream",
|
| 159 |
-
"description": "Executes synthesize layout independent key stream within Computer Use Virtual Keyboard Layout Mapper to eliminate operational defects.",
|
| 160 |
-
"inputSchema": {
|
| 161 |
-
"type": "object",
|
| 162 |
-
"properties": {
|
| 163 |
-
"code_content": {
|
| 164 |
-
"type": "string",
|
| 165 |
-
"description": "Python source code or configuration to statically audit."
|
| 166 |
-
}
|
| 167 |
-
},
|
| 168 |
-
"required": [
|
| 169 |
-
"code_content"
|
| 170 |
-
]
|
| 171 |
-
}
|
| 172 |
-
}
|
| 173 |
-
]
|
| 174 |
-
|
| 175 |
-
def lookup_kb(words, tool_filter=None):
|
| 176 |
-
best, score = None, -1
|
| 177 |
-
for inc in KB_DATA:
|
| 178 |
-
if tool_filter and inc.get("tool_scope") != tool_filter:
|
| 179 |
-
continue
|
| 180 |
-
sc = sum(1 for w in words if w.lower() in inc.get("title", "").lower() or w.lower() in inc.get("root_cause", "").lower())
|
| 181 |
-
if sc > score:
|
| 182 |
-
score = sc
|
| 183 |
-
best = inc
|
| 184 |
-
return best
|
| 185 |
-
|
| 186 |
-
def process_message(req: dict) -> dict:
|
| 187 |
-
method = req.get("method")
|
| 188 |
-
msg_id = req.get("id")
|
| 189 |
-
params = req.get("params", {})
|
| 190 |
-
|
| 191 |
-
if method == "initialize":
|
| 192 |
-
return {
|
| 193 |
-
"jsonrpc": "2.0",
|
| 194 |
-
"id": msg_id,
|
| 195 |
-
"result": {
|
| 196 |
-
"protocolVersion": "2024-11-05",
|
| 197 |
-
"capabilities": {"tools": {"listChanged": False}},
|
| 198 |
-
"serverInfo": {"name": "computer_use_virtual_keyboard_layout_mapper", "version": "2.5.0"}
|
| 199 |
-
}
|
| 200 |
-
}
|
| 201 |
-
elif method == "tools/list":
|
| 202 |
-
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
|
| 203 |
-
elif method == "tools/call":
|
| 204 |
-
name = params.get("name")
|
| 205 |
-
args = params.get("arguments", {})
|
| 206 |
-
res = execute_tool(name, args)
|
| 207 |
-
query = re.findall(r"\w+", str(args))
|
| 208 |
-
match = lookup_kb(query, tool_filter=name)
|
| 209 |
-
if match and isinstance(res, dict):
|
| 210 |
-
res["_diagnostic_context"] = {
|
| 211 |
-
"incident_ref": match.get("id"),
|
| 212 |
-
"incident_title": match.get("title"),
|
| 213 |
-
"root_cause_summary": match.get("root_cause", "")[:140] + "...",
|
| 214 |
-
"prevention_rule": match.get("prevention_rule")
|
| 215 |
-
}
|
| 216 |
-
return {
|
| 217 |
-
"jsonrpc": "2.0",
|
| 218 |
-
"id": msg_id,
|
| 219 |
-
"result": {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}], "isError": False}
|
| 220 |
-
}
|
| 221 |
-
elif method == "notifications/initialized":
|
| 222 |
-
return None
|
| 223 |
-
elif method == "ping":
|
| 224 |
-
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
|
| 225 |
-
elif msg_id is not None:
|
| 226 |
-
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Method '{method}' not supported"}}
|
| 227 |
-
return None
|
| 228 |
-
|
| 229 |
-
def main():
|
| 230 |
-
while True:
|
| 231 |
-
try:
|
| 232 |
-
line = sys.stdin.readline()
|
| 233 |
-
if not line: break
|
| 234 |
-
line = line.strip()
|
| 235 |
-
if not line: continue
|
| 236 |
-
req = json.loads(line)
|
| 237 |
-
resp = process_message(req)
|
| 238 |
-
if resp:
|
| 239 |
-
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
|
| 240 |
-
sys.stdout.flush()
|
| 241 |
-
except Exception as e:
|
| 242 |
-
err = {"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}
|
| 243 |
-
sys.stdout.write(json.dumps(err, ensure_ascii=False) + "\n")
|
| 244 |
-
sys.stdout.flush()
|
| 245 |
-
|
| 246 |
-
if __name__ == "__main__":
|
| 247 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server_free.py
CHANGED
|
@@ -1,16 +1,16 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
Package: computer_use_virtual_keyboard_layout_mapper
|
| 5 |
Title: Computer Use Virtual Keyboard Layout Mapper
|
| 6 |
-
|
| 7 |
-
|
| 8 |
"""
|
| 9 |
|
| 10 |
import sys, os, json, ast, time, re
|
| 11 |
from pathlib import Path
|
|
|
|
| 12 |
|
| 13 |
-
# Ensure UTF-8 stdout
|
| 14 |
if sys.platform == "win32":
|
| 15 |
try:
|
| 16 |
sys.stdout.reconfigure(encoding="utf-8")
|
|
@@ -18,104 +18,273 @@ if sys.platform == "win32":
|
|
| 18 |
except Exception:
|
| 19 |
pass
|
| 20 |
|
| 21 |
-
KB_PATH = Path(__file__).parent / "knowledge_base.json"
|
| 22 |
-
KB_DATA = json.loads(KB_PATH.read_text(encoding="utf-8")) if KB_PATH.exists() else []
|
| 23 |
-
|
| 24 |
SESSION_SCANS = 0
|
| 25 |
-
MAX_FREE_SCANS =
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
]
|
| 45 |
|
| 46 |
-
class
|
| 47 |
-
"""
|
| 48 |
-
def __init__(self):
|
| 49 |
-
self.
|
| 50 |
-
self.
|
| 51 |
-
self.
|
| 52 |
-
self.has_for = False
|
| 53 |
-
self.has_async = False
|
| 54 |
|
| 55 |
-
def
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
elif isinstance(node.func, ast.Attribute):
|
| 59 |
-
self.call_names.add(node.func.attr.lower())
|
| 60 |
self.generic_visit(node)
|
|
|
|
| 61 |
|
| 62 |
-
def
|
| 63 |
-
|
| 64 |
-
|
| 65 |
self.generic_visit(node)
|
|
|
|
| 66 |
|
| 67 |
-
def
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
self.generic_visit(node)
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
self.generic_visit(node)
|
| 74 |
|
| 75 |
-
def
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
self.generic_visit(node)
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
def execute_tool(tool_name: str, arguments: dict) -> dict:
|
| 80 |
global SESSION_SCANS
|
| 81 |
if SESSION_SCANS >= MAX_FREE_SCANS:
|
| 82 |
return {
|
|
|
|
| 83 |
"defect_detected": False,
|
| 84 |
-
"
|
| 85 |
-
"
|
| 86 |
-
"
|
| 87 |
-
"
|
| 88 |
}
|
| 89 |
SESSION_SCANS += 1
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
|
|
|
| 94 |
try:
|
| 95 |
-
|
| 96 |
-
except SyntaxError
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
visitor = ASTSentinelVisitor()
|
| 100 |
-
visitor.visit(tree)
|
| 101 |
-
_ = [node for node in ast.walk(tree)]
|
| 102 |
|
| 103 |
lines = [l.split("#")[0] for l in code.splitlines()]
|
| 104 |
code_text = "\n".join(lines).lower()
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
if b_tok in code_text and r_tok not in code_text:
|
| 109 |
-
defect_detected = True
|
| 110 |
-
break
|
| 111 |
|
| 112 |
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
"defect_detected": defect_detected,
|
| 114 |
-
"
|
| 115 |
-
"
|
| 116 |
-
"
|
| 117 |
-
"
|
| 118 |
-
"recommendation": f"Enforce verified enterprise invariant for {tool_name} under Vision-Language Models (VLM), GUI Computer-Use & Desktop Agent Safety best practices."
|
| 119 |
}
|
| 120 |
|
| 121 |
TOOLS_SPEC = [
|
|
@@ -184,77 +353,57 @@ TOOLS_SPEC = [
|
|
| 184 |
}
|
| 185 |
}
|
| 186 |
]
|
|
|
|
| 187 |
|
| 188 |
-
def
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
continue
|
| 193 |
-
sc = sum(1 for w in words if w.lower() in inc.get("title", "").lower() or w.lower() in inc.get("root_cause", "").lower())
|
| 194 |
-
if sc > score:
|
| 195 |
-
score = sc
|
| 196 |
-
best = inc
|
| 197 |
-
return best
|
| 198 |
-
|
| 199 |
-
def process_message(req: dict) -> dict:
|
| 200 |
-
method = req.get("method")
|
| 201 |
-
msg_id = req.get("id")
|
| 202 |
-
params = req.get("params", {})
|
| 203 |
-
|
| 204 |
if method == "initialize":
|
| 205 |
return {
|
| 206 |
-
"jsonrpc": "2.0",
|
| 207 |
-
"id": msg_id,
|
| 208 |
"result": {
|
| 209 |
"protocolVersion": "2024-11-05",
|
| 210 |
"capabilities": {"tools": {"listChanged": False}},
|
| 211 |
-
"serverInfo": {"name": "
|
| 212 |
}
|
| 213 |
}
|
|
|
|
|
|
|
| 214 |
elif method == "tools/list":
|
| 215 |
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
|
| 216 |
elif method == "tools/call":
|
| 217 |
-
|
| 218 |
args = params.get("arguments", {})
|
| 219 |
-
|
| 220 |
-
query = re.findall(r"\w+", str(args))
|
| 221 |
-
match = lookup_kb(query, tool_filter=name)
|
| 222 |
-
if match and isinstance(res, dict):
|
| 223 |
-
res["_emgena_enterprise_notice"] = "\n🔒 Emgena MCP Production Engine | [Get Enterprise: https://emgena.gumroad.com/l/computer_use_virtual_keyboard_layout_mapper]\n🎟️ Use coupon LAUNCH20 for €20 discount!\n"
|
| 224 |
-
res["_diagnostic_context"] = {
|
| 225 |
-
"incident_ref": match.get("id"),
|
| 226 |
-
"incident_title": match.get("title"),
|
| 227 |
-
"root_cause_summary": match.get("root_cause", "")[:140] + "...",
|
| 228 |
-
"prevention_rule": match.get("prevention_rule")
|
| 229 |
-
}
|
| 230 |
return {
|
| 231 |
-
"jsonrpc": "2.0",
|
| 232 |
-
"
|
| 233 |
-
|
|
|
|
|
|
|
| 234 |
}
|
| 235 |
-
|
| 236 |
-
return None
|
| 237 |
-
elif method == "ping":
|
| 238 |
-
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
|
| 239 |
-
elif msg_id is not None:
|
| 240 |
-
return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32601, "message": f"Method '{method}' not supported"}}
|
| 241 |
-
return None
|
| 242 |
|
| 243 |
def main():
|
|
|
|
|
|
|
|
|
|
| 244 |
while True:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
try:
|
| 246 |
-
line = sys.stdin.readline()
|
| 247 |
-
if not line: break
|
| 248 |
-
line = line.strip()
|
| 249 |
-
if not line: continue
|
| 250 |
req = json.loads(line)
|
| 251 |
resp = process_message(req)
|
| 252 |
-
if resp:
|
| 253 |
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
|
| 254 |
sys.stdout.flush()
|
| 255 |
except Exception as e:
|
| 256 |
-
|
| 257 |
-
sys.stdout.write(json.dumps(err, ensure_ascii=False) + "\n")
|
| 258 |
sys.stdout.flush()
|
| 259 |
|
| 260 |
if __name__ == "__main__":
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
EMGENA SENTINEL MCP SERVER - COMMUNITY EVALUATION EDITION (CC-BY-NC-4.0)
|
| 4 |
Package: computer_use_virtual_keyboard_layout_mapper
|
| 5 |
Title: Computer Use Virtual Keyboard Layout Mapper
|
| 6 |
+
Upgrade to Commercial Pro (Unlimited AST Scans + CI/CD SARIF Gate + B2B VAT Invoice):
|
| 7 |
+
https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20
|
| 8 |
"""
|
| 9 |
|
| 10 |
import sys, os, json, ast, time, re
|
| 11 |
from pathlib import Path
|
| 12 |
+
from typing import Any, Dict, List, Tuple
|
| 13 |
|
|
|
|
| 14 |
if sys.platform == "win32":
|
| 15 |
try:
|
| 16 |
sys.stdout.reconfigure(encoding="utf-8")
|
|
|
|
| 18 |
except Exception:
|
| 19 |
pass
|
| 20 |
|
|
|
|
|
|
|
|
|
|
| 21 |
SESSION_SCANS = 0
|
| 22 |
+
MAX_FREE_SCANS = 5
|
| 23 |
+
UPGRADE_URL = "https://emgena.com/trainingslager?product=computer_use_virtual_keyboard_layout_mapper&coupon=LAUNCH20"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
import math as _math
|
| 27 |
+
|
| 28 |
+
SAFE_VALUE_MARKERS = (
|
| 29 |
+
"redacted", "placeholder", "example", "changeme", "your_", "dummy", "mock",
|
| 30 |
+
"***", "xxxx", "<", "alias/", "vault:", "kms:", "secret_ref", "env:",
|
| 31 |
+
"os.environ", "getenv", "test_", "rfc2606", "rfc5737",
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
def _shannon_entropy(data: str) -> float:
|
| 35 |
+
if not data:
|
| 36 |
+
return 0.0
|
| 37 |
+
freq = {}
|
| 38 |
+
for ch in data:
|
| 39 |
+
freq[ch] = freq.get(ch, 0) + 1
|
| 40 |
+
length = len(data)
|
| 41 |
+
return -sum((cnt / length) * _math.log2(cnt / length) for cnt in freq.values())
|
| 42 |
+
|
| 43 |
+
def _mask_preview(val: str) -> str:
|
| 44 |
+
s = str(val).replace("\n", " ").strip()
|
| 45 |
+
if len(s) <= 8:
|
| 46 |
+
return "****"
|
| 47 |
+
return s[:4] + "****" + s[-4:]
|
| 48 |
+
|
| 49 |
+
def _call_name(node: ast.Call) -> str:
|
| 50 |
+
if isinstance(node.func, ast.Name):
|
| 51 |
+
return node.func.id.lower()
|
| 52 |
+
if isinstance(node.func, ast.Attribute):
|
| 53 |
+
return node.func.attr.lower()
|
| 54 |
+
return ""
|
| 55 |
+
|
| 56 |
+
def _full_attr_name(node: ast.AST) -> str:
|
| 57 |
+
parts = []
|
| 58 |
+
cur = node
|
| 59 |
+
while isinstance(cur, ast.Attribute):
|
| 60 |
+
parts.append(cur.attr.lower())
|
| 61 |
+
cur = cur.value
|
| 62 |
+
if isinstance(cur, ast.Name):
|
| 63 |
+
parts.append(cur.id.lower())
|
| 64 |
+
return ".".join(reversed(parts))
|
| 65 |
+
|
| 66 |
+
def _has_kw(node: ast.Call, name: str) -> bool:
|
| 67 |
+
return any(kw.arg and kw.arg.lower() == name.lower() for kw in node.keywords)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
DOMAIN_REGEX_RULES = [
|
| 71 |
+
("EMGENA-SRE-001", "HIGH", "CWE-1333", "Potential catastrophic ReDoS nested quantifier regex",
|
| 72 |
+
re.compile(r"\([^)]*[+*][^)]*\)[+*]")),
|
| 73 |
+
("EMGENA-SRE-002", "HIGH", "CWE-400", "Unbounded top_k / batch size or missing backpressure limit",
|
| 74 |
+
re.compile(r"(?:top_k|limit|batch_size)\s*=\s*(?:100000|999999|None)\b")),
|
| 75 |
]
|
| 76 |
|
| 77 |
+
class DomainASTVisitor(ast.NodeVisitor):
|
| 78 |
+
"""Inspects AsyncIO event loop blocking, bare excepts, unbounded loops, and unclosed resources."""
|
| 79 |
+
def __init__(self, pro_mode: bool = True):
|
| 80 |
+
self.pro_mode = pro_mode
|
| 81 |
+
self.in_async = False
|
| 82 |
+
self.findings = []
|
|
|
|
|
|
|
| 83 |
|
| 84 |
+
def visit_AsyncFunctionDef(self, node):
|
| 85 |
+
prev = self.in_async
|
| 86 |
+
self.in_async = True
|
|
|
|
|
|
|
| 87 |
self.generic_visit(node)
|
| 88 |
+
self.in_async = prev
|
| 89 |
|
| 90 |
+
def visit_FunctionDef(self, node):
|
| 91 |
+
prev = self.in_async
|
| 92 |
+
self.in_async = False
|
| 93 |
self.generic_visit(node)
|
| 94 |
+
self.in_async = prev
|
| 95 |
|
| 96 |
+
def visit_ExceptHandler(self, node):
|
| 97 |
+
if node.type is None:
|
| 98 |
+
self.findings.append({
|
| 99 |
+
"rule_id": "EMGENA-SRE-AST-101", "severity": "HIGH", "cwe": "CWE-396",
|
| 100 |
+
"line": getattr(node, "lineno", 1),
|
| 101 |
+
"message": "Bare 'except:' handler catches asyncio.CancelledError and SystemExit.",
|
| 102 |
+
"preview": "except:",
|
| 103 |
+
"remediation": "Catch specific exceptions (except ValueError / RuntimeError) and propagate CancelledError."
|
| 104 |
+
})
|
| 105 |
self.generic_visit(node)
|
| 106 |
|
| 107 |
+
def visit_While(self, node):
|
| 108 |
+
if isinstance(node.test, ast.Constant) and node.test.value is True:
|
| 109 |
+
has_exit = any(isinstance(n, (ast.Break, ast.Return, ast.Raise)) for n in ast.walk(node))
|
| 110 |
+
if not has_exit:
|
| 111 |
+
self.findings.append({
|
| 112 |
+
"rule_id": "EMGENA-SRE-AST-102", "severity": "CRITICAL", "cwe": "CWE-835",
|
| 113 |
+
"line": getattr(node, "lineno", 1),
|
| 114 |
+
"message": "Infinite 'while True:' loop without break/return/raise guard.",
|
| 115 |
+
"preview": "while True: ...",
|
| 116 |
+
"remediation": "Add bounded max_iterations, deadline check, and deterministic exit condition."
|
| 117 |
+
})
|
| 118 |
self.generic_visit(node)
|
| 119 |
|
| 120 |
+
def visit_Call(self, node):
|
| 121 |
+
full = _full_attr_name(node.func)
|
| 122 |
+
line = getattr(node, "lineno", 1)
|
| 123 |
+
|
| 124 |
+
if self.in_async and full in (
|
| 125 |
+
"time.sleep", "requests.get", "requests.post", "requests.put", "requests.delete",
|
| 126 |
+
"urllib.request.urlopen", "subprocess.run", "subprocess.call", "subprocess.check_output"
|
| 127 |
+
):
|
| 128 |
+
self.findings.append({
|
| 129 |
+
"rule_id": "EMGENA-SRE-AST-201", "severity": "CRITICAL", "cwe": "CWE-400", "line": line,
|
| 130 |
+
"message": f"Synchronous blocking call '{full}()' inside async coroutine stalls the event loop.",
|
| 131 |
+
"preview": f"async -> {full}(...)",
|
| 132 |
+
"remediation": "Use asyncio.sleep() / httpx.AsyncClient / asyncio.create_subprocess_exec() or asyncio.to_thread()."
|
| 133 |
+
})
|
| 134 |
+
|
| 135 |
+
if self.pro_mode and full in ("requests.get", "requests.post", "urllib.request.urlopen", "httpx.get", "httpx.post") and not _has_kw(node, "timeout"):
|
| 136 |
+
self.findings.append({
|
| 137 |
+
"rule_id": "EMGENA-SRE-AST-202", "severity": "HIGH", "cwe": "CWE-400", "line": line,
|
| 138 |
+
"message": f"Network call '{full}()' missing timeout risks thread/worker exhaustion.",
|
| 139 |
+
"preview": f"{full}(...)",
|
| 140 |
+
"remediation": "Configure strict connect and read timeouts."
|
| 141 |
+
})
|
| 142 |
self.generic_visit(node)
|
| 143 |
|
| 144 |
+
|
| 145 |
+
SCAN_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".env", ".json", ".yaml", ".yml", ".sh", ".toml", ".tf", ".ini", ".sql"}
|
| 146 |
+
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "mlx_data"}
|
| 147 |
+
|
| 148 |
+
def run_domain_ast_scan(code: str, pro_mode: bool = True) -> list:
|
| 149 |
+
findings = []
|
| 150 |
+
if not code or not code.strip():
|
| 151 |
+
return findings
|
| 152 |
+
|
| 153 |
+
rules = DOMAIN_REGEX_RULES if pro_mode else DOMAIN_REGEX_RULES[:4]
|
| 154 |
+
for lineno, raw_line in enumerate(code.splitlines(), 1):
|
| 155 |
+
code_no_comment = raw_line.split("#")[0]
|
| 156 |
+
low = code_no_comment.lower()
|
| 157 |
+
if any(m in low for m in ("redacted", "placeholder", "example_only", "safe_sanitized", "***")):
|
| 158 |
+
continue
|
| 159 |
+
for rule_id, sev, cwe, desc, pat in rules:
|
| 160 |
+
m = pat.search(code_no_comment)
|
| 161 |
+
if m:
|
| 162 |
+
findings.append({
|
| 163 |
+
"rule_id": rule_id,
|
| 164 |
+
"severity": sev,
|
| 165 |
+
"cwe": cwe,
|
| 166 |
+
"line": lineno,
|
| 167 |
+
"message": desc,
|
| 168 |
+
"preview": _mask_preview(m.group(0)),
|
| 169 |
+
"remediation": "Remediate detected policy violation before execution or commit."
|
| 170 |
+
})
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
tree = ast.parse(code)
|
| 174 |
+
visitor = DomainASTVisitor(pro_mode=pro_mode)
|
| 175 |
+
visitor.visit(tree)
|
| 176 |
+
findings.extend(visitor.findings)
|
| 177 |
+
except SyntaxError as e:
|
| 178 |
+
findings.append({
|
| 179 |
+
"rule_id": "EMGENA-SYNTAX-000",
|
| 180 |
+
"severity": "CRITICAL",
|
| 181 |
+
"cwe": "CWE-20",
|
| 182 |
+
"line": getattr(e, "lineno", 1) or 1,
|
| 183 |
+
"message": f"Python AST SyntaxError: {e.msg}",
|
| 184 |
+
"preview": str(e.text or "").strip()[:60],
|
| 185 |
+
"remediation": "Fix Python syntax before deploying or loading into MCP context."
|
| 186 |
+
})
|
| 187 |
+
|
| 188 |
+
seen = set()
|
| 189 |
+
unique = []
|
| 190 |
+
for f in findings:
|
| 191 |
+
key = (f["rule_id"], f["line"])
|
| 192 |
+
if key not in seen:
|
| 193 |
+
seen.add(key)
|
| 194 |
+
unique.append(f)
|
| 195 |
+
return unique
|
| 196 |
+
|
| 197 |
+
def scan_directory_or_file(target_path: str) -> dict:
|
| 198 |
+
p = Path(target_path)
|
| 199 |
+
files = [p] if p.is_file() else [
|
| 200 |
+
f for f in p.rglob("*")
|
| 201 |
+
if f.is_file() and (f.suffix.lower() in SCAN_EXTENSIONS or f.name.startswith(".env"))
|
| 202 |
+
and not any(sd in f.parts for sd in SKIP_DIRS)
|
| 203 |
+
and f.name not in ("server.py", "server_free.py")
|
| 204 |
+
]
|
| 205 |
+
all_results = []
|
| 206 |
+
for fp in files:
|
| 207 |
+
try:
|
| 208 |
+
txt = fp.read_text(encoding="utf-8", errors="ignore")
|
| 209 |
+
except Exception:
|
| 210 |
+
continue
|
| 211 |
+
if len(txt) > 512 * 1024:
|
| 212 |
+
continue
|
| 213 |
+
hits = run_domain_ast_scan(txt, pro_mode=True)
|
| 214 |
+
for h in hits:
|
| 215 |
+
h["file"] = str(fp)
|
| 216 |
+
all_results.append(h)
|
| 217 |
+
return {"files_scanned": len(files), "total_findings": len(all_results), "findings": all_results}
|
| 218 |
+
|
| 219 |
+
def build_sarif(scan_res: dict, pkg_id: str) -> dict:
|
| 220 |
+
runs_results = []
|
| 221 |
+
for f in scan_res["findings"]:
|
| 222 |
+
runs_results.append({
|
| 223 |
+
"ruleId": f["rule_id"],
|
| 224 |
+
"level": "error" if f["severity"] == "CRITICAL" else "warning",
|
| 225 |
+
"message": {"text": f"{f['message']} ({f['preview']}) -> {f['remediation']}"},
|
| 226 |
+
"locations": [{
|
| 227 |
+
"physicalLocation": {
|
| 228 |
+
"artifactLocation": {"uri": f.get("file", "unknown")},
|
| 229 |
+
"region": {"startLine": int(f.get("line", 1))}
|
| 230 |
+
}
|
| 231 |
+
}]
|
| 232 |
+
})
|
| 233 |
+
return {
|
| 234 |
+
"version": "2.1.0",
|
| 235 |
+
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
| 236 |
+
"runs": [{
|
| 237 |
+
"tool": {"driver": {"name": f"EMGENA-{pkg_id}", "version": "3.0.0"}},
|
| 238 |
+
"results": runs_results
|
| 239 |
+
}]
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def _legacy_package_check(code: str, code_text: str, tool_name: str) -> bool:
|
| 244 |
+
return False
|
| 245 |
+
|
| 246 |
def execute_tool(tool_name: str, arguments: dict) -> dict:
|
| 247 |
global SESSION_SCANS
|
| 248 |
if SESSION_SCANS >= MAX_FREE_SCANS:
|
| 249 |
return {
|
| 250 |
+
"package": "computer_use_virtual_keyboard_layout_mapper",
|
| 251 |
"defect_detected": False,
|
| 252 |
+
"is_safe": False,
|
| 253 |
+
"status": "COMMUNITY_LIMIT_REACHED",
|
| 254 |
+
"error": f"Community Edition limit ({MAX_FREE_SCANS} scans/session) reached. Unlock Commercial Pro (code LAUNCH20): {UPGRADE_URL}",
|
| 255 |
+
"_emgena_commercial_pro": {"upgrade_url": UPGRADE_URL, "coupon": "LAUNCH20"}
|
| 256 |
}
|
| 257 |
SESSION_SCANS += 1
|
| 258 |
+
if not isinstance(arguments, dict):
|
| 259 |
+
arguments = {}
|
| 260 |
+
code = (arguments.get("code_content") or arguments.get("code") or arguments.get("code_snippet") or arguments.get("raw_chunk_text") or arguments.get("chunk_text") or arguments.get("flawed_code") or arguments.get("payload") or arguments.get("sql") or arguments.get("prompt") or arguments.get("source") or "")
|
| 261 |
+
if not isinstance(code, str):
|
| 262 |
+
code = json.dumps(code, ensure_ascii=False)
|
| 263 |
+
if not code.strip():
|
| 264 |
+
return {"package": "computer_use_virtual_keyboard_layout_mapper", "defect_detected": False, "is_safe": True, "status": "EMPTY_CODE", "findings": []}
|
| 265 |
|
| 266 |
+
ast_valid = True
|
| 267 |
try:
|
| 268 |
+
ast.parse(code)
|
| 269 |
+
except SyntaxError:
|
| 270 |
+
ast_valid = False
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
lines = [l.split("#")[0] for l in code.splitlines()]
|
| 273 |
code_text = "\n".join(lines).lower()
|
| 274 |
+
real_findings = run_domain_ast_scan(code, pro_mode=False)
|
| 275 |
+
legacy_hit = _legacy_package_check(code, code_text, tool_name) if ast_valid else False
|
| 276 |
+
defect_detected = bool(real_findings) or legacy_hit or (not ast_valid)
|
|
|
|
|
|
|
|
|
|
| 277 |
|
| 278 |
return {
|
| 279 |
+
"package": "computer_use_virtual_keyboard_layout_mapper",
|
| 280 |
+
"tool": tool_name,
|
| 281 |
+
"edition": "COMMUNITY_EVALUATION (CC-BY-NC-4.0)",
|
| 282 |
+
"status": "VIOLATION_DETECTED" if defect_detected else "PASS_VALIDATED",
|
| 283 |
"defect_detected": defect_detected,
|
| 284 |
+
"is_safe": not defect_detected,
|
| 285 |
+
"scans_remaining": max(0, MAX_FREE_SCANS - SESSION_SCANS),
|
| 286 |
+
"findings": real_findings,
|
| 287 |
+
"_emgena_pro_notice": f"Commercial deployment or CI/CD --sarif requires Commercial License -> {UPGRADE_URL}"
|
|
|
|
| 288 |
}
|
| 289 |
|
| 290 |
TOOLS_SPEC = [
|
|
|
|
| 353 |
}
|
| 354 |
}
|
| 355 |
]
|
| 356 |
+
TOOLS = TOOLS_SPEC
|
| 357 |
|
| 358 |
+
def process_message(message: dict) -> dict:
|
| 359 |
+
msg_id = message.get("id")
|
| 360 |
+
method = message.get("method")
|
| 361 |
+
params = message.get("params", {}) or {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
if method == "initialize":
|
| 363 |
return {
|
| 364 |
+
"jsonrpc": "2.0", "id": msg_id,
|
|
|
|
| 365 |
"result": {
|
| 366 |
"protocolVersion": "2024-11-05",
|
| 367 |
"capabilities": {"tools": {"listChanged": False}},
|
| 368 |
+
"serverInfo": {"name": "computer_use_virtual_keyboard_layout_mapper_community", "version": "3.0.0-free"}
|
| 369 |
}
|
| 370 |
}
|
| 371 |
+
elif method == "notifications/initialized":
|
| 372 |
+
return None
|
| 373 |
elif method == "tools/list":
|
| 374 |
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
|
| 375 |
elif method == "tools/call":
|
| 376 |
+
tname = params.get("name", "")
|
| 377 |
args = params.get("arguments", {})
|
| 378 |
+
tool_res = execute_tool(tname, args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
return {
|
| 380 |
+
"jsonrpc": "2.0", "id": msg_id,
|
| 381 |
+
"result": {
|
| 382 |
+
"content": [{"type": "text", "text": json.dumps(tool_res, indent=2, ensure_ascii=False)}],
|
| 383 |
+
"isError": False
|
| 384 |
+
}
|
| 385 |
}
|
| 386 |
+
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
|
| 388 |
def main():
|
| 389 |
+
if "--scan" in sys.argv:
|
| 390 |
+
print(f"CLI --scan & --sarif CI/CD Gate requires Commercial Pro. Unlock with LAUNCH20: {UPGRADE_URL}")
|
| 391 |
+
sys.exit(2)
|
| 392 |
while True:
|
| 393 |
+
line = sys.stdin.readline()
|
| 394 |
+
if not line:
|
| 395 |
+
break
|
| 396 |
+
line = line.strip()
|
| 397 |
+
if not line:
|
| 398 |
+
continue
|
| 399 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
req = json.loads(line)
|
| 401 |
resp = process_message(req)
|
| 402 |
+
if resp is not None:
|
| 403 |
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
|
| 404 |
sys.stdout.flush()
|
| 405 |
except Exception as e:
|
| 406 |
+
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}) + "\n")
|
|
|
|
| 407 |
sys.stdout.flush()
|
| 408 |
|
| 409 |
if __name__ == "__main__":
|
train.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:acb7d258156927a479e7f77dec752e0e58ef231e6195518dafdfed29370ff118
|
| 3 |
+
size 21520
|
train_lora_unsloth.py
CHANGED
|
@@ -1,26 +1,102 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
def main():
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
if __name__ == "__main__":
|
| 26 |
main()
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
EMGENA AI LABS v3.0 - UNSLOTH QLoRA 4-BIT FINE-TUNING ENGINE
|
| 4 |
+
Works cleanly with local `chatml_format.jsonl` (NVIDIA RTX / A100 / Google Colab).
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
python train_lora_unsloth.py --dry-run # Validate dataset resolution & ChatML records offline
|
| 8 |
+
python train_lora_unsloth.py # Run full 4-bit QLoRA training + GGUF export
|
| 9 |
"""
|
| 10 |
+
import json
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parent
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def resolve_dataset_file() -> Path:
|
| 18 |
+
for name in ("chatml_format.jsonl", "full_training_dataset.jsonl"):
|
| 19 |
+
p = ROOT / name
|
| 20 |
+
if p.exists() and p.stat().st_size > 0:
|
| 21 |
+
return p
|
| 22 |
+
for p in sorted(ROOT.glob("*.jsonl")):
|
| 23 |
+
if p.stat().st_size > 0:
|
| 24 |
+
return p
|
| 25 |
+
raise FileNotFoundError("Missing ChatML JSONL file in package directory.")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def dry_run():
|
| 29 |
+
ds_file = resolve_dataset_file()
|
| 30 |
+
count = 0
|
| 31 |
+
with ds_file.open("r", encoding="utf-8") as f:
|
| 32 |
+
for line in f:
|
| 33 |
+
if line.strip():
|
| 34 |
+
obj = json.loads(line)
|
| 35 |
+
assert isinstance(obj.get("messages"), list) and len(obj["messages"]) >= 2
|
| 36 |
+
count += 1
|
| 37 |
+
print(f"✅ Unsloth v3.0 Dry-Run Passed: {ds_file.name} ({count} valid ChatML trajectories)")
|
| 38 |
+
|
| 39 |
|
| 40 |
def main():
|
| 41 |
+
if "--dry-run" in sys.argv:
|
| 42 |
+
dry_run()
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
import torch
|
| 46 |
+
from datasets import load_dataset
|
| 47 |
+
from transformers import TrainingArguments
|
| 48 |
+
from trl import SFTTrainer
|
| 49 |
+
from unsloth import FastLanguageModel
|
| 50 |
+
|
| 51 |
+
ds_file = resolve_dataset_file()
|
| 52 |
+
max_seq_length = 2048
|
| 53 |
+
model, tokenizer = FastLanguageModel.from_pretrained(
|
| 54 |
+
model_name="unsloth/Qwen2.5-Coder-7B-Instruct-bnb-4bit",
|
| 55 |
+
max_seq_length=max_seq_length,
|
| 56 |
+
dtype=None,
|
| 57 |
+
load_in_4bit=True,
|
| 58 |
+
)
|
| 59 |
+
model = FastLanguageModel.get_peft_model(
|
| 60 |
+
model, r=16,
|
| 61 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
|
| 62 |
+
lora_alpha=16, lora_dropout=0, bias="none", use_gradient_checkpointing="unsloth",
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
dataset = load_dataset("json", data_files={"train": str(ds_file)}, split="train")
|
| 66 |
+
dataset = dataset.map(
|
| 67 |
+
lambda batch: {
|
| 68 |
+
"text": [
|
| 69 |
+
tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=False)
|
| 70 |
+
for msgs in batch["messages"]
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
batched=True,
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
trainer = SFTTrainer(
|
| 77 |
+
model=model,
|
| 78 |
+
tokenizer=tokenizer,
|
| 79 |
+
train_dataset=dataset,
|
| 80 |
+
dataset_text_field="text",
|
| 81 |
+
max_seq_length=max_seq_length,
|
| 82 |
+
dataset_num_proc=2,
|
| 83 |
+
packing=False,
|
| 84 |
+
args=TrainingArguments(
|
| 85 |
+
per_device_train_batch_size=2,
|
| 86 |
+
gradient_accumulation_steps=4,
|
| 87 |
+
warmup_steps=5,
|
| 88 |
+
num_train_epochs=1,
|
| 89 |
+
learning_rate=2e-4,
|
| 90 |
+
fp16=not torch.cuda.is_bf16_supported(),
|
| 91 |
+
bf16=torch.cuda.is_bf16_supported(),
|
| 92 |
+
logging_steps=10,
|
| 93 |
+
output_dir=str(ROOT / "lora_output"),
|
| 94 |
+
),
|
| 95 |
+
)
|
| 96 |
+
trainer.train()
|
| 97 |
+
model.save_pretrained_merged(str(ROOT / "checkpoint_merged"), tokenizer, save_method="merged_16bit")
|
| 98 |
+
print("🎉 Fine-tuning complete! Export to GGUF via: model.save_pretrained_gguf('gguf_model', tokenizer, quantization_method='q4_k_m')")
|
| 99 |
+
|
| 100 |
|
| 101 |
if __name__ == "__main__":
|
| 102 |
main()
|
train_mlx.py
CHANGED
|
@@ -1,87 +1,117 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
Optimized for Apple M1/M2/M3/M4 (
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
Prerequisites on Mac:
|
| 8 |
-
pip install mlx mlx-lm
|
| 9 |
|
| 10 |
Usage:
|
| 11 |
-
python train_mlx.py
|
| 12 |
-
python train_mlx.py --
|
|
|
|
| 13 |
"""
|
| 14 |
-
import
|
| 15 |
import os
|
| 16 |
import platform
|
| 17 |
import subprocess
|
|
|
|
| 18 |
from pathlib import Path
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
return {
|
| 24 |
"os": platform.system(),
|
| 25 |
"arch": platform.machine(),
|
| 26 |
-
"is_apple_silicon":
|
| 27 |
-
"python_version": sys.version.split()[0]
|
| 28 |
}
|
| 29 |
|
| 30 |
-
|
|
|
|
| 31 |
info = get_system_info()
|
| 32 |
print("=================================================================")
|
| 33 |
-
print("🍎 EMGENA SENTINEL: APPLE SILICON (MLX)
|
| 34 |
-
print("=================================================================")
|
| 35 |
-
print(f"• Operating System: {info['os']} ({info['arch']})")
|
| 36 |
-
print(f"• Apple Silicon Metal Ready: {'✅ YES' if info['is_apple_silicon'] else '⚠️ NO (Cross-Platform Verification Mode)'}")
|
| 37 |
-
print(f"• Framework: Apple MLX (mlx_lm.lora)")
|
| 38 |
-
print(f"• Target Architecture: Qwen/Qwen2.5-Coder-7B-Instruct (4-Bit / 8-Bit)")
|
| 39 |
-
print(f"• Memory Architecture: Apple Unified Memory (Zero CPU-to-GPU transfer latency)")
|
| 40 |
-
print(f"• LoRA Hyperparameters:")
|
| 41 |
-
print(f" - Rank (r): 16 | Alpha: 32 | Dropout: 0.05")
|
| 42 |
-
print(f" - Target Layers: q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj")
|
| 43 |
-
print(f" - Batch Size: 4 (Scales with Unified RAM: 16GB, 36GB, 64GB, 128GB+)")
|
| 44 |
-
print(f" - Learning Rate: 1e-4 | Iterations: 600")
|
| 45 |
-
print(f" - Sequence Length: 2048 tokens")
|
| 46 |
print("=================================================================")
|
| 47 |
-
print("
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
def run_training():
|
| 51 |
-
info = get_system_info()
|
| 52 |
-
verify_recipe()
|
| 53 |
-
|
| 54 |
if not info["is_apple_silicon"]:
|
| 55 |
-
print("
|
| 56 |
-
print("To train via Apple MLX, execute this script on an Apple Silicon Mac (M1/M2/M3/M4).")
|
| 57 |
-
print("For NVIDIA GPUs, run 'python train_lora_unsloth.py' instead.")
|
| 58 |
return
|
| 59 |
|
| 60 |
try:
|
| 61 |
import mlx.core as mx
|
| 62 |
-
print(f"
|
| 63 |
except ImportError:
|
| 64 |
-
print("
|
| 65 |
-
print("Please run: pip install mlx mlx-lm")
|
| 66 |
sys.exit(1)
|
| 67 |
|
| 68 |
cmd = [
|
| 69 |
sys.executable, "-m", "mlx_lm.lora",
|
| 70 |
"--model", "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit",
|
| 71 |
-
"--train",
|
| 72 |
-
"--
|
| 73 |
-
"--
|
| 74 |
-
"--lora-layers", "16",
|
| 75 |
-
"--iters", "600",
|
| 76 |
-
"--learning-rate", "1e-4",
|
| 77 |
-
"--adapter-path", "./adapters_mlx"
|
| 78 |
]
|
| 79 |
-
print("\n🚀 Executing Native Apple Silicon MLX Training:")
|
| 80 |
-
print(" " + " ".join(cmd))
|
| 81 |
subprocess.run(cmd, check=True)
|
| 82 |
|
|
|
|
| 83 |
if __name__ == "__main__":
|
| 84 |
-
|
| 85 |
-
run_training()
|
| 86 |
-
else:
|
| 87 |
-
verify_recipe()
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
EMGENA SENTINEL v3.0 - NATIVE APPLE SILICON (MLX) FINE-TUNING ENGINE
|
| 4 |
+
Optimized for Apple M1/M2/M3/M4 (Unified Memory) using Apple's mlx-lm.
|
| 5 |
+
Automatically converts chatml_format.jsonl -> ./mlx_data/{train,valid}.jsonl on first run.
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
Usage:
|
| 8 |
+
python train_mlx.py # Verify hardware & parameters
|
| 9 |
+
python train_mlx.py --prepare-only # Build ./mlx_data/{train,valid}.jsonl and validate
|
| 10 |
+
python train_mlx.py --train # Prepare data + run Apple Silicon LoRA fine-tuning
|
| 11 |
"""
|
| 12 |
+
import json
|
| 13 |
import os
|
| 14 |
import platform
|
| 15 |
import subprocess
|
| 16 |
+
import sys
|
| 17 |
from pathlib import Path
|
| 18 |
|
| 19 |
+
ROOT = Path(__file__).resolve().parent
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def find_source_jsonl() -> Path:
|
| 23 |
+
for name in ("chatml_format.jsonl", "full_training_dataset.jsonl"):
|
| 24 |
+
p = ROOT / name
|
| 25 |
+
if p.exists() and p.stat().st_size > 0:
|
| 26 |
+
return p
|
| 27 |
+
for p in sorted(ROOT.glob("*.jsonl")):
|
| 28 |
+
if p.stat().st_size > 0:
|
| 29 |
+
return p
|
| 30 |
+
raise FileNotFoundError("No ChatML .jsonl dataset file found in package directory.")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def prepare_mlx_data() -> dict:
|
| 34 |
+
src = find_source_jsonl()
|
| 35 |
+
records = []
|
| 36 |
+
with src.open("r", encoding="utf-8") as f:
|
| 37 |
+
for line in f:
|
| 38 |
+
line = line.strip()
|
| 39 |
+
if not line:
|
| 40 |
+
continue
|
| 41 |
+
row = json.loads(line)
|
| 42 |
+
msgs = row.get("messages")
|
| 43 |
+
if isinstance(msgs, list) and msgs:
|
| 44 |
+
# mlx-lm supports native OpenAI {"messages": [...]} format cleanly
|
| 45 |
+
clean_msgs = [{"role": str(m.get("role", "user")), "content": str(m.get("content", ""))} for m in msgs]
|
| 46 |
+
records.append({"messages": clean_msgs})
|
| 47 |
+
|
| 48 |
+
if not records:
|
| 49 |
+
raise ValueError(f"Zero valid ChatML records parsed from {src.name}")
|
| 50 |
+
|
| 51 |
+
split_idx = max(1, int(len(records) * 0.9))
|
| 52 |
+
train_rows = records[:split_idx]
|
| 53 |
+
valid_rows = records[split_idx:] or records[-min(10, len(records)):]
|
| 54 |
+
|
| 55 |
+
out_dir = ROOT / "mlx_data"
|
| 56 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 57 |
+
with (out_dir / "train.jsonl").open("w", encoding="utf-8") as f:
|
| 58 |
+
for r in train_rows:
|
| 59 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 60 |
+
with (out_dir / "valid.jsonl").open("w", encoding="utf-8") as f:
|
| 61 |
+
for r in valid_rows:
|
| 62 |
+
f.write(json.dumps(r, ensure_ascii=False) + "\n")
|
| 63 |
+
|
| 64 |
+
return {"source": src.name, "train_count": len(train_rows), "valid_count": len(valid_rows), "dir": str(out_dir)}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_system_info() -> dict:
|
| 68 |
return {
|
| 69 |
"os": platform.system(),
|
| 70 |
"arch": platform.machine(),
|
| 71 |
+
"is_apple_silicon": (sys.platform == "darwin" and platform.machine() in ("arm64", "aarch64")),
|
| 72 |
+
"python_version": sys.version.split()[0],
|
| 73 |
}
|
| 74 |
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
info = get_system_info()
|
| 78 |
print("=================================================================")
|
| 79 |
+
print("🍎 EMGENA SENTINEL v3.0: APPLE SILICON (MLX) TRAINING ENGINE")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
print("=================================================================")
|
| 81 |
+
print(f"• OS / Arch: {info['os']} ({info['arch']}) | Python {info['python_version']}")
|
| 82 |
+
print(f"• Apple Silicon Metal: {'✅ YES' if info['is_apple_silicon'] else '⚠️ Cross-Platform Mode'}")
|
| 83 |
+
|
| 84 |
+
if "--prepare-only" in sys.argv or "--train" in sys.argv:
|
| 85 |
+
stats = prepare_mlx_data()
|
| 86 |
+
print(f"✅ Prepared MLX splits from {stats['source']}: train={stats['train_count']}, valid={stats['valid_count']} -> ./mlx_data")
|
| 87 |
+
if "--prepare-only" in sys.argv:
|
| 88 |
+
return
|
| 89 |
+
|
| 90 |
+
if "--train" not in sys.argv:
|
| 91 |
+
src = find_source_jsonl()
|
| 92 |
+
print(f"✅ Dataset located: {src.name} | Run '--prepare-only' or '--train' on M1-M4 Mac.")
|
| 93 |
+
return
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
if not info["is_apple_silicon"]:
|
| 96 |
+
print("⚠️ Non-Apple Silicon host detected. Run '--train' on an Apple Silicon Mac (M1-M4).")
|
|
|
|
|
|
|
| 97 |
return
|
| 98 |
|
| 99 |
try:
|
| 100 |
import mlx.core as mx
|
| 101 |
+
print(f"⚡ Apple MLX active: {mx.default_device()}")
|
| 102 |
except ImportError:
|
| 103 |
+
print("❌ Install MLX first: pip install mlx mlx-lm")
|
|
|
|
| 104 |
sys.exit(1)
|
| 105 |
|
| 106 |
cmd = [
|
| 107 |
sys.executable, "-m", "mlx_lm.lora",
|
| 108 |
"--model", "mlx-community/Qwen2.5-Coder-7B-Instruct-4bit",
|
| 109 |
+
"--train", "--data", str(ROOT / "mlx_data"),
|
| 110 |
+
"--batch-size", "4", "--lora-layers", "16", "--iters", "600",
|
| 111 |
+
"--learning-rate", "1e-4", "--adapter-path", str(ROOT / "adapters_mlx"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
]
|
|
|
|
|
|
|
| 113 |
subprocess.run(cmd, check=True)
|
| 114 |
|
| 115 |
+
|
| 116 |
if __name__ == "__main__":
|
| 117 |
+
main()
|
|
|
|
|
|
|
|
|
verify_dataset.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
EMGENA FACTORY v3.0 STRICT AST, SCHEMA, TRAINING & MCP VERIFIER
|
| 4 |
+
Verifies:
|
| 5 |
+
1. All *.jsonl, sharegpt_format.json, alpaca_format.json, dpo_format.json records + python code blocks via ast.parse
|
| 6 |
+
2. server.py / server_free.py / train_mlx.py / train_lora_unsloth.py syntax & zero external dependencies in MCP servers
|
| 7 |
+
3. Live MCP stdio JSON-RPC initialize -> tools/list -> tools/call (content[] spec)
|
| 8 |
+
4. Training scripts dry-run compatibility (train_lora_unsloth.py --dry-run & train_mlx.py)
|
| 9 |
+
"""
|
| 10 |
+
import ast
|
| 11 |
+
import json
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
if sys.platform == "win32":
|
| 17 |
+
try:
|
| 18 |
+
sys.stdout.reconfigure(encoding="utf-8")
|
| 19 |
+
except Exception:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _iter_strings(obj):
|
| 24 |
+
if isinstance(obj, str):
|
| 25 |
+
yield obj
|
| 26 |
+
elif isinstance(obj, dict):
|
| 27 |
+
for v in obj.values():
|
| 28 |
+
yield from _iter_strings(v)
|
| 29 |
+
elif isinstance(obj, list):
|
| 30 |
+
for v in obj:
|
| 31 |
+
yield from _iter_strings(v)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _check_python_blocks(text: str, loc: str, errors: list):
|
| 35 |
+
if "```python" in text:
|
| 36 |
+
for b in text.split("```python")[1:]:
|
| 37 |
+
code = b.split("```")[0].strip()
|
| 38 |
+
if not code:
|
| 39 |
+
continue
|
| 40 |
+
try:
|
| 41 |
+
ast.parse(code)
|
| 42 |
+
except SyntaxError as se:
|
| 43 |
+
errors.append(f"{loc} Python block AST error: {se}")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def verify():
|
| 47 |
+
root = Path(__file__).parent
|
| 48 |
+
errors = []
|
| 49 |
+
|
| 50 |
+
# 1. Verify JSONL files
|
| 51 |
+
for jl in sorted(root.glob("*.jsonl")):
|
| 52 |
+
if jl.parent.name == "mlx_data":
|
| 53 |
+
continue
|
| 54 |
+
with jl.open("r", encoding="utf-8") as f:
|
| 55 |
+
for lno, line in enumerate(f, 1):
|
| 56 |
+
if not line.strip():
|
| 57 |
+
continue
|
| 58 |
+
try:
|
| 59 |
+
obj = json.loads(line)
|
| 60 |
+
for m in obj.get("messages", []):
|
| 61 |
+
_check_python_blocks(str(m.get("content", "")), f"{jl.name}:{lno}", errors)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
errors.append(f"{jl.name}:{lno} JSON parse error: {e}")
|
| 64 |
+
|
| 65 |
+
# 2. Verify ShareGPT, Alpaca, DPO JSONs
|
| 66 |
+
for jf_name in ("sharegpt_format.json", "alpaca_format.json", "dpo_format.json"):
|
| 67 |
+
jf = root / jf_name
|
| 68 |
+
if jf.exists():
|
| 69 |
+
try:
|
| 70 |
+
arr = json.loads(jf.read_text(encoding="utf-8"))
|
| 71 |
+
if not isinstance(arr, list) or not arr:
|
| 72 |
+
errors.append(f"{jf_name} empty or invalid JSON list")
|
| 73 |
+
else:
|
| 74 |
+
for idx, item in enumerate(arr[:50]):
|
| 75 |
+
for s_val in _iter_strings(item):
|
| 76 |
+
_check_python_blocks(s_val, f"{jf_name}[{idx}]", errors)
|
| 77 |
+
except Exception as e:
|
| 78 |
+
errors.append(f"{jf_name} invalid JSON: {e}")
|
| 79 |
+
|
| 80 |
+
# 3. Verify Python scripts AST & MCP stdio if present
|
| 81 |
+
for pyf in ("server.py", "server_free.py", "eval_benchmark.py", "dashboard.py", "train_mlx.py", "train_lora_unsloth.py"):
|
| 82 |
+
p = root / pyf
|
| 83 |
+
if p.exists():
|
| 84 |
+
try:
|
| 85 |
+
ast.parse(p.read_text(encoding="utf-8"))
|
| 86 |
+
except SyntaxError as se:
|
| 87 |
+
errors.append(f"{pyf} SyntaxError: {se}")
|
| 88 |
+
|
| 89 |
+
srv = root / "server.py"
|
| 90 |
+
if srv.exists():
|
| 91 |
+
try:
|
| 92 |
+
proc = subprocess.Popen(
|
| 93 |
+
[sys.executable, str(srv)],
|
| 94 |
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8"
|
| 95 |
+
)
|
| 96 |
+
proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}) + "\n")
|
| 97 |
+
proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}) + "\n")
|
| 98 |
+
proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "audit", "arguments": {"code_content": "def clean():\n return 1\n"}}}) + "\n")
|
| 99 |
+
proc.stdin.flush()
|
| 100 |
+
proc.stdin.close()
|
| 101 |
+
lines = [ln for ln in proc.stdout.read().splitlines() if ln.strip()]
|
| 102 |
+
proc.wait(timeout=3)
|
| 103 |
+
if len(lines) < 3:
|
| 104 |
+
errors.append(f"MCP stdio returned only {len(lines)} responses")
|
| 105 |
+
else:
|
| 106 |
+
r3 = json.loads(lines[2])
|
| 107 |
+
content = r3.get("result", {}).get("content", [])
|
| 108 |
+
if not content or content[0].get("type") != "text":
|
| 109 |
+
errors.append("MCP tools/call missing standard result.content[] array")
|
| 110 |
+
except Exception as e:
|
| 111 |
+
errors.append(f"MCP live stdio test failed: {e}")
|
| 112 |
+
|
| 113 |
+
# 4. Dry-run training script
|
| 114 |
+
up = root / "train_lora_unsloth.py"
|
| 115 |
+
if up.exists():
|
| 116 |
+
dr = subprocess.run([sys.executable, str(up), "--dry-run"], capture_output=True, text=True)
|
| 117 |
+
if dr.returncode != 0:
|
| 118 |
+
errors.append(f"train_lora_unsloth.py --dry-run failed: {dr.stderr[:120]}")
|
| 119 |
+
|
| 120 |
+
if errors:
|
| 121 |
+
print(f"❌ Verification failed ({len(errors)} errors):")
|
| 122 |
+
for e in errors[:10]:
|
| 123 |
+
print(f" - {e}")
|
| 124 |
+
sys.exit(1)
|
| 125 |
+
print("✅ 100% Factory v3.0 Invariance Verified (AST + Datasets + MCP Spec + Training Dry-Run)!")
|
| 126 |
+
sys.exit(0)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
verify()
|