torusguard 1.3.3 → 1.3.4

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 (127) hide show
  1. package/.torusguard/runs/report-latest.html +3 -3
  2. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-115-9a059e/metadata.json +15 -0
  3. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-115-9a059e/minimal_patch_plan.md +21 -0
  4. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-115-9a059e/patch.diff +9 -0
  5. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-119-61557c/metadata.json +15 -0
  6. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-119-61557c/minimal_patch_plan.md +21 -0
  7. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-119-61557c/patch.diff +9 -0
  8. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-265-996ca3/metadata.json +15 -0
  9. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-265-996ca3/minimal_patch_plan.md +21 -0
  10. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-265-996ca3/patch.diff +9 -0
  11. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-503-d11cf8/metadata.json +15 -0
  12. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-503-d11cf8/minimal_patch_plan.md +21 -0
  13. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-503-d11cf8/patch.diff +9 -0
  14. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-79-91f41f/metadata.json +15 -0
  15. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-79-91f41f/minimal_patch_plan.md +21 -0
  16. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-db-004-79-91f41f/patch.diff +9 -0
  17. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-107-516a40/metadata.json +15 -0
  18. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-107-516a40/minimal_patch_plan.md +21 -0
  19. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-107-516a40/patch.diff +9 -0
  20. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/metadata.json +15 -0
  21. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/minimal_patch_plan.md +21 -0
  22. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-128-7809a1/patch.diff +9 -0
  23. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/metadata.json +15 -0
  24. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/minimal_patch_plan.md +21 -0
  25. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-002-256-c8a22e/patch.diff +9 -0
  26. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/metadata.json +15 -0
  27. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/minimal_patch_plan.md +21 -0
  28. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-input-003-53-d167b4/patch.diff +9 -0
  29. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-platform-001-183-47fd5e/metadata.json +15 -0
  30. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-platform-001-183-47fd5e/minimal_patch_plan.md +21 -0
  31. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-platform-001-183-47fd5e/patch.diff +9 -0
  32. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/metadata.json +15 -0
  33. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/minimal_patch_plan.md +21 -0
  34. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-209-4f6424/patch.diff +9 -0
  35. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-257-89bf34/metadata.json +15 -0
  36. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-257-89bf34/minimal_patch_plan.md +21 -0
  37. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-257-89bf34/patch.diff +9 -0
  38. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-341-ce228c/metadata.json +15 -0
  39. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-341-ce228c/minimal_patch_plan.md +21 -0
  40. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-341-ce228c/patch.diff +9 -0
  41. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-355-7b190b/metadata.json +15 -0
  42. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-355-7b190b/minimal_patch_plan.md +21 -0
  43. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-355-7b190b/patch.diff +9 -0
  44. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-64-5af31a/metadata.json +15 -0
  45. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-64-5af31a/minimal_patch_plan.md +21 -0
  46. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-64-5af31a/patch.diff +9 -0
  47. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-9-f51467/metadata.json +15 -0
  48. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-9-f51467/minimal_patch_plan.md +21 -0
  49. package/.torusguard/runs/run-20260910-120238-audit/bundles/bnd-tg-sec-001-9-f51467/patch.diff +9 -0
  50. package/.torusguard/runs/run-20260910-120238-audit/findings.json +1520 -0
  51. package/.torusguard/runs/run-20260910-120238-audit/findings.md +560 -0
  52. package/.torusguard/runs/run-20260910-120238-audit/manifest.json +13 -0
  53. package/.torusguard/runs/run-20260910-120238-audit/recheck.md +86 -0
  54. package/.torusguard/runs/run-20260910-120238-audit/remediation.md +262 -0
  55. package/.torusguard/runs/run-20260910-120238-audit/summary.md +5 -0
  56. package/.torusguard/runs/run-20260910-121238-audit/findings.json +794 -0
  57. package/.torusguard/runs/run-20260910-121238-audit/findings.md +344 -0
  58. package/.torusguard/runs/run-20260910-121238-audit/manifest.json +12 -0
  59. package/.torusguard/runs/run-20260910-121238-audit/summary.md +5 -0
  60. package/.torusguard/runs/run-20260910-130454-audit/findings.json +893 -0
  61. package/.torusguard/runs/run-20260910-130454-audit/findings.md +386 -0
  62. package/.torusguard/runs/run-20260910-130454-audit/manifest.json +12 -0
  63. package/.torusguard/runs/run-20260910-130454-audit/summary.md +5 -0
  64. package/.torusguard/runs/run-20260910-130519-audit/findings.json +563 -0
  65. package/.torusguard/runs/run-20260910-130519-audit/findings.md +246 -0
  66. package/.torusguard/runs/run-20260910-130519-audit/manifest.json +12 -0
  67. package/.torusguard/runs/run-20260910-130519-audit/summary.md +5 -0
  68. package/.torusguard/scripts/__pycache__/audit_runner.cpython-311.pyc +0 -0
  69. package/.torusguard/scripts/__pycache__/diff_guard.cpython-311.pyc +0 -0
  70. package/.torusguard/scripts/__pycache__/html_reporter.cpython-311.pyc +0 -0
  71. package/.torusguard/scripts/__pycache__/rules_sync.cpython-311.pyc +0 -0
  72. package/.torusguard/scripts/__pycache__/stack_detect.cpython-311.pyc +0 -0
  73. package/.torusguard/scripts/__pycache__/term_ui.cpython-311.pyc +0 -0
  74. package/.torusguard/scripts/apply_runner.py +138 -100
  75. package/.torusguard/scripts/audit_runner.py +219 -116
  76. package/.torusguard/scripts/harden_runner.py +144 -64
  77. package/.torusguard/scripts/recheck_runner.py +80 -63
  78. package/.torusguard/scripts/recipes_runner.py +38 -31
  79. package/.torusguard/scripts/term_ui.py +162 -0
  80. package/.torusguard/skills/torusguard/SKILL.md +61 -31
  81. package/.torusguard/skills/torusguard-apply/SKILL.md +80 -46
  82. package/.torusguard/skills/torusguard-audit/SKILL.md +83 -70
  83. package/.torusguard/skills/torusguard-authorize/SKILL.md +5 -4
  84. package/.torusguard/skills/torusguard-exploit-check/SKILL.md +6 -5
  85. package/.torusguard/skills/torusguard-full/SKILL.md +1 -1
  86. package/.torusguard/skills/torusguard-harden/SKILL.md +94 -63
  87. package/.torusguard/skills/torusguard-init/SKILL.md +64 -52
  88. package/.torusguard/skills/torusguard-recheck/SKILL.md +77 -53
  89. package/.torusguard/skills/torusguard-report/SKILL.md +72 -54
  90. package/.torusguard/skills/torusguard-status/SKILL.md +58 -42
  91. package/.torusguard/skills/torusguard-verify/SKILL.md +8 -7
  92. package/.torusguard/skills/torusguard-web-validate/SKILL.md +8 -7
  93. package/README.md +4 -3
  94. package/bin/torusguard.js +544 -437
  95. package/package.json +1 -1
  96. package/skills/torusguard/SKILL.md +61 -31
  97. package/skills/torusguard/payload/scripts/apply_runner.py +138 -100
  98. package/skills/torusguard/payload/scripts/audit_runner.py +219 -116
  99. package/skills/torusguard/payload/scripts/harden_runner.py +144 -64
  100. package/skills/torusguard/payload/scripts/recheck_runner.py +80 -63
  101. package/skills/torusguard/payload/scripts/recipes_runner.py +38 -31
  102. package/skills/torusguard/payload/scripts/term_ui.py +162 -0
  103. package/skills/torusguard/payload/skills/torusguard/SKILL.md +61 -31
  104. package/skills/torusguard/payload/skills/torusguard-apply/SKILL.md +80 -46
  105. package/skills/torusguard/payload/skills/torusguard-audit/SKILL.md +83 -70
  106. package/skills/torusguard/payload/skills/torusguard-authorize/SKILL.md +5 -4
  107. package/skills/torusguard/payload/skills/torusguard-exploit-check/SKILL.md +6 -5
  108. package/skills/torusguard/payload/skills/torusguard-full/SKILL.md +1 -1
  109. package/skills/torusguard/payload/skills/torusguard-harden/SKILL.md +94 -63
  110. package/skills/torusguard/payload/skills/torusguard-init/SKILL.md +64 -52
  111. package/skills/torusguard/payload/skills/torusguard-recheck/SKILL.md +77 -53
  112. package/skills/torusguard/payload/skills/torusguard-report/SKILL.md +72 -54
  113. package/skills/torusguard/payload/skills/torusguard-status/SKILL.md +58 -42
  114. package/skills/torusguard/payload/skills/torusguard-verify/SKILL.md +8 -7
  115. package/skills/torusguard/payload/skills/torusguard-web-validate/SKILL.md +8 -7
  116. package/skills/torusguard-apply/SKILL.md +80 -48
  117. package/skills/torusguard-audit/SKILL.md +83 -75
  118. package/skills/torusguard-authorize/SKILL.md +1 -1
  119. package/skills/torusguard-exploit-check/SKILL.md +1 -1
  120. package/skills/torusguard-full/SKILL.md +1 -1
  121. package/skills/torusguard-harden/SKILL.md +94 -67
  122. package/skills/torusguard-init/SKILL.md +64 -53
  123. package/skills/torusguard-recheck/SKILL.md +77 -54
  124. package/skills/torusguard-report/SKILL.md +72 -55
  125. package/skills/torusguard-status/SKILL.md +58 -43
  126. package/skills/torusguard-verify/SKILL.md +1 -1
  127. package/skills/torusguard-web-validate/SKILL.md +1 -1
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env python3
2
2
  """
3
- TorusGuard Golden Fix Recipe Explorer (v1.3.0)
3
+ TorusGuard Golden Fix Recipe Explorer (v1.3.3)
4
4
  Inspect, list, and export reusable, verified AST remediation code snippets
5
5
  distilled from passing security patches and persistent memory patterns.
6
+ Standardized 75-column terminal UI formatting.
6
7
 
7
8
  Pure Python 3.10+ standard library (zero external dependencies).
8
9
  """
@@ -10,11 +11,19 @@ Pure Python 3.10+ standard library (zero external dependencies).
10
11
  import sys
11
12
  import json
12
13
  import argparse
13
- import unicodedata
14
- import re
15
14
  from pathlib import Path
16
15
  from typing import Dict, List, Any, Optional
17
16
 
17
+ # Ensure scripts dir is in sys.path for term_ui import
18
+ scripts_dir = Path(__file__).resolve().parent
19
+ if str(scripts_dir) not in sys.path:
20
+ sys.path.insert(0, str(scripts_dir))
21
+
22
+ try:
23
+ import term_ui
24
+ except ImportError:
25
+ term_ui = None
26
+
18
27
  # Windows console UTF-8 support
19
28
  if sys.stdout and hasattr(sys.stdout, "reconfigure"):
20
29
  try:
@@ -22,7 +31,7 @@ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
22
31
  except Exception:
23
32
  pass
24
33
 
25
- # ─── ANSI Colors & Formatter ───────────────────────────────────────────────────
34
+ # ─── Formatting Helpers ────────────────────────────────────────────────────────
26
35
  BOLD = "\033[1m"
27
36
  DIM = "\033[2m"
28
37
  RESET = "\033[0m"
@@ -33,25 +42,25 @@ WHITE = "\033[97m"
33
42
  GRAY = "\033[90m"
34
43
  RED = "\033[31m"
35
44
 
36
- ANSI_REGEX = re.compile(r'\033\[[0-9;]*m')
45
+ def box_line(content: str, width: int = 67, border: str = "│", border_color: str = CYAN) -> str:
46
+ if term_ui:
47
+ return term_ui.format_box_line(content, width=width, border=border, border_color=border_color)
48
+ return f" {border_color}{border}{RESET} {content}"
49
+
50
+ def box_header(title: str, subtitle: str = "", version: str = "v1.3.3", border_color: str = CYAN) -> str:
51
+ if term_ui:
52
+ return term_ui.card_header(title, subtitle, version, border_color)
53
+ return f"=== {title} ({version}) ==="
37
54
 
38
- def get_visual_width(text: str) -> int:
39
- clean = ANSI_REGEX.sub('', text)
40
- width = 0
41
- for ch in clean:
42
- ea = unicodedata.east_asian_width(ch)
43
- if ea in ('W', 'F'):
44
- width += 2
45
- elif ord(ch) >= 0x1F300:
46
- width += 2
47
- else:
48
- width += 1
49
- return width
55
+ def border_top(title: str = "", border_color: str = CYAN, double: bool = False) -> str:
56
+ if term_ui:
57
+ return term_ui.card_border_top(title, border_color=border_color, double=double)
58
+ return "┌" + "─" * 71 + "┐"
50
59
 
51
- def format_box_line(content: str, width: int = 71, border: str = "│", border_color: str = CYAN) -> str:
52
- vis = get_visual_width(content)
53
- pad = " " * max(0, width - vis)
54
- return f" {border_color}{border}{RESET} {content}{pad}{border_color}{border}{RESET}"
60
+ def border_bottom(border_color: str = CYAN, double: bool = False) -> str:
61
+ if term_ui:
62
+ return term_ui.card_border_bottom(border_color=border_color, double=double)
63
+ return "└" + "─" * 71 + "┘"
55
64
 
56
65
 
57
66
  def list_recipes(target_root: Path, detail_id: Optional[str] = None, json_output: bool = False) -> None:
@@ -70,19 +79,16 @@ def list_recipes(target_root: Path, detail_id: Optional[str] = None, json_output
70
79
  return
71
80
 
72
81
  # Header Card
73
- print(f"\n {CYAN}╭─────────────────────────────────────────────────────────────────────────╮{RESET}")
74
- print(f" {CYAN}│ │{RESET}")
75
- print(format_box_line(f"{BOLD}🛡️ TORUSGUARD GOLDEN FIX RECIPES v1.3.0{RESET}", border_color=CYAN))
76
- print(format_box_line(f"{DIM}Distilled Ponytail Fixes (<= 35 add, <= 25 del) in Persistent Memory{RESET}", border_color=CYAN))
77
- print(f" {CYAN}│ │{RESET}")
78
- print(f" {CYAN}╰─────────────────────────────────────────────────────────────────────────╯{RESET}\n")
82
+ print()
83
+ print(box_header("🛡️ TORUSGUARD GOLDEN FIX RECIPES", "Distilled Ponytail Fixes (<= 35 add, <= 25 del) in Persistent Memory", "v1.3.3"))
84
+ print()
79
85
 
80
86
  if not recipes:
81
87
  print(f" {YELLOW}ℹ No golden fix recipes captured yet.{RESET}")
82
88
  print(f" Run {CYAN}npx torusguard harden{RESET} followed by {CYAN}npx torusguard apply{RESET} to distill verified recipes.\n")
83
89
  return
84
90
 
85
- print(f" {CYAN}┌─ Active Distilled Recipes ({len(recipes)}) ─────────────────────────────────────┐{RESET}")
91
+ print(border_top(f"Active Distilled Recipes ({len(recipes)})"))
86
92
  for idx, r in enumerate(recipes, 1):
87
93
  rule_id = r.get("rule_id", "TG-SEC")
88
94
  rec_id = r.get("recipe_id", f"recipe-{idx}")
@@ -93,9 +99,10 @@ def list_recipes(target_root: Path, detail_id: Optional[str] = None, json_output
93
99
  adds = metrics.get("additions", 0)
94
100
  dels = metrics.get("deletions", 0)
95
101
 
96
- print(format_box_line(f"{GREEN}[{rule_id}]{RESET} {WHITE}{rec_id}{RESET} (Verified {verified}x · +{adds}/-{dels} Ponytail)"))
97
- print(format_box_line(f" └─ {DIM}{desc}{RESET}"))
98
- print(f" {CYAN}└─────────────────────────────────────────────────────────────────────────┘{RESET}\n")
102
+ print(box_line(f"{GREEN}[{rule_id}]{RESET} {WHITE}{rec_id}{RESET} (Verified {verified}x · +{adds}/-{dels} Ponytail)"))
103
+ print(box_line(f" └─ {DIM}{desc}{RESET}"))
104
+ print(border_bottom())
105
+ print()
99
106
 
100
107
  if detail_id:
101
108
  target_rec = next((r for r in recipes if r.get("recipe_id") == detail_id), None)
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ TorusGuard Unified Terminal UI Engine (v1.3.3)
4
+ Provides mathematically exact 75-column card formatting, ANSI-stripping,
5
+ Unicode/emoji visual width calculation, and visual truncation with ellipsis.
6
+ Pure Python 3.10+ standard library (zero external dependencies).
7
+ """
8
+
9
+ import sys
10
+ import os
11
+ import re
12
+ import unicodedata
13
+ from typing import Optional
14
+
15
+ # Ensure UTF-8 stdout/stderr on Windows consoles
16
+ if sys.stdout and hasattr(sys.stdout, "reconfigure"):
17
+ try:
18
+ getattr(sys.stdout, "reconfigure")(encoding="utf-8", errors="replace")
19
+ except Exception:
20
+ pass
21
+ if sys.stderr and hasattr(sys.stderr, "reconfigure"):
22
+ try:
23
+ getattr(sys.stderr, "reconfigure")(encoding="utf-8", errors="replace")
24
+ except Exception:
25
+ pass
26
+
27
+ # ─── ANSI Colors & Styles ─────────────────────────────────────────────────────
28
+ BOLD = "\033[1m"
29
+ DIM = "\033[2m"
30
+ RESET = "\033[0m"
31
+ CYAN = "\033[36m"
32
+ GREEN = "\033[32m"
33
+ YELLOW = "\033[33m"
34
+ WHITE = "\033[97m"
35
+ GRAY = "\033[90m"
36
+ RED = "\033[31m"
37
+ MAGENTA = "\033[35m"
38
+ BG_GREEN = "\033[42m"
39
+ BG_CYAN = "\033[46m"
40
+
41
+ ANSI_REGEX = re.compile(r'\x1b\[[0-9;]*m|\033\[[0-9;]*m')
42
+
43
+ def strip_ansi(text: str) -> str:
44
+ """Remove all ANSI color and style escape sequences."""
45
+ return ANSI_REGEX.sub('', text)
46
+
47
+ def get_visual_width(text: str) -> int:
48
+ """
49
+ Calculate the printable display width of a string in terminal columns.
50
+ Accounts for ANSI escapes, Unicode variation selectors, emojis, and fullwidth chars.
51
+ """
52
+ clean = strip_ansi(text)
53
+ width = 0
54
+ for ch in clean:
55
+ cp = ord(ch)
56
+ # Variation selectors (VS1-16, VS17-256) occupy 0 terminal columns
57
+ if (0xFE00 <= cp <= 0xFE0F) or (0xE0100 <= cp <= 0xE01EF):
58
+ continue
59
+ # Zero-width spaces, joiners, soft hyphens
60
+ if cp in (0x200B, 0x200C, 0x200D, 0x00AD):
61
+ continue
62
+ ea = unicodedata.east_asian_width(ch)
63
+ if ea in ('W', 'F'):
64
+ width += 2
65
+ elif cp >= 0x1F300: # Emojis and miscellaneous pictographs
66
+ width += 2
67
+ elif cp in (0x26A0, 0x2714, 0x2716, 0x2139): # ⚠, ✔, ✖, ℹ
68
+ width += 1
69
+ else:
70
+ width += 1
71
+ return width
72
+
73
+ def truncate_visual(text: str, max_w: int = 67) -> str:
74
+ """Truncate text visually to max_w columns without breaking ANSI escape codes."""
75
+ if get_visual_width(text) <= max_w:
76
+ return text
77
+ out = []
78
+ curr_w = 0
79
+ in_ansi = False
80
+ ansi_buf = ''
81
+ for ch in text:
82
+ if ch in ('\033', '\x1b'):
83
+ in_ansi = True
84
+ ansi_buf = ch
85
+ continue
86
+ if in_ansi:
87
+ ansi_buf += ch
88
+ if ch == 'm':
89
+ in_ansi = False
90
+ out.append(ansi_buf)
91
+ continue
92
+ cp = ord(ch)
93
+ if (0xFE00 <= cp <= 0xFE0F) or (0xE0100 <= cp <= 0xE01EF) or cp in (0x200B, 0x200C, 0x200D, 0x00AD):
94
+ out.append(ch)
95
+ continue
96
+ ea = unicodedata.east_asian_width(ch)
97
+ cw = 2 if (ea in ('W', 'F') or cp >= 0x1F300) else 1
98
+ if curr_w + cw > max_w - 3:
99
+ out.append(RESET + '...')
100
+ curr_w += 3
101
+ break
102
+ out.append(ch)
103
+ curr_w += cw
104
+ out.append(RESET)
105
+ return ''.join(out)
106
+
107
+ def format_box_line(content: str, width: int = 67, border: str = "│", border_color: str = CYAN) -> str:
108
+ """
109
+ Pad content so the card line is strictly 75 visual columns total width.
110
+ Layout: ' ' (2) + border (1) + ' ' (2) + content/pad (width=67) + ' ' (2) + border (1) = 75 cols.
111
+ """
112
+ trunc = truncate_visual(content, width)
113
+ vis = get_visual_width(trunc)
114
+ pad = " " * max(0, width - vis)
115
+ return f" {border_color}{border}{RESET} {trunc}{pad} {border_color}{border}{RESET}"
116
+
117
+ def card_border_top(title: str = "", border_color: str = CYAN, double: bool = False) -> str:
118
+ """Generate 75-column top border (single ┌ or double ╔) with optional title."""
119
+ left = "╔" if double else "┌"
120
+ right = "╗" if double else "┐"
121
+ h = "═" if double else "─"
122
+ if title:
123
+ vis = get_visual_width(title)
124
+ rem = max(0, 68 - vis)
125
+ return f" {border_color}{left}{h} {BOLD}{WHITE}{title}{RESET}{border_color} {h * rem}{right}{RESET}"
126
+ return f" {border_color}{left}{h * 71}{right}{RESET}"
127
+
128
+ def card_border_bottom(border_color: str = CYAN, double: bool = False) -> str:
129
+ """Generate 75-column bottom border (single └ or double ╚)."""
130
+ left = "╚" if double else "└"
131
+ right = "╝" if double else "┘"
132
+ h = "═" if double else "─"
133
+ return f" {border_color}{left}{h * 71}{right}{RESET}"
134
+
135
+ def card_divider(title: str = "", border_color: str = CYAN, double: bool = False) -> str:
136
+ """Generate 75-column divider (single ├ or double ╠) with optional title."""
137
+ left = "╠" if double else "├"
138
+ right = "╣" if double else "┤"
139
+ h = "═" if double else "─"
140
+ if title:
141
+ vis = get_visual_width(title)
142
+ rem = max(0, 68 - vis)
143
+ return f" {border_color}{left}{h} {BOLD}{WHITE}{title}{RESET}{border_color} {h * rem}{right}{RESET}"
144
+ return f" {border_color}{left}{h * 71}{right}{RESET}"
145
+
146
+ def card_header(title: str, subtitle: str = "", version: str = "v1.3.4", border_color: str = CYAN) -> str:
147
+ """Generate standardized 75-column curved header box."""
148
+ top = f" {border_color}╭{'─' * 71}╮{RESET}"
149
+ bottom = f" {border_color}╰{'─' * 71}╯{RESET}"
150
+ empty = f" {border_color}│{' ' * 71}│{RESET}"
151
+
152
+ # Calculate padding between title and version
153
+ title_vis = get_visual_width(title)
154
+ ver_vis = get_visual_width(version)
155
+ space_count = max(1, 67 - title_vis - ver_vis)
156
+ title_str = f"{BOLD}{WHITE}{title}{RESET}{' ' * space_count}{GRAY}{version}{RESET}"
157
+
158
+ lines = [top, empty, format_box_line(title_str, width=67, border_color=border_color)]
159
+ if subtitle:
160
+ lines.append(format_box_line(f"{DIM}{subtitle}{RESET}", width=67, border_color=border_color))
161
+ lines.extend([empty, bottom])
162
+ return "\n".join(lines)
@@ -1,42 +1,72 @@
1
1
  ---
2
2
  name: torusguard
3
- description: "Universal autonomous security engine: 71 rules across 11 families, polyglot stack detection across 16+ languages, governed remediation (Ponytail Protocol <=35 add, <=25 del), SARIF v2.1.0 exports, single-file HTML dashboards, and persistent security memory context for modern web applications."
4
- version: 1.3.2
3
+ description: Universal autonomous security engine: 71 canonical rules across 11 families, polyglot stack detection across 16+ languages, Ponytail remediation bounds (<=35 add, <=25 del), standardized 75-column terminal UI, SARIF v2.1.0 exports, and persistent security memory context.
4
+ version: 1.3.4
5
5
  ---
6
6
 
7
- # TorusGuard Master Security Router
7
+ # TorusGuard Master Security Engine & Command Router
8
8
 
9
- **Principle:** If the browser or client receives it, users can inspect it. Keep secrets, database queries, and authorization strictly on trusted server-side code.
9
+ **Core Invariant:** If the browser or client receives it, users can inspect it. Never expose database credentials, master keys, or private API secrets in client bundles. Always isolate multi-tenant database queries.
10
10
 
11
11
  ---
12
12
 
13
- ## ⚡ Workspace Bootstrap Check
14
- 1. **If `.torusguard/` exists on disk:** Full autonomous governance active. Load `.torusguard/memory/context.json` into prompt context for local-first intelligence. Route commands to specialist workflows below.
15
- 2. **If `.torusguard/` is absent (Autonomous AI Mode):** Operates standalone in any AI agent (Kimi, Antigravity, VS Code, Cursor, Claude Code, Windsurf). Apply universal security invariants:
16
- - Server-side auth & tenant scoping (`.filter(tenant=...)`, `.Where("tenant_id = ?")`, `where: { tenantId: ... }`).
17
- - Zero client-side secrets (`SUPABASE_SERVICE_ROLE_KEY`, live API keys, Stripe secret keys).
18
- - Ponytail Protocol patch limits ($\le 35$ additions, $\le 25$ deletions, zero full-file rewrites).
19
- - *Upgrade:* Run `npx torusguard init` to unlock local `.torusguard/` workspace tracking, persistent memory, and individual slash commands.
13
+ ## Command Catalog: Terminal CLI & AI Chat Parity
14
+
15
+ TorusGuard operates with 100% feature parity across both the terminal CLI and AI chat slash commands:
16
+
17
+ | Capability | Terminal CLI Command | AI Chat Slash Command | Specialist Skill | Purpose |
18
+ | :--- | :--- | :--- | :--- | :--- |
19
+ | **Init** | `npx torusguard init` | `/torusguard init` | `skills/torusguard-init` | Stack discovery, rule activation, workspace scaffolding |
20
+ | **Status** | `npx torusguard status` | `/torusguard status` | `skills/torusguard-status` | Posture score, active rules, run history, scope check |
21
+ | **Audit** | `npx torusguard audit` | `/torusguard audit` | `skills/torusguard-audit` | Static AST scan, invariant fingerprinting, confidence scoring |
22
+ | **Verify** | `npx torusguard verify` | `/torusguard verify` | `skills/torusguard-verify` | Evidence sufficiency audit & line match calibration |
23
+ | **Harden** | `npx torusguard harden` | `/torusguard harden` | `skills/torusguard-harden` | Ponytail patch formulation ($\le 35$ add, $\le 25$ del) |
24
+ | **Apply** | `npx torusguard apply [--yes]` | `/torusguard apply` | `skills/torusguard-apply` | Human Gate review, `.bak` snapshots, patch application |
25
+ | **Rollback** | `npx torusguard rollback` | `/torusguard rollback` | `skills/torusguard-apply` | Instant 1-step rollback from pre-apply snapshots |
26
+ | **Recheck** | `npx torusguard recheck` | `/torusguard recheck` | `skills/torusguard-recheck` | Targeted differential AST scan, fix closure verification |
27
+ | **Recipes** | `npx torusguard recipes` | `/torusguard recipes` | `skills/torusguard-harden` | Explore verified Golden Fix Recipes from persistent memory |
28
+ | **Report** | `npx torusguard report --html` | `/torusguard report` | `skills/torusguard-report` | Executive posture reporting, SARIF v2.1.0 & visual HTML |
29
+ | **Authorize** | `npx torusguard authorize` | `/torusguard authorize` | `skills/torusguard-authorize`| Legal scope definition & safety boundaries |
30
+ | **Validate** | `npx torusguard web-validate` | `/torusguard web-validate` | `skills/torusguard-web-validate`| Authorized non-destructive HTTP probing |
31
+ | **Exploit** | `npx torusguard exploit-check` | `/torusguard exploit-check`| `skills/torusguard-exploit-check`| Bounded single-step exploitability confirmation |
32
+ | **Full** | `npx torusguard full` | `/torusguard full` | `skills/torusguard-full` | End-to-end 7-stage closed-loop execution |
33
+ | **Sync** | `npx torusguard rules sync` | `/torusguard rules sync` | `skills/torusguard-init` | Synchronize rules across AI editors (Cursor, Claude, Antigravity) |
34
+
35
+ ---
36
+
37
+ ## Non-Negotiable Invariants
38
+
39
+ 1. **Browser-Code Truth:** If the client receives it, it is public. Zero hardcoded secrets (`SUPABASE_SERVICE_ROLE_KEY`, private tokens, live API keys) in frontend code.
40
+ 2. **Multi-Tenant Isolation:** All database lookups must be scoped by organization or user ownership (`tenant_id`, `organization_id`, `where: { tenantId }`).
41
+ 3. **Ponytail Churn Bounds:** Patches must be minimal and surgical ($\le 35$ additions, $\le 25$ deletions). Never perform full-file rewrites.
42
+ 4. **Standardized 75-Column Terminal:** All CLI terminal output is strictly normalized to 75 visual columns with Unicode emoji width calculation, ANSI escape handling, and visual truncation with ellipsis (`...`).
43
+ 5. **Zero Security Bypasses:** Never insert `# nosec`, `verify=False`, `InsecureSkipVerify: true`, `[AllowAnonymous]`, or `csrf().disable()`.
44
+ 6. **Snapshots Before Edits:** Every code modification must capture a byte-for-byte pre-apply backup in `.torusguard/snapshots/<run_id>/` before touching disk code.
20
45
 
21
46
  ---
22
47
 
23
- ## Specialist Skill Routing (Lazy Loading)
24
- Load **only** the designated sub-skill on demand to preserve the 1,000–1,500 token budget:
25
-
26
- | Command | Specialist Skill | Agent | Purpose |
27
- | :--- | :--- | :--- | :--- |
28
- | `/torusguard init` | `skills/torusguard-init/SKILL.md` | `profiler` | Workspace discovery, stack detection & scaffolding |
29
- | `/torusguard authorize` | `skills/torusguard-authorize/SKILL.md` | `reviewer` | Legal scope definition & safety boundaries |
30
- | `/torusguard audit` | `skills/torusguard-audit/SKILL.md` | `auditor` | Static AST security audit & root-cause clustering |
31
- | `/torusguard verify` | `skills/torusguard-verify/SKILL.md` | `validator` | Evidence sufficiency & line match audit |
32
- | `/torusguard web-validate` | `skills/torusguard-web-validate/SKILL.md` | `validator` | Authorized non-destructive HTTP probing |
33
- | `/torusguard exploit-check`| `skills/torusguard-exploit-check/SKILL.md`| `validator` | Bounded single-step exploitability confirmation |
34
- | `/torusguard harden` | `skills/torusguard-harden/SKILL.md` | `remediator`| Governed remediation under Ponytail Protocol |
35
- | `/torusguard apply` | `skills/torusguard-apply/SKILL.md` | `remediator`| Governed patch application with rollback snapshots |
36
- | `/torusguard recheck` | `skills/torusguard-recheck/SKILL.md` | `reviewer` | Differential AST re-scan & closure verification |
37
- | `/torusguard report` | `skills/torusguard-report/SKILL.md` | `reviewer` | Executive posture reporting, SARIF & visual HTML export |
38
- | `/torusguard status` | `skills/torusguard-status/SKILL.md` | `reviewer` | Diagnostic overview of posture, stack & rules |
39
- | `/torusguard memory` | `skills/torusguard/SKILL.md` | `reviewer` | Persistent memory inspection, decay & context cards |
40
- | `/torusguard full` | `skills/torusguard-full/SKILL.md` | *All* | End-to-end 7-stage closed-loop execution |
41
-
42
- *Note: Never load all skills simultaneously. Lazy-load strictly on demand.*
48
+ ## Workspace Layout Structure
49
+ ```
50
+ .torusguard/
51
+ ├── config/
52
+ │ ├── torusguard.json # Detected stack, settings, and rule counts
53
+ │ └── scope.json # Authorized runtime validation targets & TTL
54
+ ├── memory/
55
+ │ ├── context.json # Aggregated security memory context
56
+ │ ├── patterns.json # Distilled Golden Fix Recipes
57
+ │ └── events.json # Historical audit, apply, and recheck events
58
+ ├── rules/
59
+ │ └── active/ # Active TG-* rule definitions
60
+ ├── runs/
61
+ │ └── run-YYYYMMDD-HHMMSS-audit/
62
+ │ ├── findings.json # Machine-readable AST findings
63
+ │ ├── findings.md # Actionable markdown finding cards
64
+ │ ├── remediation.md # Formulated candidate patch catalog
65
+ │ ├── diff_summary.md # Summary of applied diffs
66
+ │ ├── recheck.md # Differential recheck status transitions
67
+ │ ├── report.html # Single-file visual dark-mode HTML report
68
+ │ ├── results.sarif # OASIS SARIF v2.1.0 log
69
+ │ └── bundles/ # Formulated Ponytail remediation bundles
70
+ └── snapshots/
71
+ └── run-YYYYMMDD-HHMMSS-audit/ # Pre-apply .bak files for instant rollback
72
+ ```
@@ -1,46 +1,80 @@
1
- ---
2
- name: torusguard-apply
3
- description: Apply governed remediation patches to disk with pre-apply rollback snapshots and Human Gate validation.
4
- version: 0.9.2
5
- workflow: .torusguard/workflows/apply.md
6
- tools: Read, Grep, Glob, Bash, Edit, Write
7
- scripts-binding:
8
- - .torusguard/scripts/run_manager.py
9
- - .torusguard/scripts/diff_guard.py
10
- ---
11
-
12
- # TorusGuard Apply — Governed Patch Application & Rollback Snapshot
13
-
14
- ## Objective
15
- Safely apply approved remediation bundles to disk source files, capturing a byte-for-byte pre-apply backup snapshot and asserting syntax validity post-patch.
16
-
17
- ---
18
-
19
- ## Execution Steps
20
-
21
- 1. **Load Bundle:** Read `patch.diff` and metadata from `.torusguard/runs/<run_id>/remediation/<finding_id>/`.
22
- 2. **Pre-Apply Snapshot:** Save exact backup to `.torusguard/runs/<run_id>/pre_apply/<filename>.bak`.
23
- 3. **Obtain Human Gate:** Confirm user approval for proposed diff.
24
- 4. **Apply Patch:** Execute surgical modification using `replace_file_content` or `patch`.
25
- 5. **Assert Integrity:** Verify modified file compiles cleanly without syntax errors.
26
- 6. **Record Ledger:** Log timestamp, file path, and post-patch SHA-256 in `apply-log.json`.
27
-
28
- ---
29
-
30
- ## Governance & Safety Rules
31
- - Hard limit: additions $\le 35$, deletions $\le 25$ lines.
32
- - Always create a rollback snapshot before modifying disk code.
33
- - If compile or syntax error occurs, instantly restore from `.bak`.
34
- - Require explicit operator confirmation before writing changes.
35
-
36
- ---
37
-
38
- ## Output Format
39
- ```markdown
40
- 🚀 [TorusGuard] Patch Applied Successfully
41
- - Finding Target: <Finding ID> | File: <Path>
42
- - Churn: +<Additions> / -<Deletions>
43
- - Rollback Backup: `.torusguard/runs/<run_id>/pre_apply/<file>.bak`
44
- - Compile Check: PASSED
45
- Next: Run `/torusguard recheck` to verify vulnerability is closed.
46
- ```
1
+ ---
2
+ name: torusguard-apply
3
+ description: Apply governed remediation patches to disk with pre-apply rollback snapshots and Human Gate validation via CLI or AI Agent.
4
+ version: 1.3.4
5
+ workflow: .torusguard/workflows/apply.md
6
+ tools: Read, Grep, Glob, Write, replace_file_content, run_command
7
+ scripts-binding:
8
+ - .torusguard/scripts/apply_runner.py
9
+ - .torusguard/scripts/term_ui.py
10
+ - .torusguard/scripts/memory_engine.py
11
+ ---
12
+
13
+ # TorusGuard Apply — Governed Patch Application & Rollback Snapshot
14
+
15
+ ## Objective
16
+ Safely apply approved remediation bundles to disk source files, creating an automated byte-for-byte pre-apply backup snapshot (`.bak`) in `.torusguard/snapshots/<run_id>/`, asserting syntax validity, and distilling passing patterns into Golden Fix Recipes.
17
+
18
+ ---
19
+
20
+ ## Two Execution Modes
21
+
22
+ ### Mode A: Automated CLI Execution (Interactive or Non-Interactive)
23
+ Run the governed patch applier from your terminal:
24
+ ```bash
25
+ # Interactive Human Gate review (prompts for each patch: [y]es / [n]o / [a]ll / [q]uit)
26
+ npx torusguard apply
27
+
28
+ # Non-interactive automated application
29
+ npx torusguard apply --yes
30
+
31
+ # Apply patches from a specific run ID
32
+ npx torusguard apply --run run-20260910-121618-audit --yes
33
+
34
+ # Emergency rollback from pre-apply snapshot
35
+ npx torusguard rollback
36
+ # or
37
+ npx torusguard apply --rollback
38
+ ```
39
+ **Under the Hood:** Executes `python .torusguard/scripts/apply_runner.py`.
40
+ 1. Reads candidate bundles from `.torusguard/runs/<run_id>/bundles/`.
41
+ 2. Creates `.bak` snapshot in `.torusguard/snapshots/<run_id>/<rel_path>.bak`.
42
+ 3. Performs line-aware replacement without corrupting concurrent modifications.
43
+ 4. Distills the applied fix into a **Golden Fix Recipe** registered in `.torusguard/memory/patterns.json`.
44
+ 5. Emits `diff_summary.md` and `apply_plan.md` in the run directory.
45
+ 6. Displays pixel-perfect 75-column terminal cards.
46
+
47
+ ### Mode B: In-Session AI Chat Agent Application
48
+ When applying patches directly within an AI chat session:
49
+ 1. **Human Gate Confirmation:** Present the unified diff to the operator and request explicit approval before editing code.
50
+ 2. **Pre-Apply Snapshot:** Ensure target file backup is created at `.torusguard/snapshots/<run_id>/<rel_path>.bak`.
51
+ 3. **Execute Surgical Edit:** Use `replace_file_content` to apply only the approved lines. Strictly adhere to the formulated Ponytail diff.
52
+ 4. **Syntax & Integrity Check:** Verify that the patched file is syntactically valid (e.g. `node --check <file>` or `python -m py_compile <file>`). If syntax fails, immediately restore from `.bak`.
53
+ 5. **Memory Registration:** Update persistent memory events in `.torusguard/memory/events.json` with event `fix_applied`.
54
+ 6. **Recommend Recheck:** Advise running `/torusguard recheck` or `npx torusguard recheck` to verify closure.
55
+
56
+ ---
57
+
58
+ ## Rollback Guarantee
59
+ If an applied patch introduces unexpected runtime behavior or breaks tests:
60
+ ```bash
61
+ # Instant one-command rollback of the latest applied run:
62
+ npx torusguard rollback
63
+
64
+ # Or rollback a specific run:
65
+ npx torusguard rollback --run run-20260910-121618-audit
66
+ ```
67
+ All affected files are restored byte-for-byte from `.torusguard/snapshots/<run_id>/`.
68
+
69
+ ---
70
+
71
+ ## Output Card Format
72
+ ```markdown
73
+ ### 🚀 TorusGuard Patch Applied Successfully
74
+ - **Target File:** `server/index.js:9`
75
+ - **Rule ID:** `TG-SEC-001` (Hardcoded JWT secret)
76
+ - **Ponytail Churn:** +1 / -1
77
+ - **Rollback Snapshot:** `.torusguard/snapshots/<run_id>/server/index.js.bak`
78
+ - **Golden Recipe:** Distilled into persistent memory
79
+ - **Next Step:** Run `npx torusguard recheck` or `/torusguard recheck` to verify closure
80
+ ```