rcdebug 1.0.0__py3-none-any.whl

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.
@@ -0,0 +1,115 @@
1
+ """
2
+ 120-Source Light Luau Debugger Pack loader and static probe engine.
3
+
4
+ Loads 120 lightweight Luau debugging, linting, profiling, memory-leak,
5
+ and security probes from data/luau_debugger_pack_120.json.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from dataclasses import dataclass
13
+ from functools import lru_cache
14
+ from pathlib import Path
15
+ from typing import Pattern
16
+
17
+ from .models import Finding
18
+
19
+ PACK_JSON_PATH = Path(__file__).resolve().parent / "data" / "luau_debugger_pack_120.json"
20
+ EXPECTED_PACK_COUNT = 120
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class DebuggerProbe:
25
+ id: str
26
+ source: str
27
+ category: str
28
+ severity: str
29
+ name: str
30
+ pattern: Pattern[str]
31
+ raw_pattern: str
32
+ root_cause: str
33
+ fix: str
34
+
35
+
36
+ class LuauDebuggerPack:
37
+ """Compiled 120-probe Light Luau Debugger Pack."""
38
+
39
+ def __init__(self, probes: tuple[DebuggerProbe, ...]) -> None:
40
+ self.probes = probes
41
+ self._by_id: dict[str, DebuggerProbe] = {p.id: p for p in probes}
42
+
43
+ def count(self) -> int:
44
+ return len(self.probes)
45
+
46
+ def get(self, probe_id: str) -> DebuggerProbe | None:
47
+ return self._by_id.get(probe_id.upper())
48
+
49
+ def search(self, query: str = "", limit: int = 20) -> list[DebuggerProbe]:
50
+ q = query.strip().lower()
51
+ if not q:
52
+ return list(self.probes[:limit])
53
+ matches = [
54
+ p
55
+ for p in self.probes
56
+ if q in p.name.lower()
57
+ or q in p.source.lower()
58
+ or q in p.category.lower()
59
+ or q in p.root_cause.lower()
60
+ ]
61
+ return matches[:limit]
62
+
63
+ def scan_source(self, script_path: str, source: str, limit: int = 25) -> list[Finding]:
64
+ """Runs all 120 precompiled Luau debugger probes against a script."""
65
+ findings: list[Finding] = []
66
+ for probe in self.probes:
67
+ if probe.pattern.search(source):
68
+ findings.append(
69
+ Finding(
70
+ severity=probe.severity,
71
+ category=f"LuauPack:{probe.category}",
72
+ title=f"[{probe.id}] {probe.name} ({probe.source})",
73
+ path=script_path,
74
+ flaw=probe.root_cause,
75
+ abuse=f"Detected by {probe.source} diagnostic '{probe.name}'.",
76
+ fix=probe.fix,
77
+ metadata={"pack_id": probe.id, "source": probe.source},
78
+ )
79
+ )
80
+ if len(findings) >= limit:
81
+ break
82
+ return findings
83
+
84
+
85
+ def load_debugger_pack(json_path: Path = PACK_JSON_PATH) -> tuple[DebuggerProbe, ...]:
86
+ if not json_path.exists():
87
+ raise FileNotFoundError(f"Luau debugger pack not found: {json_path}")
88
+
89
+ raw_items = json.loads(json_path.read_text(encoding="utf-8"))
90
+ if not isinstance(raw_items, list) or len(raw_items) != EXPECTED_PACK_COUNT:
91
+ count = len(raw_items) if isinstance(raw_items, list) else 0
92
+ raise ValueError(f"Expected {EXPECTED_PACK_COUNT} probes in {json_path}, found {count}")
93
+
94
+ probes: list[DebuggerProbe] = []
95
+ for item in raw_items:
96
+ probes.append(
97
+ DebuggerProbe(
98
+ id=str(item["id"]),
99
+ source=str(item["source"]),
100
+ category=str(item["category"]),
101
+ severity=str(item["severity"]),
102
+ name=str(item["name"]),
103
+ pattern=re.compile(str(item["pattern"]), re.MULTILINE),
104
+ raw_pattern=str(item["pattern"]),
105
+ root_cause=str(item["root_cause"]),
106
+ fix=str(item["fix"]),
107
+ )
108
+ )
109
+ return tuple(probes)
110
+
111
+
112
+ @lru_cache(maxsize=1)
113
+ def get_debugger_pack() -> LuauDebuggerPack:
114
+ """Returns the cached 120-probe Light Luau Debugger Pack."""
115
+ return LuauDebuggerPack(probes=load_debugger_pack())
rcdebug/exporter.py ADDED
@@ -0,0 +1,135 @@
1
+ """
2
+ Markdown Security & QA Audit Report generator for rcdebug (--export <file.md>).
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from pathlib import Path
8
+
9
+ from .models import SEVERITY_ORDER, AuditSession, Finding, SeverityFilter, format_filter_label, matches_filter
10
+
11
+
12
+ def generate_markdown_report(session: AuditSession, filter_level: SeverityFilter = None) -> str:
13
+ filtered_findings: list[Finding] = [
14
+ f for f in session.findings if matches_filter(f.severity, filter_level)
15
+ ]
16
+ # Sort findings strictly by (severity_tier, catalog_rank_asc, confidence_desc)
17
+ filtered_findings.sort(key=lambda f: f.sort_key())
18
+
19
+ counts = {"CRITICAL": 0, "WARN": 0, "INFO": 0}
20
+ for f in filtered_findings:
21
+ counts[f.severity] = counts.get(f.severity, 0) + 1
22
+
23
+ lines: list[str] = [
24
+ "# rcdebug — Roblox Security & Performance Audit Report",
25
+ "",
26
+ "## 1. Executive Summary",
27
+ "",
28
+ "| Field | Value |",
29
+ "| :--- | :--- |",
30
+ f"| **Audit Mode** | `{session.mode.upper()}` |",
31
+ f"| **Target** | `{session.target_name}` |",
32
+ f"| **Session Timestamp** | `{session.started_at}` |",
33
+ f"| **Severity Filter** | `{format_filter_label(filter_level) if filter_level else 'ALL'}` |",
34
+ f"| **Total Findings** | **{len(filtered_findings)}** (`{counts['CRITICAL']}` Critical, `{counts['WARN']}` Warn, `{counts['INFO']}` Info) |",
35
+ "",
36
+ ]
37
+
38
+ # Overview table
39
+ lines.extend([
40
+ "## 2. Findings Overview",
41
+ "",
42
+ ])
43
+
44
+ if not filtered_findings:
45
+ lines.append("_No findings recorded matching the active filter criteria._")
46
+ lines.append("")
47
+ else:
48
+ lines.extend([
49
+ "| # | Severity | Category | Title | Instance Path |",
50
+ "| :--- | :--- | :--- | :--- | :--- |",
51
+ ])
52
+ for idx, f in enumerate(filtered_findings, start=1):
53
+ lines.append(
54
+ f"| {idx} | **{f.severity}** | `{f.category}` | {f.title} | `{f.path}` |"
55
+ )
56
+ lines.append("")
57
+
58
+ lines.extend([
59
+ "## 3. Detailed Security & Architectural Findings",
60
+ "",
61
+ ])
62
+
63
+ for idx, f in enumerate(filtered_findings, start=1):
64
+ lines.extend([
65
+ f"### 3.{idx} [{f.severity}] {f.title}",
66
+ "",
67
+ f"- **Instance Path:** `{f.path}`",
68
+ f"- **Category:** `{f.category}`",
69
+ f"- **Detected At:** `{f.timestamp}`",
70
+ f"- **Architectural Flaw:** {f.flaw}",
71
+ f"- **Malicious Client Abuse Vector:** {f.abuse}",
72
+ f"- **Recommended Server-Side Fix:** {f.fix}",
73
+ "",
74
+ ])
75
+ if f.code_example:
76
+ lines.extend([
77
+ "```luau",
78
+ f.code_example.strip(),
79
+ "```",
80
+ "",
81
+ ])
82
+
83
+ # Remote Traffic Profiler Section
84
+ if session.remote_traffic:
85
+ lines.extend([
86
+ "## 4. Remote Traffic Profiler Summary",
87
+ "",
88
+ "| Remote Path | Class | Total Calls | Peak Rate (calls/s) | Last Rate (calls/s) | Cooldown Flag |",
89
+ "| :--- | :--- | :--- | :--- | :--- | :--- |",
90
+ ])
91
+ for stat in sorted(
92
+ session.remote_traffic.values(),
93
+ key=lambda s: (-s.peak_rate_per_sec, -s.total_calls),
94
+ ):
95
+ flag = "NEEDS DEBOUNCE" if stat.has_cooldown_warning else "OK"
96
+ lines.append(
97
+ f"| `{stat.remote_path}` | `{stat.remote_type}` | {stat.total_calls} | "
98
+ f"{stat.peak_rate_per_sec:.1f}/s | {stat.last_rate_per_sec:.1f}/s | **{flag}** |"
99
+ )
100
+ lines.append("")
101
+
102
+ # Memory & Instance Diffing Section
103
+ if session.memory_snapshots:
104
+ lines.extend([
105
+ "## 5. Instance & Memory Diffing Timeline",
106
+ "",
107
+ "| Snapshot Time | Elapsed (s) | Workspace Instances | Player Instances | Total Memory (MB) |",
108
+ "| :--- | :--- | :--- | :--- | :--- |",
109
+ ])
110
+ for snap in session.memory_snapshots:
111
+ lines.append(
112
+ f"| `{snap.timestamp}` | {snap.elapsed_sec:.1f}s | "
113
+ f"{snap.workspace_instances} | {snap.player_instances} | {snap.total_memory_mb:.2f} MB |"
114
+ )
115
+ lines.append("")
116
+
117
+ lines.extend([
118
+ "---",
119
+ "_Generated by **rcdebug (Revan Cool Debugger)** v1.0.0_",
120
+ "",
121
+ ])
122
+
123
+ return "\n".join(lines)
124
+
125
+
126
+ def export_markdown_report(
127
+ session: AuditSession,
128
+ output_path: str | Path,
129
+ filter_level: str | None = None,
130
+ ) -> Path:
131
+ dest = Path(output_path).expanduser().resolve()
132
+ dest.parent.mkdir(parents=True, exist_ok=True)
133
+ report_md = generate_markdown_report(session, filter_level=filter_level)
134
+ dest.write_text(report_md, encoding="utf-8")
135
+ return dest