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ead
e546ade
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#!/usr/bin/env python3
"""

EMGENA SENTINEL MCP SERVER - COMMUNITY EVALUATION EDITION (CC-BY-NC-4.0)

Package: agent_longterm_memory_context_rot_purger

Title: Agent Longterm Memory Context Rot Purger

Upgrade to Commercial Pro (Unlimited AST Scans + CI/CD SARIF Gate + B2B VAT Invoice):

https://emgena.com/trainingslager?product=agent_longterm_memory_context_rot_purger&coupon=LAUNCH20

"""

import sys, os, json, ast, time, re
from pathlib import Path
from typing import Any, Dict, List, Tuple

if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass

SESSION_SCANS = 0
MAX_FREE_SCANS = 5
UPGRADE_URL = "https://emgena.com/trainingslager?product=agent_longterm_memory_context_rot_purger&coupon=LAUNCH20"


import math as _math

SAFE_VALUE_MARKERS = (
    "redacted", "placeholder", "example", "changeme", "your_", "dummy", "mock",
    "***", "xxxx", "<", "alias/", "vault:", "kms:", "secret_ref", "env:",
    "os.environ", "getenv", "test_", "rfc2606", "rfc5737",
)

def _shannon_entropy(data: str) -> float:
    if not data:
        return 0.0
    freq = {}
    for ch in data:
        freq[ch] = freq.get(ch, 0) + 1
    length = len(data)
    return -sum((cnt / length) * _math.log2(cnt / length) for cnt in freq.values())

def _mask_preview(val: str) -> str:
    s = str(val).replace("\n", " ").strip()
    if len(s) <= 8:
        return "****"
    return s[:4] + "****" + s[-4:]

def _call_name(node: ast.Call) -> str:
    if isinstance(node.func, ast.Name):
        return node.func.id.lower()
    if isinstance(node.func, ast.Attribute):
        return node.func.attr.lower()
    return ""

def _full_attr_name(node: ast.AST) -> str:
    parts = []
    cur = node
    while isinstance(cur, ast.Attribute):
        parts.append(cur.attr.lower())
        cur = cur.value
    if isinstance(cur, ast.Name):
        parts.append(cur.id.lower())
    return ".".join(reversed(parts))

def _has_kw(node: ast.Call, name: str) -> bool:
    return any(kw.arg and kw.arg.lower() == name.lower() for kw in node.keywords)


DOMAIN_REGEX_RULES = [
    ("EMGENA-SRE-001", "HIGH", "CWE-1333", "Potential catastrophic ReDoS nested quantifier regex",
     re.compile(r"\([^)]*[+*][^)]*\)[+*]")),
    ("EMGENA-SRE-002", "HIGH", "CWE-400", "Unbounded top_k / batch size or missing backpressure limit",
     re.compile(r"(?:top_k|limit|batch_size)\s*=\s*(?:100000|999999|None)\b")),
]

class DomainASTVisitor(ast.NodeVisitor):
    """Inspects AsyncIO event loop blocking, bare excepts, unbounded loops, and unclosed resources."""
    def __init__(self, pro_mode: bool = True):
        self.pro_mode = pro_mode
        self.in_async = False
        self.findings = []

    def visit_AsyncFunctionDef(self, node):
        prev = self.in_async
        self.in_async = True
        self.generic_visit(node)
        self.in_async = prev

    def visit_FunctionDef(self, node):
        prev = self.in_async
        self.in_async = False
        self.generic_visit(node)
        self.in_async = prev

    def visit_ExceptHandler(self, node):
        if node.type is None:
            self.findings.append({
                "rule_id": "EMGENA-SRE-AST-101", "severity": "HIGH", "cwe": "CWE-396",
                "line": getattr(node, "lineno", 1),
                "message": "Bare 'except:' handler catches asyncio.CancelledError and SystemExit.",
                "preview": "except:",
                "remediation": "Catch specific exceptions (except ValueError / RuntimeError) and propagate CancelledError."
            })
        self.generic_visit(node)

    def visit_While(self, node):
        if isinstance(node.test, ast.Constant) and node.test.value is True:
            has_exit = any(isinstance(n, (ast.Break, ast.Return, ast.Raise)) for n in ast.walk(node))
            if not has_exit:
                self.findings.append({
                    "rule_id": "EMGENA-SRE-AST-102", "severity": "CRITICAL", "cwe": "CWE-835",
                    "line": getattr(node, "lineno", 1),
                    "message": "Infinite 'while True:' loop without break/return/raise guard.",
                    "preview": "while True: ...",
                    "remediation": "Add bounded max_iterations, deadline check, and deterministic exit condition."
                })
        self.generic_visit(node)

    def visit_Call(self, node):
        full = _full_attr_name(node.func)
        line = getattr(node, "lineno", 1)

        if self.in_async and full in (
            "time.sleep", "requests.get", "requests.post", "requests.put", "requests.delete",
            "urllib.request.urlopen", "subprocess.run", "subprocess.call", "subprocess.check_output"
        ):
            self.findings.append({
                "rule_id": "EMGENA-SRE-AST-201", "severity": "CRITICAL", "cwe": "CWE-400", "line": line,
                "message": f"Synchronous blocking call '{full}()' inside async coroutine stalls the event loop.",
                "preview": f"async -> {full}(...)",
                "remediation": "Use asyncio.sleep() / httpx.AsyncClient / asyncio.create_subprocess_exec() or asyncio.to_thread()."
            })

        if self.pro_mode and full in ("requests.get", "requests.post", "urllib.request.urlopen", "httpx.get", "httpx.post") and not _has_kw(node, "timeout"):
            self.findings.append({
                "rule_id": "EMGENA-SRE-AST-202", "severity": "HIGH", "cwe": "CWE-400", "line": line,
                "message": f"Network call '{full}()' missing timeout risks thread/worker exhaustion.",
                "preview": f"{full}(...)",
                "remediation": "Configure strict connect and read timeouts."
            })
        self.generic_visit(node)


SCAN_EXTENSIONS = {".py", ".js", ".ts", ".jsx", ".tsx", ".env", ".json", ".yaml", ".yml", ".sh", ".toml", ".tf", ".ini", ".sql"}
SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", "mlx_data"}

def run_domain_ast_scan(code: str, pro_mode: bool = True) -> list:
    findings = []
    if not code or not code.strip():
        return findings

    rules = DOMAIN_REGEX_RULES if pro_mode else DOMAIN_REGEX_RULES[:4]
    for lineno, raw_line in enumerate(code.splitlines(), 1):
        code_no_comment = raw_line.split("#")[0]
        low = code_no_comment.lower()
        if any(m in low for m in ("redacted", "placeholder", "example_only", "safe_sanitized", "***")):
            continue
        for rule_id, sev, cwe, desc, pat in rules:
            m = pat.search(code_no_comment)
            if m:
                findings.append({
                    "rule_id": rule_id,
                    "severity": sev,
                    "cwe": cwe,
                    "line": lineno,
                    "message": desc,
                    "preview": _mask_preview(m.group(0)),
                    "remediation": "Remediate detected policy violation before execution or commit."
                })

    try:
        tree = ast.parse(code)
        visitor = DomainASTVisitor(pro_mode=pro_mode)
        visitor.visit(tree)
        findings.extend(visitor.findings)
    except SyntaxError as e:
        findings.append({
            "rule_id": "EMGENA-SYNTAX-000",
            "severity": "CRITICAL",
            "cwe": "CWE-20",
            "line": getattr(e, "lineno", 1) or 1,
            "message": f"Python AST SyntaxError: {e.msg}",
            "preview": str(e.text or "").strip()[:60],
            "remediation": "Fix Python syntax before deploying or loading into MCP context."
        })

    seen = set()
    unique = []
    for f in findings:
        key = (f["rule_id"], f["line"])
        if key not in seen:
            seen.add(key)
            unique.append(f)
    return unique

def scan_directory_or_file(target_path: str) -> dict:
    p = Path(target_path)
    files = [p] if p.is_file() else [
        f for f in p.rglob("*")
        if f.is_file() and (f.suffix.lower() in SCAN_EXTENSIONS or f.name.startswith(".env"))
        and not any(sd in f.parts for sd in SKIP_DIRS)
        and f.name not in ("server.py", "server_free.py")
    ]
    all_results = []
    for fp in files:
        try:
            txt = fp.read_text(encoding="utf-8", errors="ignore")
        except Exception:
            continue
        if len(txt) > 512 * 1024:
            continue
        hits = run_domain_ast_scan(txt, pro_mode=True)
        for h in hits:
            h["file"] = str(fp)
            all_results.append(h)
    return {"files_scanned": len(files), "total_findings": len(all_results), "findings": all_results}

def build_sarif(scan_res: dict, pkg_id: str) -> dict:
    runs_results = []
    for f in scan_res["findings"]:
        runs_results.append({
            "ruleId": f["rule_id"],
            "level": "error" if f["severity"] == "CRITICAL" else "warning",
            "message": {"text": f"{f['message']} ({f['preview']}) -> {f['remediation']}"},
            "locations": [{
                "physicalLocation": {
                    "artifactLocation": {"uri": f.get("file", "unknown")},
                    "region": {"startLine": int(f.get("line", 1))}
                }
            }]
        })
    return {
        "version": "2.1.0",
        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
        "runs": [{
            "tool": {"driver": {"name": f"EMGENA-{pkg_id}", "version": "3.0.0"}},
            "results": runs_results
        }]
    }


def _legacy_package_check(code: str, code_text: str, tool_name: str) -> bool:
    return False

def execute_tool(tool_name: str, arguments: dict) -> dict:
    global SESSION_SCANS
    if SESSION_SCANS >= MAX_FREE_SCANS:
        return {
            "package": "agent_longterm_memory_context_rot_purger",
            "defect_detected": False,
            "is_safe": False,
            "status": "COMMUNITY_LIMIT_REACHED",
            "error": f"Community Edition limit ({MAX_FREE_SCANS} scans/session) reached. Unlock Commercial Pro (code LAUNCH20): {UPGRADE_URL}",
            "_emgena_commercial_pro": {"upgrade_url": UPGRADE_URL, "coupon": "LAUNCH20"}
        }
    SESSION_SCANS += 1
    if not isinstance(arguments, dict):
        arguments = {}
    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 "")
    if not isinstance(code, str):
        code = json.dumps(code, ensure_ascii=False)
    if not code.strip():
        return {"package": "agent_longterm_memory_context_rot_purger", "defect_detected": False, "is_safe": True, "status": "EMPTY_CODE", "findings": []}

    ast_valid = True
    try:
        ast.parse(code)
    except SyntaxError:
        ast_valid = False

    lines = [l.split("#")[0] for l in code.splitlines()]
    code_text = "\n".join(lines).lower()
    real_findings = run_domain_ast_scan(code, pro_mode=False)
    legacy_hit = _legacy_package_check(code, code_text, tool_name) if ast_valid else False
    defect_detected = bool(real_findings) or legacy_hit or (not ast_valid)

    return {
        "package": "agent_longterm_memory_context_rot_purger",
        "tool": tool_name,
        "edition": "COMMUNITY_EVALUATION (CC-BY-NC-4.0)",
        "status": "VIOLATION_DETECTED" if defect_detected else "PASS_VALIDATED",
        "defect_detected": defect_detected,
        "is_safe": not defect_detected,
        "scans_remaining": max(0, MAX_FREE_SCANS - SESSION_SCANS),
        "findings": real_findings,
        "_emgena_pro_notice": f"Commercial deployment or CI/CD --sarif requires Commercial License -> {UPGRADE_URL}"
    }

TOOLS_SPEC = [
  {
    "name": "calculate_memory_decay_score",
    "description": "Computes exponential half-life decay scores for long-term memory vectors based on age and access frequency.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  },
  {
    "name": "purge_expired_ephemeral_memories",
    "description": "Automatically deletes transient memories older than 7 days.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  },
  {
    "name": "compact_vector_tombstones",
    "description": "Executes background vacuum and compaction to reclaim storage from soft-deleted vectors in Qdrant/Chroma.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  },
  {
    "name": "consolidate_duplicate_memory_clusters",
    "description": "Merges highly similar memory embeddings into unified authoritative knowledge nodes.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  },
  {
    "name": "audit_context_retrieval_relevance",
    "description": "Tracks whether retrieved long-term memories were actually referenced in final LLM completions.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  },
  {
    "name": "quarantine_obsolete_codebase_assumptions",
    "description": "Identifies and purges cached assumptions about deleted files or refactored functions.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  },
  {
    "name": "fuzz_rapid_memory_churn_and_compaction",
    "description": "Simulates continuous write-delete cycles to verify index compaction does not degrade search latency.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  },
  {
    "name": "circuit_break_context_pollution",
    "description": "Purges bottom 20% lowest-scoring memories if retrieval noise causes task failure rates to spike.",
    "inputSchema": {
      "type": "object",
      "properties": {
        "code_content": {
          "type": "string"
        }
      },
      "required": [
        "code_content"
      ]
    }
  }
]
TOOLS = TOOLS_SPEC

def process_message(message: dict) -> dict:
    msg_id = message.get("id")
    method = message.get("method")
    params = message.get("params", {}) or {}
    if method == "initialize":
        return {
            "jsonrpc": "2.0", "id": msg_id,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {"listChanged": False}},
                "serverInfo": {"name": "agent_longterm_memory_context_rot_purger_community", "version": "3.0.0-free"}
            }
        }
    elif method == "notifications/initialized":
        return None
    elif method == "tools/list":
        return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
    elif method == "tools/call":
        tname = params.get("name", "")
        args = params.get("arguments", {})
        tool_res = execute_tool(tname, args)
        return {
            "jsonrpc": "2.0", "id": msg_id,
            "result": {
                "content": [{"type": "text", "text": json.dumps(tool_res, indent=2, ensure_ascii=False)}],
                "isError": False
            }
        }
    return {"jsonrpc": "2.0", "id": msg_id, "result": {}}

def main():
    if "--scan" in sys.argv:
        print(f"CLI --scan & --sarif CI/CD Gate requires Commercial Pro. Unlock with LAUNCH20: {UPGRADE_URL}")
        sys.exit(2)
    while True:
        line = sys.stdin.readline()
        if not line:
            break
        line = line.strip()
        if not line:
            continue
        try:
            req = json.loads(line)
            resp = process_message(req)
            if resp is not None:
                sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
                sys.stdout.flush()
        except Exception as e:
            sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}) + "\n")
            sys.stdout.flush()

if __name__ == "__main__":
    main()