tzero-mcp 11.14.0 → 11.15.2

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 (38) hide show
  1. package/LICENSE +661 -21
  2. package/NOTICE +22 -0
  3. package/README.md +3 -3
  4. package/index.js +5 -0
  5. package/package.json +3 -2
  6. package/src/addmcp.py +2 -2
  7. package/src/app.py +1 -1
  8. package/src/tzero/__init__.py +5 -0
  9. package/src/tzero/tzero_benchmark.py +2 -2
  10. package/src/tzero/tzero_blackboard.py +1 -1
  11. package/src/tzero/tzero_budget.py +1 -1
  12. package/src/tzero/tzero_ci.py +658 -10
  13. package/src/tzero/tzero_commit.py +1 -1
  14. package/src/tzero/tzero_contracts.py +2 -2
  15. package/src/tzero/tzero_cost.py +1 -1
  16. package/src/tzero/tzero_dashboard.py +3 -3
  17. package/src/tzero/tzero_debt.py +1 -1
  18. package/src/tzero/tzero_drift.py +1 -1
  19. package/src/tzero/tzero_explain.py +1 -1
  20. package/src/tzero/tzero_golden.py +2 -2
  21. package/src/tzero/tzero_infra.py +1 -1
  22. package/src/tzero/tzero_jarvis/__init__.py +15 -1
  23. package/src/tzero/tzero_jarvis/agent_guard.py +620 -0
  24. package/src/tzero/tzero_jarvis/creative_director.py +1 -1
  25. package/src/tzero/tzero_jarvis/orchestrator.py +36 -34
  26. package/src/tzero/tzero_jarvis/self_healing.py +325 -250
  27. package/src/tzero/tzero_lsp.py +1 -1
  28. package/src/tzero/tzero_mcp.py +121 -63
  29. package/src/tzero/tzero_promo.py +504 -0
  30. package/src/tzero/tzero_replay.py +1 -1
  31. package/src/tzero/tzero_semantic_merge.py +1 -1
  32. package/src/tzero/tzero_stubs.py +1 -1
  33. package/src/tzero/tzero_task_benchmark.py +2 -2
  34. package/src/tzero/tzero_tui.py +2 -2
  35. package/src/tzero/tzero_turbo.py +1 -1
  36. package/src/tzero/tzero_v3.py +61 -8
  37. package/src/tzero/tzero_welcome.py +2 -2
  38. package/test/package.test.js +1 -1
@@ -0,0 +1,620 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Deterministic, Zero-Spend AI Agent Guardrails and Execution Safety Engine.
3
+
4
+ Provides multi-layer security policies, path protection, command risk assessment,
5
+ secret redaction, transactional file modification, and AI grounding verification.
6
+ Operates 100% locally and offline with zero cloud API dependencies.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import enum
12
+ import hashlib
13
+ import io
14
+ import math
15
+ import os
16
+ from pathlib import Path
17
+ import re
18
+ import shlex
19
+ import time
20
+ import tokenize
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Dict, List, Optional, Set, Tuple, Union
23
+
24
+
25
+ # ==============================================================================
26
+ # 1. COMMAND RISK ASSESSMENT & EXECUTION POLICY
27
+ # ==============================================================================
28
+
29
+ class CommandRiskLevel(str, enum.Enum):
30
+ SAFE_READ_ONLY = "SAFE_READ_ONLY"
31
+ WORKSPACE_MUTATION = "WORKSPACE_MUTATION"
32
+ NETWORK_OR_PACKAGE = "NETWORK_OR_PACKAGE"
33
+ DESTRUCTIVE = "DESTRUCTIVE"
34
+ BLOCKED_OR_SUSPICIOUS = "BLOCKED_OR_SUSPICIOUS"
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class CommandEvaluation:
39
+ command: str
40
+ risk_level: CommandRiskLevel
41
+ allowed: bool
42
+ reason: str
43
+ argv: Optional[List[str]] = None
44
+ is_chained: bool = False
45
+ has_redirection: bool = False
46
+ has_substitution: bool = False
47
+ involves_network: bool = False
48
+ involves_package_install: bool = False
49
+ involves_destruction: bool = False
50
+
51
+ def to_dict(self) -> Dict[str, Any]:
52
+ return {
53
+ "command": self.command,
54
+ "risk_level": self.risk_level.value,
55
+ "allowed": self.allowed,
56
+ "reason": self.reason,
57
+ "argv": self.argv,
58
+ "is_chained": self.is_chained,
59
+ "has_redirection": self.has_redirection,
60
+ "has_substitution": self.has_substitution,
61
+ "involves_network": self.involves_network,
62
+ "involves_package_install": self.involves_package_install,
63
+ "involves_destruction": self.involves_destruction,
64
+ }
65
+
66
+
67
+ class CommandRiskAssessor:
68
+ """Evaluates commands for shell injection, network access, and risk level."""
69
+
70
+ NETWORK_BINARIES: Set[str] = {
71
+ "curl", "wget", "nc", "ncat", "netcat", "ssh", "scp", "sftp", "ftp",
72
+ "telnet", "invoke-webrequest", "iwr", "irm", "bitsadmin", "nmap",
73
+ "socat", "rclone", "rsync"
74
+ }
75
+
76
+ PACKAGE_MANAGERS: Set[str] = {
77
+ "pip", "pip3", "npm", "yarn", "pnpm", "poetry", "cargo", "gem",
78
+ "apt", "apt-get", "yum", "brew", "choco", "winget", "conda"
79
+ }
80
+
81
+ DESTRUCTIVE_COMMANDS: Set[str] = {
82
+ "rm", "del", "erase", "format", "dd", "mkfs", "fdisk", "shred",
83
+ "truncate", "wipefs"
84
+ }
85
+
86
+ SAFE_READ_COMMANDS: Set[str] = {
87
+ "git status", "git diff", "git log", "git show", "git branch",
88
+ "flake8", "pytest", "python -m unittest", "python -m pytest",
89
+ "mypy", "dir", "ls", "echo", "pwd", "whoami"
90
+ }
91
+
92
+ # Detect shell chaining: &&, ||, ;, single & (backgrounding or chaining)
93
+ RE_CHAINING = re.compile(r'(?:&&|\|\||;|(?<!\d)&(?!\d))')
94
+ # Detect redirection: >, >>, <, | (pipes)
95
+ RE_REDIRECTION = re.compile(r'(?:>>|>|<|\|(?!\|))')
96
+ # Detect command substitution or variable expansion exploits
97
+ RE_SUBSTITUTION = re.compile(r'(?:\$\([^)]+\)|`[^`]+`|\$env:[A-Za-z0-9_]+|%[A-Za-z0-9_]+%)')
98
+
99
+ @classmethod
100
+ def parse_argv(cls, command: str) -> Optional[List[str]]:
101
+ """Attempt safe lexical splitting without invoking a host shell."""
102
+ cmd_clean = (command or "").strip()
103
+ if not cmd_clean:
104
+ return None
105
+ try:
106
+ # On Windows, posix=False preserves quotes and backslashes properly
107
+ posix_mode = (os.name != "nt")
108
+ parts = shlex.split(cmd_clean, posix=posix_mode)
109
+ # Clean up outer quotes if on Windows
110
+ if not posix_mode:
111
+ parts = [p.strip('"\'') if (p.startswith(('"', "'")) and p.endswith(('"', "'"))) else p for p in parts]
112
+ return parts if parts else None
113
+ except Exception:
114
+ return None
115
+
116
+ @classmethod
117
+ def assess(cls, command: str) -> CommandEvaluation:
118
+ """Classify command risk level and identify dangerous primitives."""
119
+ cmd_clean = (command or "").strip()
120
+ if not cmd_clean:
121
+ return CommandEvaluation(
122
+ command=command,
123
+ risk_level=CommandRiskLevel.BLOCKED_OR_SUSPICIOUS,
124
+ allowed=False,
125
+ reason="Empty command."
126
+ )
127
+
128
+ is_chained = bool(cls.RE_CHAINING.search(cmd_clean))
129
+ has_redirection = bool(cls.RE_REDIRECTION.search(cmd_clean))
130
+ has_substitution = bool(cls.RE_SUBSTITUTION.search(cmd_clean))
131
+
132
+ argv = cls.parse_argv(cmd_clean)
133
+ first_token = (argv[0].lower() if argv else cmd_clean.split()[0].lower()).replace("\\", "/")
134
+ binary_name = Path(first_token).name.lower()
135
+ if binary_name.endswith(".exe"):
136
+ binary_name = binary_name[:-4]
137
+
138
+ # Check package installation commands
139
+ involves_package_install = False
140
+ if binary_name in cls.PACKAGE_MANAGERS:
141
+ involves_package_install = True
142
+ elif len(argv or []) >= 3 and argv[0].lower().endswith("python") and argv[1].lower() == "-m" and argv[2].lower() == "pip":
143
+ involves_package_install = True
144
+
145
+ # Check network access
146
+ involves_network = binary_name in cls.NETWORK_BINARIES or involves_package_install
147
+ if any(tool in cmd_clean.lower() for tool in ("http://", "https://", "ftp://")):
148
+ involves_network = True
149
+
150
+ # Check destructive operations
151
+ involves_destruction = False
152
+ if binary_name in cls.DESTRUCTIVE_COMMANDS:
153
+ involves_destruction = True
154
+ if re.search(r'\b(?:rmdir|del)\s+/[sS]', cmd_clean, re.IGNORECASE):
155
+ involves_destruction = True
156
+ if re.search(r'\brm\s+-[a-zA-Z]*[rf]', cmd_clean, re.IGNORECASE):
157
+ involves_destruction = True
158
+ if re.search(r'\bgit\s+(?:reset\s+--hard|clean\s+-[a-zA-Z]*f)', cmd_clean, re.IGNORECASE):
159
+ involves_destruction = True
160
+
161
+ # Determine risk level
162
+ if involves_destruction:
163
+ level = CommandRiskLevel.DESTRUCTIVE
164
+ reason = "Destructive filesystem or repository mutation detected."
165
+ elif involves_package_install:
166
+ level = CommandRiskLevel.NETWORK_OR_PACKAGE
167
+ reason = "Automated package installation is blocked to prevent network costs and supply chain risks."
168
+ elif involves_network:
169
+ level = CommandRiskLevel.NETWORK_OR_PACKAGE
170
+ reason = "Network access is blocked to guarantee zero-cost and prevent data exfiltration."
171
+ elif is_chained or has_redirection or has_substitution:
172
+ level = CommandRiskLevel.BLOCKED_OR_SUSPICIOUS
173
+ reason = "Shell chaining, redirection, or command substitution detected."
174
+ elif any(cmd_clean.startswith(safe) for safe in cls.SAFE_READ_COMMANDS):
175
+ level = CommandRiskLevel.SAFE_READ_ONLY
176
+ reason = "Standard read-only diagnostic command."
177
+ else:
178
+ level = CommandRiskLevel.WORKSPACE_MUTATION
179
+ reason = "Standard local command."
180
+
181
+ return CommandEvaluation(
182
+ command=cmd_clean,
183
+ risk_level=level,
184
+ allowed=(level == CommandRiskLevel.SAFE_READ_ONLY),
185
+ reason=reason,
186
+ argv=argv,
187
+ is_chained=is_chained,
188
+ has_redirection=has_redirection,
189
+ has_substitution=has_substitution,
190
+ involves_network=involves_network,
191
+ involves_package_install=involves_package_install,
192
+ involves_destruction=involves_destruction
193
+ )
194
+
195
+
196
+ @dataclass
197
+ class CommandExecutionPolicy:
198
+ """Operator-controlled permission policy separated from agent inputs."""
199
+
200
+ allow_agent_shell: bool = False
201
+ allow_network: bool = False
202
+ allow_package_install: bool = False
203
+ allow_destructive: bool = False
204
+ allow_chaining: bool = False
205
+ prefer_argv: bool = True
206
+ dry_run: bool = False
207
+
208
+ @classmethod
209
+ def from_environment(cls) -> "CommandExecutionPolicy":
210
+ """Read permissions strictly from server operator environment variables."""
211
+ return cls(
212
+ allow_agent_shell=(os.environ.get("TZERO_ALLOW_AGENT_SHELL") == "1"),
213
+ allow_network=(os.environ.get("TZERO_ALLOW_NETWORK") == "1"),
214
+ allow_package_install=(os.environ.get("TZERO_ALLOW_PACKAGE_INSTALL") == "1"),
215
+ allow_destructive=(os.environ.get("TZERO_ALLOW_DESTRUCTIVE") == "1"),
216
+ allow_chaining=(os.environ.get("TZERO_ALLOW_CHAINED_COMMANDS") == "1"),
217
+ prefer_argv=True,
218
+ dry_run=(os.environ.get("TZERO_DRY_RUN") == "1")
219
+ )
220
+
221
+ def is_command_allowed(self, evaluation: CommandEvaluation) -> Tuple[bool, str]:
222
+ """Check whether the evaluated command is permitted under the active policy."""
223
+ if not self.allow_agent_shell:
224
+ return False, "Agent shell execution is disabled by default. Server operator must set TZERO_ALLOW_AGENT_SHELL=1."
225
+
226
+ if evaluation.involves_package_install and not self.allow_package_install:
227
+ return False, "Package installation blocked: zero-spend policy forbids unverified package installs."
228
+
229
+ if evaluation.involves_network and not self.allow_network:
230
+ return False, "Network access blocked: zero-spend & privacy policy forbids external network calls."
231
+
232
+ if evaluation.involves_destruction and not self.allow_destructive:
233
+ return False, "Destructive command blocked by safety policy."
234
+
235
+ if (evaluation.is_chained or evaluation.has_redirection or evaluation.has_substitution) and not self.allow_chaining:
236
+ return False, "Shell chaining, redirection, or command substitution blocked by safety policy."
237
+
238
+ return True, "Command permitted under current operator policy."
239
+
240
+
241
+ # ==============================================================================
242
+ # 2. PATH & FILESYSTEM BOUNDARY GUARD
243
+ # ==============================================================================
244
+
245
+ class PathGuard:
246
+ """Guards against directory traversal, symlink escape, and protected file mutation."""
247
+
248
+ PROTECTED_FILENAMES: Set[str] = {
249
+ ".env", ".env.local", ".env.production", ".env.staging", ".env.development",
250
+ "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "authorized_keys",
251
+ ".npmrc", ".pypirc", "credentials", "secrets.json"
252
+ }
253
+
254
+ PROTECTED_DIRS: Set[str] = {
255
+ ".git", ".ssh", ".aws", ".kube", ".gnupg"
256
+ }
257
+
258
+ PROTECTED_EXTENSIONS: Set[str] = {
259
+ ".pem", ".key", ".pfx", ".p12", ".kdbx", ".cert"
260
+ }
261
+
262
+ MAX_SAFE_FILE_SIZE_BYTES: int = 5 * 1024 * 1024 # 5 MB
263
+ MAX_LINES_CHANGED_LIMIT: int = 500
264
+
265
+ @classmethod
266
+ def validate_target_path(
267
+ cls,
268
+ file_path: Union[str, Path],
269
+ work_dir: Union[str, Path],
270
+ for_write: bool = True
271
+ ) -> Tuple[bool, str, Optional[Path]]:
272
+ """Validate target file path against workspace boundaries, symlinks, and protected paths."""
273
+ try:
274
+ root = Path(work_dir).resolve(strict=True)
275
+ except (OSError, RuntimeError) as exc:
276
+ return False, f"Invalid workspace root: {exc}", None
277
+
278
+ path = Path(file_path)
279
+ if not path.is_absolute():
280
+ path = root / path
281
+
282
+ # Check raw string for traversal attempts
283
+ parts_str = [str(p) for p in path.parts]
284
+ if ".." in parts_str:
285
+ return False, "Path traversal ('..') detected.", None
286
+
287
+ # Check symlinks on target and parents
288
+ try:
289
+ test_path = path
290
+ while test_path != test_path.parent:
291
+ if test_path.is_symlink():
292
+ return False, f"Symlink path forbidden: {test_path}", None
293
+ test_path = test_path.parent
294
+ except (OSError, RuntimeError):
295
+ pass
296
+
297
+ try:
298
+ resolved = path.resolve(strict=for_write)
299
+ except FileNotFoundError:
300
+ if for_write:
301
+ return False, f"Target file does not exist: {path}", None
302
+ resolved = path.resolve()
303
+ except (OSError, RuntimeError) as exc:
304
+ return False, f"Path resolution error: {exc}", None
305
+
306
+ # Boundary check: resolved must be strictly relative to root
307
+ try:
308
+ relative = resolved.relative_to(root)
309
+ except ValueError:
310
+ return False, f"Path escapes workspace boundary: {resolved} is outside {root}", None
311
+
312
+ # Check every component of relative path for symlinks or protected directories
313
+ current = root
314
+ for part in relative.parts:
315
+ if part in cls.PROTECTED_DIRS:
316
+ return False, f"Access to protected directory '{part}' is forbidden.", None
317
+ current = current / part
318
+ if current.is_symlink():
319
+ return False, f"Symlink component forbidden: {current}", None
320
+
321
+ # Check protected filenames and extensions
322
+ filename_lower = resolved.name.lower()
323
+ if filename_lower in cls.PROTECTED_FILENAMES:
324
+ return False, f"Mutation of protected configuration file '{resolved.name}' is forbidden.", None
325
+
326
+ if resolved.suffix.lower() in cls.PROTECTED_EXTENSIONS:
327
+ return False, f"Mutation of protected key/certificate extension '{resolved.suffix}' is forbidden.", None
328
+
329
+ # Check file size if modifying existing file
330
+ if for_write and resolved.is_file():
331
+ try:
332
+ size = resolved.stat().st_size
333
+ if size > cls.MAX_SAFE_FILE_SIZE_BYTES:
334
+ return False, f"File size ({size} bytes) exceeds maximum safe repair threshold ({cls.MAX_SAFE_FILE_SIZE_BYTES} bytes).", None
335
+ except OSError as exc:
336
+ return False, f"Cannot stat file: {exc}", None
337
+
338
+ return True, "Path validated successfully.", resolved
339
+
340
+
341
+ # ==============================================================================
342
+ # 3. SECRET & TOKEN REDACTION SHIELD
343
+ # ==============================================================================
344
+
345
+ class SecretRedactor:
346
+ """Masks API keys, tokens, high-entropy strings, and credentials from diagnostics."""
347
+
348
+ REDACTION_TAG = "[REDACTED_SECRET]"
349
+
350
+ PATTERNS: List[Tuple[str, re.Pattern]] = [
351
+ ("AWS_KEY", re.compile(r'\b(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}\b')),
352
+ ("GITHUB_TOKEN", re.compile(r'\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,255}\b')),
353
+ ("GITHUB_PAT", re.compile(r'\bgithub_pat_[A-Za-z0-9_]{82}\b')),
354
+ ("BEARER_TOKEN", re.compile(r'(?i)\bBearer\s+[A-Za-z0-9\-._~+/]+=*')),
355
+ ("PRIVATE_KEY", re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----')),
356
+ ("OPENAI_KEY", re.compile(r'\bsk-(?:proj-)?[A-Za-z0-9_\-]{32,}\b')),
357
+ ("GENERIC_SECRET_ASSIGNMENT", re.compile(r'(?i)(?:api_key|secret|password|token|auth_token)\s*[:=]\s*["\']([^"\']{16,})["\']')),
358
+ ]
359
+
360
+ @classmethod
361
+ def calculate_shannon_entropy(cls, s: str) -> float:
362
+ """Calculate Shannon entropy in bits per character."""
363
+ if not s:
364
+ return 0.0
365
+ length = len(s)
366
+ counts: Dict[str, int] = {}
367
+ for c in s:
368
+ counts[c] = counts.get(c, 0) + 1
369
+ return -sum((cnt / length) * math.log2(cnt / length) for cnt in counts.values())
370
+
371
+ @classmethod
372
+ def sanitize(cls, text: str) -> str:
373
+ """Redact sensitive patterns and suspicious high-entropy tokens from text."""
374
+ if not text:
375
+ return text
376
+
377
+ result = text
378
+ # 1. Pattern-based redactions
379
+ for name, pattern in cls.PATTERNS:
380
+ if name == "GENERIC_SECRET_ASSIGNMENT":
381
+ def replace_generic(match: re.Match) -> str:
382
+ full = match.group(0)
383
+ val = match.group(1)
384
+ return full.replace(val, cls.REDACTION_TAG)
385
+ result = pattern.sub(replace_generic, result)
386
+ else:
387
+ result = pattern.sub(cls.REDACTION_TAG, result)
388
+
389
+ # 2. Entropy-based token masking for unquoted suspicious strings (length >= 32, entropy >= 4.75)
390
+ words = result.split()
391
+ for w in words:
392
+ clean_w = w.strip('"\',;:()[]{}')
393
+ if len(clean_w) >= 32 and not any(p in clean_w for p in ("http:", "https:", "/", "\\", ".")):
394
+ # Must have diverse character sets
395
+ has_digit = any(c.isdigit() for c in clean_w)
396
+ has_upper = any(c.isupper() for c in clean_w)
397
+ has_lower = any(c.islower() for c in clean_w)
398
+ if sum([has_digit, has_upper, has_lower]) >= 2:
399
+ if cls.calculate_shannon_entropy(clean_w) >= 4.75:
400
+ result = result.replace(clean_w, cls.REDACTION_TAG)
401
+
402
+ return result
403
+
404
+
405
+ # ==============================================================================
406
+ # 4. AI GROUNDING & ANTI-HALLUCINATION VERIFIER
407
+ # ==============================================================================
408
+
409
+ class AIGroundingVerifier:
410
+ """Verifies that files, symbols, and line numbers claimed by AI exist in the workspace."""
411
+
412
+ @classmethod
413
+ def verify_file(cls, work_dir: Union[str, Path], file_path: str) -> Tuple[bool, str, Optional[Path]]:
414
+ """Verify that a referenced file exists within the workspace."""
415
+ valid, reason, resolved = PathGuard.validate_target_path(file_path, work_dir, for_write=False)
416
+ if not valid or not resolved or not resolved.is_file():
417
+ return False, f"File not found in workspace: {file_path}", None
418
+ return True, "File exists.", resolved
419
+
420
+ @classmethod
421
+ def verify_line(cls, work_dir: Union[str, Path], file_path: str, line_no: int) -> Tuple[bool, str]:
422
+ """Verify that a referenced line number is within file boundaries."""
423
+ exists, msg, resolved = cls.verify_file(work_dir, file_path)
424
+ if not exists or not resolved:
425
+ return False, msg
426
+ try:
427
+ line_count = len(resolved.read_text(encoding="utf-8", errors="replace").splitlines())
428
+ if 1 <= line_no <= line_count:
429
+ return True, f"Line {line_no} verified (total lines: {line_count})."
430
+ return False, f"Line number {line_no} out of bounds (file has {line_count} lines)."
431
+ except OSError as exc:
432
+ return False, f"Cannot read file lines: {exc}"
433
+
434
+ @classmethod
435
+ def verify_python_symbol(
436
+ cls,
437
+ work_dir: Union[str, Path],
438
+ file_path: str,
439
+ symbol_name: str
440
+ ) -> Tuple[bool, str, Optional[str], Optional[int]]:
441
+ """Verify that a function, class, or method symbol exists in a Python file's AST."""
442
+ exists, msg, resolved = cls.verify_file(work_dir, file_path)
443
+ if not exists or not resolved:
444
+ return False, msg, None, None
445
+
446
+ if resolved.suffix != ".py":
447
+ return False, "Symbol AST verification is only supported for Python files.", None, None
448
+
449
+ try:
450
+ source = resolved.read_text(encoding="utf-8", errors="replace")
451
+ tree = ast.parse(source, filename=str(resolved))
452
+ except (SyntaxError, OSError) as exc:
453
+ return False, f"AST parse failed on {resolved.name}: {exc}", None, None
454
+
455
+ for node in ast.walk(tree):
456
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == symbol_name:
457
+ return True, f"Found function '{symbol_name}' at line {node.lineno}.", "function", node.lineno
458
+ if isinstance(node, ast.ClassDef) and node.name == symbol_name:
459
+ return True, f"Found class '{symbol_name}' at line {node.lineno}.", "class", node.lineno
460
+
461
+ return False, f"Symbol '{symbol_name}' not found in AST of {resolved.name}.", None, None
462
+
463
+ @classmethod
464
+ def audit_traceback_evidence(
465
+ cls,
466
+ work_dir: Union[str, Path],
467
+ traceback_text: str
468
+ ) -> Dict[str, Any]:
469
+ """Extract all File and line claims from traceback and verify their workspace ground truth."""
470
+ matches = re.findall(r'File "([^"\n]+)", line (\d+)', traceback_text or "")
471
+ verified_frames = []
472
+ unverified_frames = []
473
+
474
+ for fpath, lstr in matches:
475
+ lno = int(lstr)
476
+ is_valid, msg, resolved = cls.verify_file(work_dir, fpath)
477
+ if is_valid and resolved:
478
+ line_ok, lmsg = cls.verify_line(work_dir, fpath, lno)
479
+ frame_info = {"file": str(resolved), "line": lno, "status": "VERIFIED" if line_ok else "LINE_OUT_OF_BOUNDS", "detail": lmsg}
480
+ if line_ok:
481
+ verified_frames.append(frame_info)
482
+ else:
483
+ unverified_frames.append(frame_info)
484
+ else:
485
+ unverified_frames.append({"file": fpath, "line": lno, "status": "UNVERIFIED_FILE", "detail": msg})
486
+
487
+ return {
488
+ "total_frames": len(matches),
489
+ "verified_frames": verified_frames,
490
+ "unverified_frames": unverified_frames,
491
+ "has_grounded_target": len(verified_frames) > 0,
492
+ "primary_target": verified_frames[-1] if verified_frames else None
493
+ }
494
+
495
+ @classmethod
496
+ def flag_unverified_claims(cls, text: str) -> List[str]:
497
+ """Detect and flag absolute or ungrounded claims in text."""
498
+ flags = []
499
+ unsubstantiated_patterns = [
500
+ (r'\b100%\s*(?:guaranteed|leak-proof|safe|accuracy)\b', "Claim of '100% security/accuracy' cannot be verified mathematically."),
501
+ (r'\bzero\s*(?:bug|error|defect|vulnerability)\s*guarantee\b', "Claim of 'zero bug/defect guarantee' is invalid for software systems."),
502
+ (r'\bcompletely\s+eliminates\s+all\s+hallucinations\b', "Claim of 'completely eliminating all hallucinations' is unsupported without bounded AST proof.")
503
+ ]
504
+ for pattern, explanation in unsubstantiated_patterns:
505
+ if re.search(pattern, text, re.IGNORECASE):
506
+ flags.append(explanation)
507
+ return flags
508
+
509
+
510
+ # ==============================================================================
511
+ # 5. MULTI-FILE TRANSACTION & ROLLBACK STACK
512
+ # ==============================================================================
513
+
514
+ @dataclass
515
+ class TransactionEntry:
516
+ path: Path
517
+ original_bytes: bytes
518
+ applied_bytes: bytes
519
+ diff: str
520
+ timestamp: float = field(default_factory=time.time)
521
+
522
+
523
+ class MultiFileRollbackStack:
524
+ """Manages transactional file modifications with safe reverse-order rollback."""
525
+
526
+ def __init__(self):
527
+ self._stack: List[TransactionEntry] = []
528
+
529
+ def push(self, path: Path, original: bytes, applied: bytes, diff: str) -> None:
530
+ self._stack.append(TransactionEntry(path, original, applied, diff))
531
+
532
+ def rollback_all(self) -> List[str]:
533
+ """Roll back all modified files in reverse order if they haven't been concurrently modified."""
534
+ diagnostics = []
535
+ while self._stack:
536
+ entry = self._stack.pop()
537
+ try:
538
+ if not entry.path.is_file():
539
+ diagnostics.append(f"Rollback warning: {entry.path.name} no longer exists.")
540
+ continue
541
+ current_bytes = entry.path.read_bytes()
542
+ if current_bytes == entry.applied_bytes:
543
+ entry.path.write_bytes(entry.original_bytes)
544
+ diagnostics.append(f"Restored {entry.path.name} to original state.")
545
+ else:
546
+ diagnostics.append(f"Rollback skipped for {entry.path.name}: file modified concurrently.")
547
+ except OSError as exc:
548
+ diagnostics.append(f"Rollback error for {entry.path.name}: {exc}")
549
+ return diagnostics
550
+
551
+ def clear(self) -> None:
552
+ self._stack.clear()
553
+
554
+ def __len__(self) -> int:
555
+ return len(self._stack)
556
+
557
+
558
+ # ==============================================================================
559
+ # 6. IN-MEMORY AUDIT LOGGING
560
+ # ==============================================================================
561
+
562
+ @dataclass(frozen=True)
563
+ class SecurityAuditEvent:
564
+ timestamp: float
565
+ event_type: str
566
+ target: str
567
+ verdict: str
568
+ reason: str
569
+ metadata: Dict[str, Any] = field(default_factory=dict)
570
+
571
+ def to_dict(self) -> Dict[str, Any]:
572
+ return {
573
+ "timestamp": self.timestamp,
574
+ "event_type": self.event_type,
575
+ "target": self.target,
576
+ "verdict": self.verdict,
577
+ "reason": self.reason,
578
+ "metadata": self.metadata
579
+ }
580
+
581
+
582
+ class SecurityAuditLogger:
583
+ """Thread-safe, bounded, in-memory security audit log with secret sanitization."""
584
+
585
+ def __init__(self, capacity: int = 500):
586
+ self._capacity = capacity
587
+ self._events: List[SecurityAuditEvent] = []
588
+
589
+ def record(self, event_type: str, target: str, verdict: str, reason: str, metadata: Optional[Dict[str, Any]] = None) -> SecurityAuditEvent:
590
+ clean_target = SecretRedactor.sanitize(target)
591
+ clean_reason = SecretRedactor.sanitize(reason)
592
+ clean_meta = {}
593
+ if metadata:
594
+ for k, v in metadata.items():
595
+ clean_meta[k] = SecretRedactor.sanitize(str(v)) if isinstance(v, str) else v
596
+
597
+ event = SecurityAuditEvent(
598
+ timestamp=round(time.time(), 3),
599
+ event_type=event_type,
600
+ target=clean_target,
601
+ verdict=verdict,
602
+ reason=clean_reason,
603
+ metadata=clean_meta
604
+ )
605
+ self._events.append(event)
606
+ if len(self._events) > self._capacity:
607
+ self._events.pop(0)
608
+ return event
609
+
610
+ def get_events(self, event_type: Optional[str] = None) -> List[Dict[str, Any]]:
611
+ if event_type:
612
+ return [e.to_dict() for e in self._events if e.event_type == event_type]
613
+ return [e.to_dict() for e in self._events]
614
+
615
+ def clear(self) -> None:
616
+ self._events.clear()
617
+
618
+
619
+ # Global audit logger instance
620
+ GLOBAL_AUDIT_LOGGER = SecurityAuditLogger()
@@ -3,7 +3,7 @@
3
3
  T-ZERO JARVIS MULTI-MODAL CREATIVE DIRECTOR & PROMPT ENGINE
4
4
  ------------------------------------------------------------
5
5
  Developer: Toprak Ahmet Aydoğmuş (Siber Akademi)
6
- Version: 5.1.0 | License: MIT
6
+ Version: 5.1.0 | License: AGPL-3.0-only
7
7
 
8
8
  Autonomous creative director that synthesizes ultra-photorealistic image prompts
9
9
  (Midjourney v6.1, Flux.1 Pro, Imagen 3) and cinematic video generation prompts