tzero-mcp 12.2.1 → 12.2.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 (43) hide show
  1. package/package.json +1 -1
  2. package/src/addmcp.py +10 -5
  3. package/src/app.py +3 -9
  4. package/src/tzero/__init__.py +1 -1
  5. package/src/tzero/anti_rea/asar_shield.py +3 -1
  6. package/src/tzero/anti_rea/auditor.py +42 -12
  7. package/src/tzero/anti_rea/canary_beacon.py +27 -19
  8. package/src/tzero/anti_rea/cli.py +7 -1
  9. package/src/tzero/anti_rea/confusables.py +62 -18
  10. package/src/tzero/anti_rea/engine.py +79 -10
  11. package/src/tzero/anti_rea/extractor_shield.py +52 -9
  12. package/src/tzero/anti_rea/gui.py +1 -4
  13. package/src/tzero/anti_rea/integrity_guard.py +17 -5
  14. package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
  15. package/src/tzero/anti_rea/string_vault.py +10 -7
  16. package/src/tzero/siber_akademi.ico +0 -0
  17. package/src/tzero/siber_akademi_icon.py +14 -8
  18. package/src/tzero/tzero_armor.py +27 -5
  19. package/src/tzero/tzero_benchmark.py +4 -2
  20. package/src/tzero/tzero_budget.py +14 -5
  21. package/src/tzero/tzero_ci.py +1 -1
  22. package/src/tzero/tzero_contracts.py +7 -5
  23. package/src/tzero/tzero_dashboard.py +28 -9
  24. package/src/tzero/tzero_debt.py +19 -4
  25. package/src/tzero/tzero_explain.py +1 -1
  26. package/src/tzero/tzero_features.py +43 -29
  27. package/src/tzero/tzero_federation.py +9 -2
  28. package/src/tzero/tzero_fixer/mcp_server.py +10 -0
  29. package/src/tzero/tzero_golden.py +37 -9
  30. package/src/tzero/tzero_growth.py +166 -8
  31. package/src/tzero/tzero_guard.py +147 -46
  32. package/src/tzero/tzero_lsp.py +1 -1
  33. package/src/tzero/tzero_mcp.py +64 -16
  34. package/src/tzero/tzero_mutation.py +88 -15
  35. package/src/tzero/tzero_promo.py +1 -1
  36. package/src/tzero/tzero_proxy.py +105 -12
  37. package/src/tzero/tzero_scip.py +12 -6
  38. package/src/tzero/tzero_security.py +375 -60
  39. package/src/tzero/tzero_task_benchmark.py +2 -2
  40. package/src/tzero/tzero_traffic.py +35 -10
  41. package/src/tzero/tzero_tui.py +17 -8
  42. package/src/tzero/tzero_v3.py +268 -88
  43. package/src/tzero/tzero_welcome.py +12 -4
@@ -208,8 +208,8 @@ SECRET_RULES: List[SecretRule] = [
208
208
  SecretRule(
209
209
  rule_id="SEC-CRYPTO-001",
210
210
  provider="PKI",
211
- description="Private Key Header (RSA, EC, OPENSSH, DSA, PGP)",
212
- pattern=re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----"),
211
+ description="Private Key Block or Header (RSA, EC, OPENSSH, DSA, PGP)",
212
+ pattern=re.compile(r"-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----|-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----"),
213
213
  mask_tag="[ZERO_LEAK_MASKED_PRIVATE_KEY]"
214
214
  ),
215
215
  SecretRule(
@@ -265,6 +265,10 @@ class ZeroLeakEngine:
265
265
 
266
266
  MIN_ENTROPY_THRESHOLD: float = 4.75
267
267
  MIN_ENTROPY_LENGTH: int = 28
268
+ _PEM_BEGIN_RE = re.compile(r"-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----")
269
+ _PEM_COMPLETE_BLOCK_RE = re.compile(
270
+ r"-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----"
271
+ )
268
272
 
269
273
  @classmethod
270
274
  def is_placeholder(cls, s: str) -> bool:
@@ -291,28 +295,70 @@ class ZeroLeakEngine:
291
295
 
292
296
  @classmethod
293
297
  def scan_text(cls, text: str, check_entropy: bool = True) -> List[SecretFinding]:
294
- """Scans in-memory text for known secrets and high-entropy secret anomalies."""
298
+ """Scans in-memory text (including comments and multiline PEM blocks) for secrets."""
295
299
  if not text:
296
300
  return []
297
301
 
298
302
  findings: List[SecretFinding] = []
299
303
  lines = text.splitlines()
300
304
 
305
+ # Pre-compute line numbers covered by complete multi-line PEM blocks
306
+ pem_ranges: List[Tuple[int, int]] = []
307
+ for pm in cls._PEM_COMPLETE_BLOCK_RE.finditer(text):
308
+ start_line = text[: pm.start()].count("\n") + 1
309
+ end_line = text[: pm.end()].count("\n") + 1
310
+ pem_ranges.append((start_line, end_line))
311
+ findings.append(SecretFinding(
312
+ rule_id="SEC-CRYPTO-001",
313
+ provider="PKI",
314
+ description="Private Key Block (PEM)",
315
+ severity="CRITICAL",
316
+ line_no=start_line,
317
+ preview="[ZERO_LEAK_MASKED_PRIVATE_KEY]",
318
+ entropy=round(calculate_shannon_entropy(pm.group(0)), 2),
319
+ is_entropy_anomaly=False,
320
+ secret_value=pm.group(0),
321
+ ))
322
+
323
+ def _in_pem_block(ln: int) -> bool:
324
+ return any(s <= ln <= e for s, e in pem_ranges)
325
+
301
326
  for lineno, line in enumerate(lines, 1):
302
327
  stripped = line.strip()
303
- if not stripped or stripped.startswith(("#", "//", "*", "/*")):
328
+ if not stripped or _in_pem_block(lineno):
304
329
  continue
305
330
 
306
- # 1. Signature Rule Matching
331
+ # 1. Signature Rule Matching (scans code AND comment lines alike)
307
332
  has_specific_provider_match = False
308
333
  for rule in SECRET_RULES:
334
+ if rule.rule_id == "SEC-CRYPTO-001":
335
+ if cls._PEM_BEGIN_RE.search(line):
336
+ val = cls._PEM_BEGIN_RE.search(line).group(0)
337
+ findings.append(SecretFinding(
338
+ rule_id=rule.rule_id,
339
+ provider=rule.provider,
340
+ description=rule.description,
341
+ severity=rule.severity,
342
+ line_no=lineno,
343
+ preview=cls.mask_preview(line),
344
+ entropy=round(calculate_shannon_entropy(val), 2),
345
+ is_entropy_anomaly=False,
346
+ secret_value=val,
347
+ ))
348
+ has_specific_provider_match = True
349
+ continue
350
+
309
351
  # If a specific provider rule matched, avoid duplicate generic rule hit on same line
310
352
  if rule.rule_id == "SEC-GENERIC-001" and has_specific_provider_match:
311
353
  continue
312
354
 
313
355
  for match in rule.pattern.finditer(line):
314
- val = match.group(0)
315
- if cls.is_placeholder(val):
356
+ # Preserve capture group 1 for generic/Bearer assignment rules so LHS variable stays intact
357
+ if rule.rule_id in ("SEC-GENERIC-001", "SEC-AUTH-002") and match.lastindex and match.lastindex >= 1:
358
+ val = match.group(1)
359
+ else:
360
+ val = match.group(0)
361
+ if cls.is_placeholder(val) or cls.is_placeholder(match.group(0)):
316
362
  continue
317
363
 
318
364
  ent = calculate_shannon_entropy(val)
@@ -325,13 +371,13 @@ class ZeroLeakEngine:
325
371
  preview=cls.mask_preview(line),
326
372
  entropy=round(ent, 2),
327
373
  is_entropy_anomaly=False,
328
- secret_value=val
374
+ secret_value=val,
329
375
  ))
330
376
  if rule.provider != "Generic":
331
377
  has_specific_provider_match = True
332
378
 
333
379
  # 2. Shannon Entropy Scanner for Unmatched Candidate Tokens
334
- if check_entropy:
380
+ if check_entropy and not stripped.startswith(("#", "//", "*", "/*")):
335
381
  # Candidate secrets must be single compact tokens without whitespace, slashes, or URL schemas
336
382
  candidate_tokens = re.findall(r"""['"]([A-Za-z0-9+/=_\-]{28,})['"]""", line)
337
383
  for tok in candidate_tokens:
@@ -347,7 +393,7 @@ class ZeroLeakEngine:
347
393
  continue
348
394
  if cls.is_natural_or_identifier(tok):
349
395
  continue
350
-
396
+
351
397
  ent = calculate_shannon_entropy(tok)
352
398
  if ent >= cls.MIN_ENTROPY_THRESHOLD and len(tok) >= cls.MIN_ENTROPY_LENGTH:
353
399
  already_reported = any(f.line_no == lineno for f in findings)
@@ -361,7 +407,7 @@ class ZeroLeakEngine:
361
407
  preview=cls.mask_preview(line),
362
408
  entropy=round(ent, 2),
363
409
  is_entropy_anomaly=True,
364
- secret_value=tok
410
+ secret_value=tok,
365
411
  ))
366
412
 
367
413
  return findings
@@ -369,21 +415,31 @@ class ZeroLeakEngine:
369
415
  @classmethod
370
416
  def mask_preview(cls, line: str, max_len: int = 70) -> str:
371
417
  """Sanitizes line for safe terminal output and logging."""
372
- sanitized = cls.sanitize_text(line)
418
+ sanitized = cls.sanitize_text(line, allow_incomplete_pem=True)
373
419
  if len(sanitized) > max_len:
374
420
  return sanitized[:max_len] + "..."
375
421
  return sanitized
376
422
 
377
423
  @classmethod
378
- def sanitize_text(cls, text: str) -> str:
424
+ def sanitize_text(cls, text: str, allow_incomplete_pem: bool = False) -> str:
379
425
  """Sanitizes text by masking all detected secrets with Zero-Leak tokens."""
380
426
  if not text:
381
427
  return ""
382
428
 
383
- sanitized = text
429
+ sanitized = cls._PEM_COMPLETE_BLOCK_RE.sub("[ZERO_LEAK_MASKED_PRIVATE_KEY]", text)
430
+
431
+ if cls._PEM_BEGIN_RE.search(sanitized):
432
+ if not allow_incomplete_pem:
433
+ raise ValueError(
434
+ "Incomplete PEM private key block detected without END delimiter; aborting redaction to prevent body leak."
435
+ )
436
+ sanitized = cls._PEM_BEGIN_RE.sub("[ZERO_LEAK_MASKED_PRIVATE_KEY]", sanitized)
384
437
 
385
438
  # 1. Mask specific patterns
386
439
  for rule in SECRET_RULES:
440
+ if rule.rule_id == "SEC-CRYPTO-001":
441
+ continue
442
+
387
443
  def _replace_match(m):
388
444
  full_val = m.group(0)
389
445
  if cls.is_placeholder(full_val):
@@ -401,15 +457,41 @@ class ZeroLeakEngine:
401
457
  sanitized = re.sub(r"""['"]([^'"]{20,})['"]""", _replace_entropy, sanitized)
402
458
  return sanitized
403
459
 
460
+ @classmethod
461
+ def _sanitize_string_value(cls, val: str, allow_incomplete_pem: bool = False) -> str:
462
+ """Sanitize an extracted string value even when unquoted inside an AST literal."""
463
+ cleaned = cls.sanitize_text(val, allow_incomplete_pem=allow_incomplete_pem)
464
+ if cleaned != val:
465
+ return cleaned
466
+ # Strip unquoted high-entropy raw tokens inside AST constants if scan_text flags them
467
+ stripped = val.strip()
468
+ if cls.scan_text(f'val = "{stripped}"'):
469
+ if len(stripped) >= cls.MIN_ENTROPY_LENGTH and calculate_shannon_entropy(stripped) >= 4.4 and not cls.is_placeholder(stripped):
470
+ return f"{stripped[:4]}...[ZERO_LEAK_HIGH_ENTROPY_SECRET]"
471
+ if len(stripped) >= 12 and not cls.is_placeholder(stripped):
472
+ return "[ZERO_LEAK_MASKED_VALUE]"
473
+ return cleaned
474
+
404
475
  @classmethod
405
476
  def sanitize_ast(cls, tree: ast.AST) -> ast.AST:
406
477
  """Walks an AST tree and replaces hardcoded string literals containing secrets."""
407
478
  for node in ast.walk(tree):
408
479
  if isinstance(node, ast.Constant) and isinstance(node.value, str):
409
- val = node.value
410
- # Check if raw value itself or wrapped in quotes triggers detection
411
- if cls.scan_text(f'val = "{val}"'):
412
- node.value = cls.sanitize_text(val)
480
+ node.value = cls._sanitize_string_value(node.value)
481
+ ast.fix_missing_locations(tree)
482
+ # Re-verify unparsed code so no AST literal secret survives
483
+ try:
484
+ rendered = ast.unparse(tree)
485
+ remaining = cls.scan_text(rendered)
486
+ if remaining:
487
+ secret_vals = {f.secret_value for f in remaining if f.secret_value}
488
+ for node in ast.walk(tree):
489
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
490
+ for sv in secret_vals:
491
+ if sv and sv in node.value:
492
+ node.value = node.value.replace(sv, "[ZERO_LEAK_MASKED_VALUE]")
493
+ except Exception:
494
+ pass
413
495
  return tree
414
496
 
415
497
  @classmethod
@@ -461,26 +543,97 @@ class ZeroLeakEngine:
461
543
  pass
462
544
  return cls.scan_files_map(files_map)
463
545
 
546
+ @classmethod
547
+ def resolve_project_root(cls, target_path: str) -> str:
548
+ """Resolve nearest project root (.git ancestor) or target directory consistently."""
549
+ abs_p = os.path.abspath(target_path)
550
+ start = abs_p if os.path.isdir(abs_p) else os.path.dirname(abs_p)
551
+ curr = start
552
+ while True:
553
+ if os.path.isdir(os.path.join(curr, ".git")):
554
+ return curr
555
+ parent = os.path.dirname(curr)
556
+ if parent == curr:
557
+ return start
558
+ curr = parent
559
+
560
+ @classmethod
561
+ def check_env_git_status(
562
+ cls, env_file_path: str, gitignore_path: Optional[str] = None
563
+ ) -> Dict[str, Any]:
564
+ """Use Git check-ignore/ls-files when available (fallback to real rule parsing)."""
565
+ import subprocess
566
+ abs_env = os.path.abspath(env_file_path)
567
+ proj_root = cls.resolve_project_root(abs_env)
568
+ env_name = os.path.basename(abs_env)
569
+ in_git = os.path.isdir(os.path.join(proj_root, ".git"))
570
+ tracked = False
571
+ ignored = False
572
+
573
+ if in_git:
574
+ rel_env = os.path.relpath(abs_env, proj_root).replace("\\", "/")
575
+ tr = subprocess.run(
576
+ ["git", "-C", proj_root, "ls-files", "--error-unmatch", rel_env],
577
+ capture_output=True, text=True, check=False,
578
+ )
579
+ tracked = tr.returncode == 0
580
+ ig = subprocess.run(
581
+ ["git", "-C", proj_root, "check-ignore", "-q", abs_env],
582
+ capture_output=True, text=True, check=False,
583
+ )
584
+ ignored = ig.returncode == 0
585
+ elif gitignore_path and os.path.isfile(gitignore_path):
586
+ with open(gitignore_path, "r", encoding="utf-8", errors="ignore") as gf:
587
+ for raw_line in gf:
588
+ rule = raw_line.strip()
589
+ if not rule or rule.startswith("#") or rule.startswith("!"):
590
+ continue
591
+ norm = rule.lstrip("/")
592
+ if norm in (env_name, "*.env") or (norm == ".env" and env_name == ".env"):
593
+ ignored = True
594
+ break
595
+ return {
596
+ "in_git": in_git,
597
+ "tracked": tracked,
598
+ "ignored": ignored,
599
+ "warning": f"WARNING: {abs_env} is already tracked by Git! Run `git rm --cached {env_name}`." if tracked else "",
600
+ }
601
+
602
+ @classmethod
603
+ def _load_existing_env(cls, env_file_path: Optional[str]) -> Dict[str, str]:
604
+ env_map: Dict[str, str] = {}
605
+ if env_file_path and os.path.isfile(env_file_path):
606
+ with open(env_file_path, "r", encoding="utf-8", errors="replace") as ef:
607
+ for raw in ef:
608
+ line = raw.strip()
609
+ if not line or line.startswith("#") or "=" not in line:
610
+ continue
611
+ k, _, v = line.partition("=")
612
+ k = k.strip()
613
+ if k:
614
+ env_map[k] = v.strip()
615
+ return env_map
616
+
464
617
  @classmethod
465
618
  def auto_migrate_to_env(
466
619
  cls,
467
620
  code_str: str,
468
621
  env_file_path: Optional[str] = None,
469
- gitignore_path: Optional[str] = None
622
+ gitignore_path: Optional[str] = None,
623
+ shared_env_registry: Optional[Dict[str, str]] = None,
624
+ dry_run: bool = False,
470
625
  ) -> Tuple[str, str, int, str]:
471
- """Automatically extracts detected hardcoded secrets into .env format and refactors code with os.environ.get."""
626
+ """Extract hardcoded secrets to .env atomically without variable collisions or partial writes."""
472
627
  findings = cls.scan_text(code_str)
473
628
  valid_findings = [f for f in findings if f.secret_value and not cls.is_placeholder(f.secret_value)]
474
-
629
+
475
630
  if not valid_findings:
476
631
  return code_str, "# No secrets detected.", 0, "### 100% Zero-Leak Certified\nNo hardcoded credentials found in source code."
477
632
 
478
633
  migrated_code = code_str
479
- env_entries: Dict[str, str] = {}
480
- used_vars: Set[str] = set()
481
- counter = 1
634
+ env_registry: Dict[str, str] = shared_env_registry if shared_env_registry is not None else cls._load_existing_env(env_file_path)
635
+ new_env_entries: Dict[str, str] = {}
482
636
 
483
- # Sort findings descending by length to avoid partial substrings
484
637
  unique_findings = []
485
638
  seen_vals = set()
486
639
  for f in valid_findings:
@@ -502,6 +655,7 @@ class ZeroLeakEngine:
502
655
  "Slack": "SLACK_BOT_TOKEN",
503
656
  "Database": "DATABASE_URL",
504
657
  "JWT": "JWT_SECRET_TOKEN",
658
+ "PKI": "PRIVATE_KEY_PEM",
505
659
  "PrivateKey": "PRIVATE_KEY_PEM",
506
660
  }
507
661
 
@@ -512,23 +666,30 @@ class ZeroLeakEngine:
512
666
  "| :--- | :--- | :--- |",
513
667
  ]
514
668
 
669
+ # Build reverse map secret_value -> existing env var for idempotent reuse
670
+ val_to_var = {v: k for k, v in env_registry.items()}
671
+
515
672
  for f in unique_findings:
516
- base_var = provider_map.get(f.provider, "")
517
- if not base_var:
518
- clean_desc = re.sub(r"[^A-Z0-9_]", "_", f.description.upper()[:20])
519
- base_var = f"{clean_desc}_TOKEN"
520
-
521
- var_name = base_var
522
- while var_name in used_vars:
523
- var_name = f"{base_var}_{counter}"
524
- counter += 1
525
- used_vars.add(var_name)
526
-
527
- env_entries[var_name] = f.secret_value
673
+ if f.secret_value in val_to_var:
674
+ var_name = val_to_var[f.secret_value]
675
+ else:
676
+ base_var = provider_map.get(f.provider, "")
677
+ if not base_var:
678
+ clean_desc = re.sub(r"[^A-Z0-9_]", "_", f.description.upper()[:20]).strip("_")
679
+ base_var = f"{clean_desc or 'APP'}_SECRET"
680
+
681
+ var_name = base_var
682
+ idx = 2
683
+ while var_name in env_registry:
684
+ var_name = f"{base_var}_{idx}"
685
+ idx += 1
686
+ env_registry[var_name] = f.secret_value
687
+ val_to_var[f.secret_value] = var_name
688
+ new_env_entries[var_name] = f.secret_value
689
+
528
690
  redacted = f.secret_value[:6] + "..." + f.secret_value[-4:] if len(f.secret_value) > 12 else "***"
529
691
  report_lines.append(f"| `{f.provider}` | `{var_name}` | `{redacted}` |")
530
692
 
531
- # Replace quotes in code
532
693
  pat_d = f'"{f.secret_value}"'
533
694
  pat_s = f"'{f.secret_value}'"
534
695
  replacement = f'os.environ.get("{var_name}", "")'
@@ -537,37 +698,191 @@ class ZeroLeakEngine:
537
698
  elif pat_s in migrated_code:
538
699
  migrated_code = migrated_code.replace(pat_s, replacement)
539
700
  else:
540
- migrated_code = migrated_code.replace(f.secret_value, replacement)
701
+ # Preserve surrounding quotes/assignment cleanly if matched inside a quoted value
702
+ escaped_v = re.escape(f.secret_value)
703
+ if re.search(rf"""(['"]){escaped_v}\1""", migrated_code):
704
+ migrated_code = re.sub(rf"""(['"]){escaped_v}\1""", replacement, migrated_code)
705
+ else:
706
+ migrated_code = migrated_code.replace(f.secret_value, replacement)
541
707
 
542
- # Check if os is imported
543
708
  if "os.environ" in migrated_code and "import os" not in migrated_code and "from os import" not in migrated_code:
544
- migrated_code = "import os\n" + migrated_code
709
+ lines_m = migrated_code.splitlines(keepends=True)
710
+ ins_idx = 0
711
+ for idx_l, ln_txt in enumerate(lines_m):
712
+ s_ln = ln_txt.strip()
713
+ if idx_l == 0 and s_ln.startswith("#!"):
714
+ ins_idx = idx_l + 1
715
+ elif s_ln.startswith("# -*-") or s_ln.startswith("# coding"):
716
+ ins_idx = idx_l + 1
717
+ elif s_ln.startswith("from __future__ import"):
718
+ ins_idx = idx_l + 1
719
+ elif s_ln and not s_ln.startswith("#"):
720
+ break
721
+ lines_m.insert(ins_idx, "import os\n")
722
+ migrated_code = "".join(lines_m)
545
723
 
546
- # Build .env text
547
724
  env_lines = ["# Auto-Vault Generated by T-Zero Zero-Leak Engine", "# DO NOT COMMIT THIS FILE TO PUBLIC REPOSITORIES", ""]
548
- for k, v in env_entries.items():
725
+ for k, v in env_registry.items():
549
726
  env_lines.append(f"{k}={v}")
550
727
  env_content = "\n".join(env_lines) + "\n"
551
728
 
552
- # If file paths provided, update physical .env and .gitignore
553
- if env_file_path:
554
- try:
555
- with open(env_file_path, "a", encoding="utf-8") as ef:
556
- ef.write("\n" + "\n".join(f"{k}={v}" for k, v in env_entries.items()) + "\n")
557
- except Exception:
558
- pass
729
+ # Stage & commit physical .gitignore and .env atomically BEFORE returning success
730
+ if not dry_run and (env_file_path or gitignore_path):
731
+ import tempfile
732
+ if env_file_path and gitignore_path is None:
733
+ gitignore_path = os.path.join(os.path.dirname(os.path.abspath(env_file_path)), ".gitignore")
559
734
 
560
- if gitignore_path:
735
+ gi_staged = None
736
+ env_staged = None
561
737
  try:
562
- gi_content = ""
563
- if os.path.exists(gitignore_path):
564
- with open(gitignore_path, "r", encoding="utf-8") as gf:
565
- gi_content = gf.read()
566
- if ".env" not in gi_content:
567
- with open(gitignore_path, "a", encoding="utf-8") as gf:
568
- gf.write("\n.env\n*.env\n")
569
- except Exception:
570
- pass
738
+ if gitignore_path and env_file_path:
739
+ git_status = cls.check_env_git_status(env_file_path, gitignore_path)
740
+ if git_status.get("warning"):
741
+ report_lines.append(f"\n> {git_status['warning']}")
742
+ if not git_status.get("ignored"):
743
+ existing_gi = ""
744
+ if os.path.isfile(gitignore_path):
745
+ with open(gitignore_path, "r", encoding="utf-8") as gf:
746
+ existing_gi = gf.read()
747
+ env_base = os.path.basename(os.path.abspath(env_file_path))
748
+ sep = "\n" if existing_gi and not existing_gi.endswith("\n") else ""
749
+ new_gi = f"{existing_gi}{sep}{env_base}\n"
750
+ gi_dir = os.path.dirname(os.path.abspath(gitignore_path)) or "."
751
+ os.makedirs(gi_dir, exist_ok=True)
752
+ with tempfile.NamedTemporaryFile("w", dir=gi_dir, delete=False, encoding="utf-8", prefix=".tzero_gi_") as tf:
753
+ tf.write(new_gi)
754
+ gi_staged = tf.name
755
+
756
+ if env_file_path:
757
+ env_dir = os.path.dirname(os.path.abspath(env_file_path)) or "."
758
+ os.makedirs(env_dir, exist_ok=True)
759
+ with tempfile.NamedTemporaryFile("w", dir=env_dir, delete=False, encoding="utf-8", prefix=".tzero_env_") as tf:
760
+ tf.write(env_content)
761
+ env_staged = tf.name
762
+
763
+ if gi_staged:
764
+ os.replace(gi_staged, gitignore_path)
765
+ gi_staged = None
766
+ if env_staged:
767
+ os.replace(env_staged, env_file_path)
768
+ env_staged = None
769
+ except Exception as exc:
770
+ for p in (gi_staged, env_staged):
771
+ if p and os.path.exists(p):
772
+ try:
773
+ os.remove(p)
774
+ except OSError:
775
+ pass
776
+ raise RuntimeError(f"Auto-Vault failed to persist environment/gitignore safely: {exc}") from exc
571
777
 
572
778
  return migrated_code, env_content, len(unique_findings), "\n".join(report_lines)
573
779
 
780
+ @classmethod
781
+ def migrate_files_atomically(
782
+ cls,
783
+ file_paths: List[str],
784
+ env_file_path: str,
785
+ gitignore_path: Optional[str] = None,
786
+ ) -> Dict[str, Any]:
787
+ """Atomically migrate multiple files using a shared env table with rollback on write errors."""
788
+ import tempfile
789
+ abs_env = os.path.abspath(env_file_path)
790
+ abs_gi = os.path.abspath(gitignore_path) if gitignore_path else os.path.join(os.path.dirname(abs_env), ".gitignore")
791
+ orig_sources: Dict[str, str] = {}
792
+ staged_sources: Dict[str, str] = {}
793
+ orig_env = None
794
+ if os.path.isfile(abs_env):
795
+ with open(abs_env, "r", encoding="utf-8") as _ef:
796
+ orig_env = _ef.read()
797
+ orig_gi = None
798
+ if os.path.isfile(abs_gi):
799
+ with open(abs_gi, "r", encoding="utf-8") as _gf:
800
+ orig_gi = _gf.read()
801
+ shared_env = cls._load_existing_env(abs_env)
802
+ total_migrated = 0
803
+
804
+ try:
805
+ for fp in file_paths:
806
+ abs_fp = os.path.abspath(fp)
807
+ with open(abs_fp, "r", encoding="utf-8", errors="ignore") as f:
808
+ raw = f.read()
809
+ migrated, _, cnt, _ = cls.auto_migrate_to_env(
810
+ raw,
811
+ env_file_path=abs_env,
812
+ gitignore_path=abs_gi,
813
+ shared_env_registry=shared_env,
814
+ dry_run=True,
815
+ )
816
+ if cnt > 0 and migrated != raw:
817
+ if abs_fp.endswith(".py"):
818
+ ast.parse(migrated, filename=abs_fp)
819
+ orig_sources[abs_fp] = raw
820
+ fdir = os.path.dirname(abs_fp) or "."
821
+ with tempfile.NamedTemporaryFile("w", dir=fdir, delete=False, encoding="utf-8", prefix=".tzero_src_") as tf:
822
+ tf.write(migrated)
823
+ staged_sources[abs_fp] = tf.name
824
+ total_migrated += cnt
825
+
826
+ if total_migrated == 0:
827
+ return {"success": True, "migrated_count": 0, "env_file": abs_env, "warning": ""}
828
+
829
+ # Write .gitignore and .env atomically BEFORE mutating any source files
830
+ git_status = cls.check_env_git_status(abs_env, abs_gi)
831
+ if not git_status.get("ignored"):
832
+ existing_gi = orig_gi or ""
833
+ env_base = os.path.basename(abs_env)
834
+ sep = "\n" if existing_gi and not existing_gi.endswith("\n") else ""
835
+ os.makedirs(os.path.dirname(abs_gi) or ".", exist_ok=True)
836
+ with tempfile.NamedTemporaryFile("w", dir=os.path.dirname(abs_gi) or ".", delete=False, encoding="utf-8", prefix=".tzero_gi_") as tf:
837
+ tf.write(f"{existing_gi}{sep}{env_base}\n")
838
+ gi_tmp = tf.name
839
+ os.replace(gi_tmp, abs_gi)
840
+
841
+ env_lines = ["# Auto-Vault Generated by T-Zero Zero-Leak Engine", "# DO NOT COMMIT THIS FILE TO PUBLIC REPOSITORIES", ""]
842
+ for k, v in shared_env.items():
843
+ env_lines.append(f"{k}={v}")
844
+ os.makedirs(os.path.dirname(abs_env) or ".", exist_ok=True)
845
+ with tempfile.NamedTemporaryFile("w", dir=os.path.dirname(abs_env) or ".", delete=False, encoding="utf-8", prefix=".tzero_env_") as tf:
846
+ tf.write("\n".join(env_lines) + "\n")
847
+ env_tmp = tf.name
848
+ os.replace(env_tmp, abs_env)
849
+
850
+ # Commit staged sources
851
+ for abs_fp, tmp_p in staged_sources.items():
852
+ os.replace(tmp_p, abs_fp)
853
+ staged_sources.clear()
854
+
855
+ return {
856
+ "success": True,
857
+ "migrated_count": total_migrated,
858
+ "env_file": abs_env,
859
+ "gitignore_file": abs_gi,
860
+ "warning": git_status.get("warning", ""),
861
+ }
862
+ except Exception as exc:
863
+ # Rollback .env / .gitignore / any partially touched sources
864
+ for tmp_p in staged_sources.values():
865
+ if os.path.exists(tmp_p):
866
+ try:
867
+ os.remove(tmp_p)
868
+ except OSError:
869
+ pass
870
+ if orig_env is not None:
871
+ try:
872
+ with open(abs_env, "w", encoding="utf-8") as ef:
873
+ ef.write(orig_env)
874
+ except OSError:
875
+ pass
876
+ elif os.path.exists(abs_env):
877
+ try:
878
+ os.remove(abs_env)
879
+ except OSError:
880
+ pass
881
+ if orig_gi is not None:
882
+ try:
883
+ with open(abs_gi, "w", encoding="utf-8") as gf:
884
+ gf.write(orig_gi)
885
+ except OSError:
886
+ pass
887
+ return {"success": False, "error": str(exc), "migrated_count": 0}
888
+
@@ -75,7 +75,7 @@ class TaskEvaluationResult:
75
75
 
76
76
  @dataclass
77
77
  class TaskBenchmarkReport:
78
- version: str = "12.2.1"
78
+ version: str = "12.2.2"
79
79
  tokenizer: str = "tiktoken (cl100k_base)" if TIKTOKEN_AVAILABLE else "character-ratio fallback"
80
80
  total_tasks: int = 0
81
81
  passed_tasks: int = 0
@@ -465,7 +465,7 @@ def analyze_symbol_impact(symbol_path: str, table: SymbolTable, dag: CallGraphDA
465
465
  """Formats ANSI-styled benchmark summary table."""
466
466
  lines = []
467
467
  lines.append("=" * 78)
468
- lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v12.2.1)")
468
+ lines.append(" T-ZERO TASK-COMPLETION & BPE TOKENIZER BENCHMARK REPORT (v12.2.2)")
469
469
  lines.append(f" Tokenizer: {report.tokenizer} | Tasks Evaluated: {report.total_tasks}")
470
470
  lines.append("=" * 78)
471
471
  lines.append(f"{'Task ID':<10} | {'Raw BPE':<8} | {'T-Zero':<8} | {'Saved %':<8} | {'Contract %':<10} | {'Status'}")