@teevee98/synapse-hub 3.8.5 → 3.9.1

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 (44) hide show
  1. package/.agents/skills/playwright-webapp-testing/SKILL.md +6 -4
  2. package/.agents/skills/token-and-context-optimizer/SKILL.md +1 -1
  3. package/.cursor/rules/agents.mdc +1 -1
  4. package/NOTICE +48 -0
  5. package/README.en.md +2 -2
  6. package/README.md +2 -2
  7. package/agentskills.json +1 -1
  8. package/docs/ARCHITECTURE.en.md +5 -1
  9. package/docs/ARCHITECTURE.md +5 -1
  10. package/docs/CLI_REFERENCE.en.md +7 -11
  11. package/docs/CLI_REFERENCE.md +7 -11
  12. package/docs/QUALITY_GATES.en.md +5 -5
  13. package/docs/QUALITY_GATES.md +5 -5
  14. package/docs/adopted-ecosystem-tools.md +37 -0
  15. package/docs/diagrams/clean_pom.svg +48 -0
  16. package/docs/diagrams/fsm_flow.svg +78 -0
  17. package/package.json +1 -1
  18. package/plugin.json +1 -1
  19. package/scripts/install.ps1 +1 -1
  20. package/skills_manifest.json +1 -1
  21. package/synapse.config.json +1 -1
  22. package/tools/__init__.py +1 -1
  23. package/tools/browser_helpers.js +2 -2
  24. package/tools/build_consolidated_report.py +1640 -0
  25. package/tools/cli.py +3 -3
  26. package/tools/core/memory_bus.py +25 -24
  27. package/tools/core/process_supervisor.py +15 -5
  28. package/tools/dashboard_generator.py +6 -6
  29. package/tools/diagram_architect.py +220 -0
  30. package/tools/distill_log.py +31 -0
  31. package/tools/git_worktree_manager.py +185 -0
  32. package/tools/humanize_linter.py +4 -0
  33. package/tools/interview_story.py +25 -2
  34. package/tools/mcp_docx_server.py +1 -1
  35. package/tools/mcp_excel_server.py +1 -1
  36. package/tools/mcp_server.py +1 -1
  37. package/tools/mechanical_ui_gate.py +242 -0
  38. package/tools/pairwise_generator.py +175 -0
  39. package/tools/repo_map.py +1 -1
  40. package/tools/runaway_stopper.py +178 -0
  41. package/tools/ui_server.py +1 -1
  42. package/tools/update_sentinel.py +3 -3
  43. package/tools/verify_all.py +15 -0
  44. package/tools/welcome_page.py +1 -1
package/tools/cli.py CHANGED
@@ -99,7 +99,7 @@ def cmd_set_lang(args):
99
99
  def cmd_version(args):
100
100
  """Displays the current hub version, skill catalog count, and license information."""
101
101
  manifest_path = os.path.join(REPO_ROOT, "skills_manifest.json")
102
- version = "3.8.5"
102
+ version = "3.9.1"
103
103
  if os.path.exists(manifest_path):
104
104
  try:
105
105
  import json
@@ -680,14 +680,14 @@ def cmd_trend(args):
680
680
 
681
681
  def _hub_version():
682
682
  manifest_path = os.path.join(REPO_ROOT, "skills_manifest.json")
683
- version = "3.8.5"
683
+ version = "3.9.1"
684
684
  if os.path.exists(manifest_path):
685
685
  try:
686
686
  import json
687
687
  with open(manifest_path, "r", encoding="utf-8") as f:
688
688
  version = json.load(f).get("version", version)
689
689
  except (OSError, json.JSONDecodeError):
690
- version = "3.8.5"
690
+ version = "3.9.1"
691
691
  return version
692
692
 
693
693
 
@@ -821,32 +821,33 @@ class UnifiedMemoryBus:
821
821
  Removes succeeding events and appends a ROLLBACK_EXECUTED audit event.
822
822
  """
823
823
  with self._lock:
824
- cur = self._conn.cursor()
825
- cur.execute(
826
- "SELECT sequence FROM event_stream WHERE session_id = ? AND checkpoint_name = ? ORDER BY sequence DESC LIMIT 1;",
827
- (session_id, checkpoint_name)
828
- )
829
- row = cur.fetchone()
830
- if not row:
831
- cur.close()
832
- raise ValueError(f"Checkpoint '{checkpoint_name}' not found for session '{session_id}'.")
824
+ with self.transaction():
825
+ cur = self._conn.cursor()
826
+ cur.execute(
827
+ "SELECT sequence FROM event_stream WHERE session_id = ? AND checkpoint_name = ? ORDER BY sequence DESC LIMIT 1;",
828
+ (session_id, checkpoint_name)
829
+ )
830
+ row = cur.fetchone()
831
+ if not row:
832
+ cur.close()
833
+ raise ValueError(f"Checkpoint '{checkpoint_name}' not found for session '{session_id}'.")
833
834
 
834
- cp_seq = row["sequence"]
835
- # Delete events after this checkpoint sequence
836
- cur.execute(
837
- "DELETE FROM event_stream WHERE session_id = ? AND sequence > ?;",
838
- (session_id, cp_seq)
839
- )
840
- cur.close()
835
+ cp_seq = row["sequence"]
836
+ # Atomically delete events after this checkpoint sequence
837
+ cur.execute(
838
+ "DELETE FROM event_stream WHERE session_id = ? AND sequence > ?;",
839
+ (session_id, cp_seq)
840
+ )
841
+ cur.close()
841
842
 
842
- # Record rollback event
843
- return self.record_event(
844
- session_id=session_id,
845
- event_type="ROLLBACK_EXECUTED",
846
- actor="system",
847
- stage="ROLLBACK_CONTROLLER",
848
- payload={"target_checkpoint": checkpoint_name, "reverted_to_sequence": cp_seq}
849
- )
843
+ # Record rollback audit event within the exact same atomic transaction
844
+ return self.record_event(
845
+ session_id=session_id,
846
+ event_type="ROLLBACK_EXECUTED",
847
+ actor="system",
848
+ stage="ROLLBACK_CONTROLLER",
849
+ payload={"target_checkpoint": checkpoint_name, "reverted_to_sequence": cp_seq}
850
+ )
850
851
 
851
852
  # ---------------------------------------------------------------------------
852
853
  # Diagnostics & Lifecycle
@@ -119,20 +119,30 @@ def kill_process_tree(pid: int, timeout: float = 2.0) -> bool:
119
119
  _ = err
120
120
 
121
121
  try:
122
- pgid = os.getpgid(pid)
122
+ caller_pgrp = os.getpgrp() if hasattr(os, "getpgrp") else None
123
+ candidate_pgid = os.getpgid(pid)
124
+ # Only signal process group if target process is its own group leader
125
+ # AND it is not the supervisor/caller's own process group
126
+ if candidate_pgid == pid and (caller_pgrp is None or candidate_pgid != caller_pgrp):
127
+ pgid = candidate_pgid
128
+ else:
129
+ pgid = None
123
130
  except OSError as err:
124
131
  _ = err
125
132
  pgid = None
126
133
 
134
+ sig_term = getattr(signal, "SIGTERM", 15)
135
+ sig_kill = getattr(signal, "SIGKILL", 9)
136
+
127
137
  # Stage 1: Graceful SIGTERM to process group and individual descendants
128
138
  if pgid is not None:
129
139
  try:
130
- os.killpg(pgid, signal.SIGTERM)
140
+ os.killpg(pgid, sig_term)
131
141
  except OSError as err:
132
142
  _ = err
133
143
  for p in [pid] + descendant_pids:
134
144
  try:
135
- os.kill(p, signal.SIGTERM)
145
+ os.kill(p, sig_term)
136
146
  except OSError as err:
137
147
  _ = err
138
148
 
@@ -159,12 +169,12 @@ def kill_process_tree(pid: int, timeout: float = 2.0) -> bool:
159
169
  # Stage 2: Forceful SIGKILL to eradicate all remaining processes
160
170
  for p in descendant_pids + [pid]:
161
171
  try:
162
- os.kill(p, signal.SIGKILL)
172
+ os.kill(p, sig_kill)
163
173
  except OSError as err:
164
174
  _ = err
165
175
  if pgid is not None:
166
176
  try:
167
- os.killpg(pgid, signal.SIGKILL)
177
+ os.killpg(pgid, sig_kill)
168
178
  except OSError as err:
169
179
  _ = err
170
180
  try:
@@ -1348,7 +1348,7 @@ def _build_target_translations(
1348
1348
  "th_step_status": "Trạng Thái",
1349
1349
  "th_step_details": "Chi Tiết Kỹ Thuật (OTel & AST)",
1350
1350
 
1351
- "footer_text": "Báo cáo được khởi tạo tự động bởi Synapse-Hub v3.8.5 • Bản quyền © Thế Vị (@TeeVee98) • Chuẩn Clean POM & Kiểm Thử Tự Chủ",
1351
+ "footer_text": "Báo cáo được khởi tạo tự động bởi Synapse-Hub v3.9.1 • Bản quyền © Thế Vị (@TeeVee98) • Chuẩn Clean POM & Kiểm Thử Tự Chủ",
1352
1352
  }
1353
1353
 
1354
1354
  translations_en = {
@@ -1426,7 +1426,7 @@ def _build_target_translations(
1426
1426
  "th_step_status": "Status",
1427
1427
  "th_step_details": "Technical Details (OTel & AST)",
1428
1428
 
1429
- "footer_text": "Generated automatically by Synapse-Hub v3.8.5 • Copyright © Thế Vị (@TeeVee98) • Clean POM & Autonomous Testing",
1429
+ "footer_text": "Generated automatically by Synapse-Hub v3.9.1 • Copyright © Thế Vị (@TeeVee98) • Clean POM & Autonomous Testing",
1430
1430
  }
1431
1431
 
1432
1432
  _inject_gate_translations(translations_vi, translations_en, gates)
@@ -1915,7 +1915,7 @@ def _build_hub_translations(
1915
1915
  """Builds bilingual dictionaries for Hub Dashboard."""
1916
1916
  translations_vi = {
1917
1917
  "header_title": "Bảng Điều Hành Chất Lượng Doanh Nghiệp",
1918
- "header_subtitle": "Synapse-Hub v3.8.5 • Hệ Sinh Thái Kiểm Thử AI Agent Tự Chủ",
1918
+ "header_subtitle": "Synapse-Hub v3.9.1 • Hệ Sinh Thái Kiểm Thử AI Agent Tự Chủ",
1919
1919
  "nav_welcome": "Giới Thiệu",
1920
1920
  "meta_mode": "🏷️ Chế độ: <strong>HỆ SINH THÁI QA HUB</strong>",
1921
1921
  "meta_gen": f"🕒 Khởi tạo: <strong>{now_str}</strong>",
@@ -1985,12 +1985,12 @@ def _build_hub_translations(
1985
1985
  "th_sk_ver": "Phiên Bản",
1986
1986
  "th_sk_cap": "Khả Năng Nghiệp Vụ Cốt Lõi",
1987
1987
 
1988
- "footer_text": "Bảng Điều Hành Chất Lượng Doanh Nghiệp &bull; Synapse-Hub v3.8.5 &bull; Bản quyền &copy; Thế Vị (@TeeVee98) &bull; Hệ Thống Kiểm Thử AI Agent Tự Chủ",
1988
+ "footer_text": "Bảng Điều Hành Chất Lượng Doanh Nghiệp &bull; Synapse-Hub v3.9.1 &bull; Bản quyền &copy; Thế Vị (@TeeVee98) &bull; Hệ Thống Kiểm Thử AI Agent Tự Chủ",
1989
1989
  }
1990
1990
 
1991
1991
  translations_en = {
1992
1992
  "header_title": "Enterprise QA Executive Dashboard",
1993
- "header_subtitle": "Synapse-Hub v3.8.5 &bull; Autonomous AI Agent Testing Ecosystem",
1993
+ "header_subtitle": "Synapse-Hub v3.9.1 &bull; Autonomous AI Agent Testing Ecosystem",
1994
1994
  "nav_welcome": "Welcome",
1995
1995
  "meta_mode": "🏷️ Mode: <strong>QA HUB ECOSYSTEM</strong>",
1996
1996
  "meta_gen": f"🕒 Generated: <strong>{now_str}</strong>",
@@ -2060,7 +2060,7 @@ def _build_hub_translations(
2060
2060
  "th_sk_ver": "Version",
2061
2061
  "th_sk_cap": "Core Capabilities",
2062
2062
 
2063
- "footer_text": "Enterprise QA Executive Dashboard &bull; Synapse-Hub v3.8.5 &bull; Copyright &copy; Thế Vị (@TeeVee98) &bull; Autonomous AI Agent Testing Ecosystem",
2063
+ "footer_text": "Enterprise QA Executive Dashboard &bull; Synapse-Hub v3.9.1 &bull; Copyright &copy; Thế Vị (@TeeVee98) &bull; Autonomous AI Agent Testing Ecosystem",
2064
2064
  }
2065
2065
 
2066
2066
  _inject_gate_translations(translations_vi, translations_en, gates)
@@ -0,0 +1,220 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ tools/diagram_architect.py — Standalone Self-Contained SVG & HTML Diagram Builder
5
+ Inspired by Cathryn Lavery's diagram-design standard.
6
+ Generates fully self-contained SVG and HTML architectural diagrams
7
+ with zero Mermaid dependencies, guaranteed text contrast, and mathematical containment.
8
+ 100% UTF-8 No BOM.
9
+ """
10
+
11
+ import sys
12
+ import os
13
+ import argparse
14
+ from typing import Dict, Any
15
+
16
+ # Enforce UTF-8 stdout encoding
17
+ if hasattr(sys.stdout, "reconfigure"):
18
+ try:
19
+ sys.stdout.reconfigure(encoding="utf-8")
20
+ sys.stderr.reconfigure(encoding="utf-8")
21
+ except Exception:
22
+ pass
23
+
24
+ def generate_fsm_diagram() -> str:
25
+ """Generates the 5-Stage FSM flow diagram of Synapse Hub."""
26
+ svg = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 240" width="100%" height="240" style="background:#0f172a; border-radius:12px; font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
27
+ <defs>
28
+ <linearGradient id="cyan-grad" x1="0%" y1="0%" x2="100%" y2="100%">
29
+ <stop offset="0%" stop-color="#06b6d4"/>
30
+ <stop offset="100%" stop-color="#3b82f6"/>
31
+ </linearGradient>
32
+ <linearGradient id="purple-grad" x1="0%" y1="0%" x2="100%" y2="100%">
33
+ <stop offset="0%" stop-color="#8b5cf6"/>
34
+ <stop offset="100%" stop-color="#ec4899"/>
35
+ </linearGradient>
36
+ <linearGradient id="emerald-grad" x1="0%" y1="0%" x2="100%" y2="100%">
37
+ <stop offset="0%" stop-color="#10b981"/>
38
+ <stop offset="100%" stop-color="#059669"/>
39
+ </linearGradient>
40
+ <marker id="arrow" viewBox="0 0 10 10" refX="6" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
41
+ <path d="M 0 1 L 8 5 L 0 9 z" fill="#64748b"/>
42
+ </marker>
43
+ </defs>
44
+
45
+ <!-- Connectors -->
46
+ <line x1="180" y1="120" x2="225" y2="120" stroke="#475569" stroke-width="2" marker-end="url(#arrow)"/>
47
+ <line x1="380" y1="120" x2="425" y2="120" stroke="#475569" stroke-width="2" marker-end="url(#arrow)"/>
48
+ <line x1="580" y1="120" x2="625" y2="120" stroke="#475569" stroke-width="2" marker-end="url(#arrow)"/>
49
+ <line x1="780" y1="120" x2="825" y2="120" stroke="#475569" stroke-width="2" marker-end="url(#arrow)"/>
50
+
51
+ <!-- Stage 1 -->
52
+ <g transform="translate(30, 60)">
53
+ <rect width="150" height="120" rx="10" fill="#1e293b" stroke="#06b6d4" stroke-width="2"/>
54
+ <rect width="150" height="28" rx="10" fill="#06b6d4"/>
55
+ <text x="75" y="19" text-anchor="middle" fill="#0f172a" font-size="12" font-weight="bold">STAGE 1: DISCOVERY</text>
56
+ <text x="75" y="60" text-anchor="middle" fill="#f8fafc" font-size="13" font-weight="600">test-designer</text>
57
+ <text x="75" y="80" text-anchor="middle" fill="#94a3b8" font-size="11">RBT Risk Matrices</text>
58
+ <text x="75" y="98" text-anchor="middle" fill="#38bdf8" font-size="11">Spec SDD / Gherkin</text>
59
+ </g>
60
+
61
+ <!-- Stage 2 -->
62
+ <g transform="translate(230, 60)">
63
+ <rect width="150" height="120" rx="10" fill="#1e293b" stroke="#3b82f6" stroke-width="2"/>
64
+ <rect width="150" height="28" rx="10" fill="#3b82f6"/>
65
+ <text x="75" y="19" text-anchor="middle" fill="#ffffff" font-size="12" font-weight="bold">STAGE 2: SYNTHESIS</text>
66
+ <text x="75" y="60" text-anchor="middle" fill="#f8fafc" font-size="13" font-weight="600">pom-crafter</text>
67
+ <text x="75" y="80" text-anchor="middle" fill="#94a3b8" font-size="11">Clean POM Classes</text>
68
+ <text x="75" y="98" text-anchor="middle" fill="#60a5fa" font-size="11">Zero Script Locators</text>
69
+ </g>
70
+
71
+ <!-- Stage 3 -->
72
+ <g transform="translate(430, 60)">
73
+ <rect width="150" height="120" rx="10" fill="#1e293b" stroke="#8b5cf6" stroke-width="2"/>
74
+ <rect width="150" height="28" rx="10" fill="#8b5cf6"/>
75
+ <text x="75" y="19" text-anchor="middle" fill="#ffffff" font-size="12" font-weight="bold">STAGE 3: EXECUTION</text>
76
+ <text x="75" y="60" text-anchor="middle" fill="#f8fafc" font-size="13" font-weight="600">test-runner</text>
77
+ <text x="75" y="80" text-anchor="middle" fill="#94a3b8" font-size="11">100% Pure Headless</text>
78
+ <text x="75" y="98" text-anchor="middle" fill="#c084fc" font-size="11">Parallel Worktrees</text>
79
+ </g>
80
+
81
+ <!-- Stage 4 -->
82
+ <g transform="translate(630, 60)">
83
+ <rect width="150" height="120" rx="10" fill="#1e293b" stroke="#f59e0b" stroke-width="2"/>
84
+ <rect width="150" height="28" rx="10" fill="#f59e0b"/>
85
+ <text x="75" y="19" text-anchor="middle" fill="#0f172a" font-size="12" font-weight="bold">STAGE 4: HEALING</text>
86
+ <text x="75" y="60" text-anchor="middle" fill="#f8fafc" font-size="13" font-weight="600">failure-analyst</text>
87
+ <text x="75" y="80" text-anchor="middle" fill="#94a3b8" font-size="11">AOM Diff Healing</text>
88
+ <text x="75" y="98" text-anchor="middle" fill="#fbbf24" font-size="11">Pinpoint RCA</text>
89
+ </g>
90
+
91
+ <!-- Stage 5 -->
92
+ <g transform="translate(830, 60)">
93
+ <rect width="150" height="120" rx="10" fill="#1e293b" stroke="#10b981" stroke-width="2"/>
94
+ <rect width="150" height="28" rx="10" fill="#10b981"/>
95
+ <text x="75" y="19" text-anchor="middle" fill="#0f172a" font-size="12" font-weight="bold">STAGE 5: DoD ACCEPT</text>
96
+ <text x="75" y="60" text-anchor="middle" fill="#f8fafc" font-size="13" font-weight="600">quality-gatekeeper</text>
97
+ <text x="75" y="80" text-anchor="middle" fill="#94a3b8" font-size="11">10 Quality Gates</text>
98
+ <text x="75" y="98" text-anchor="middle" fill="#34d399" font-size="11">Mutation >= 80%</text>
99
+ </g>
100
+
101
+ <!-- Title bar -->
102
+ <text x="500" y="32" text-anchor="middle" fill="#e2e8f0" font-size="15" font-weight="700" letter-spacing="1">SYNAPSE HUB — 5-STAGE AUTONOMOUS FSM ENGINE</text>
103
+ </svg>"""
104
+ return svg
105
+
106
+ def generate_clean_pom_diagram() -> str:
107
+ """Generates the Clean POM Flat Architecture diagram."""
108
+ svg = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 280" width="100%" height="280" style="background:#0b0f19; border-radius:12px; font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
109
+ <defs>
110
+ <marker id="pom-arrow" viewBox="0 0 10 10" refX="6" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
111
+ <path d="M 0 1 L 8 5 L 0 9 z" fill="#06b6d4"/>
112
+ </marker>
113
+ </defs>
114
+
115
+ <text x="450" y="35" text-anchor="middle" fill="#ffffff" font-size="16" font-weight="bold">CLEAN POM / FLAT ARCHITECTURE INVARIANT</text>
116
+
117
+ <!-- Box 1: Test Scripts -->
118
+ <g transform="translate(40, 70)">
119
+ <rect width="240" height="160" rx="8" fill="#131b2e" stroke="#ef4444" stroke-width="2"/>
120
+ <text x="120" y="35" text-anchor="middle" fill="#f87171" font-size="14" font-weight="bold">Test Scripts (tests/)</text>
121
+ <line x1="20" y1="50" x2="220" y2="50" stroke="#334155"/>
122
+ <text x="25" y="75" fill="#f8fafc" font-size="12">✅ Business actions only</text>
123
+ <text x="25" y="100" fill="#f8fafc" font-size="12">✅ loginPage.login(u, p)</text>
124
+ <text x="25" y="125" fill="#ef4444" font-size="12">❌ ZERO Raw XPaths / CSS</text>
125
+ <text x="25" y="145" fill="#ef4444" font-size="12">❌ ZERO findTestObject</text>
126
+ </g>
127
+
128
+ <!-- Arrow 1 -> 2 -->
129
+ <line x1="280" y1="150" x2="335" y2="150" stroke="#06b6d4" stroke-width="2" marker-end="url(#pom-arrow)"/>
130
+
131
+ <!-- Box 2: Page Classes -->
132
+ <g transform="translate(340, 70)">
133
+ <rect width="240" height="160" rx="8" fill="#131b2e" stroke="#06b6d4" stroke-width="2"/>
134
+ <text x="120" y="35" text-anchor="middle" fill="#22d3ee" font-size="14" font-weight="bold">Page Classes (pages/)</text>
135
+ <line x1="20" y1="50" x2="220" y2="50" stroke="#334155"/>
136
+ <text x="25" y="75" fill="#f8fafc" font-size="12">✅ Encapsulated Locators</text>
137
+ <text x="25" y="100" fill="#f8fafc" font-size="12">✅ extends BasePage</text>
138
+ <text x="25" y="125" fill="#f8fafc" font-size="12">✅ Semantic action methods</text>
139
+ <text x="25" y="145" fill="#f8fafc" font-size="12">✅ Smart Wait integration</text>
140
+ </g>
141
+
142
+ <!-- Arrow 2 -> 3 -->
143
+ <line x1="580" y1="150" x2="635" y2="150" stroke="#06b6d4" stroke-width="2" marker-end="url(#pom-arrow)"/>
144
+
145
+ <!-- Box 3: BasePage / Framework -->
146
+ <g transform="translate(640, 70)">
147
+ <rect width="220" height="160" rx="8" fill="#131b2e" stroke="#10b981" stroke-width="2"/>
148
+ <text x="110" y="35" text-anchor="middle" fill="#34d399" font-size="14" font-weight="bold">BasePage & Helpers</text>
149
+ <line x1="20" y1="50" x2="200" y2="50" stroke="#334155"/>
150
+ <text x="25" y="75" fill="#f8fafc" font-size="12">✅ uniqueCode("AUTO_")</text>
151
+ <text x="25" y="100" fill="#f8fafc" font-size="12">✅ Dynamic Smart Waits</text>
152
+ <text x="25" y="125" fill="#f8fafc" font-size="12">✅ Spinner detachment</text>
153
+ <text x="25" y="145" fill="#f8fafc" font-size="12">✅ 100% UTF-8 No BOM</text>
154
+ </g>
155
+ </svg>"""
156
+ return svg
157
+
158
+ def build_html_wrapper(svg_content: str, title: str = "Synapse Hub Architecture Diagram") -> str:
159
+ return f"""<!DOCTYPE html>
160
+ <html lang="en">
161
+ <head>
162
+ <meta charset="utf-8"/>
163
+ <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
164
+ <title>{title}</title>
165
+ <style>
166
+ body {{
167
+ margin: 0;
168
+ padding: 32px;
169
+ background: #020617;
170
+ color: #f8fafc;
171
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
172
+ display: flex;
173
+ flex-direction: column;
174
+ align-items: center;
175
+ }}
176
+ .diagram-container {{
177
+ max-width: 1040px;
178
+ width: 100%;
179
+ background: #0f172a;
180
+ border: 1px solid #1e293b;
181
+ border-radius: 16px;
182
+ padding: 24px;
183
+ box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5);
184
+ }}
185
+ </style>
186
+ </head>
187
+ <body>
188
+ <div class="diagram-container">
189
+ {svg_content}
190
+ </div>
191
+ </body>
192
+ </html>"""
193
+
194
+ def main():
195
+ parser = argparse.ArgumentParser(description="Generate self-contained standalone architectural diagrams.")
196
+ parser.add_argument("--type", choices=["fsm", "clean-pom"], default="fsm", help="Diagram type to generate.")
197
+ parser.add_argument("--output", "-o", help="Target output file path (.svg or .html).")
198
+ args = parser.parse_args()
199
+
200
+ if args.type == "fsm":
201
+ svg = generate_fsm_diagram()
202
+ title = "Synapse Hub — 5-Stage Autonomous FSM Engine"
203
+ else:
204
+ svg = generate_clean_pom_diagram()
205
+ title = "Synapse Hub — Clean POM Architecture"
206
+
207
+ if args.output:
208
+ if args.output.endswith(".html"):
209
+ content = build_html_wrapper(svg, title)
210
+ else:
211
+ content = svg
212
+ os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
213
+ with open(args.output, "w", encoding="utf-8") as f:
214
+ f.write(content)
215
+ print(f"[DIAGRAM ARCHITECT] Successfully exported {args.type} diagram to {args.output}")
216
+ else:
217
+ print(svg)
218
+
219
+ if __name__ == "__main__":
220
+ main()
@@ -119,10 +119,39 @@ def distill(log_text, max_lines=40):
119
119
  # Public alias for MCP server compatibility
120
120
  distill_log_content = distill
121
121
 
122
+ def shrink_tokens(text: str, max_chars_per_line: int = 120) -> str:
123
+ """
124
+ Caveman / shrink compression: drops verbose metadata, collapses repetitive traces,
125
+ and truncates stack noise while preserving 100% error names, line locations,
126
+ and assertion mismatches (Julius Brussee caveman/shrink pattern).
127
+ Achieves 33-65% token drop.
128
+ """
129
+ lines = text.splitlines()
130
+ shrunk_lines = []
131
+ seen_signatures = set()
132
+
133
+ for line in lines:
134
+ cleaned = re.sub(r'\s+', ' ', line).strip()
135
+ if not cleaned:
136
+ continue
137
+ # Deduplicate repeated identical trace lines
138
+ if cleaned.startswith("at ") or cleaned.startswith("File "):
139
+ sig = cleaned[:60]
140
+ if sig in seen_signatures:
141
+ continue
142
+ seen_signatures.add(sig)
143
+ # Drop excessive UUID/hex hash strings
144
+ cleaned = re.sub(r'\b[0-9a-f]{16,64}\b', '<hash>', cleaned, flags=re.IGNORECASE)
145
+ if len(cleaned) > max_chars_per_line:
146
+ cleaned = cleaned[:max_chars_per_line] + "..."
147
+ shrunk_lines.append(cleaned)
148
+ return "\n".join(shrunk_lines)
149
+
122
150
  def main():
123
151
  parser = argparse.ArgumentParser(description="Distill terminal execution logs into high-signal failure blocks.")
124
152
  parser.add_argument("--file", "-f", help="Path to raw log file (reads from stdin if omitted).")
125
153
  parser.add_argument("--save-raw", "-s", default=None, help="Path to preserve raw log (omitted by default to prevent hub pollution).")
154
+ parser.add_argument("--shrink", action="store_true", help="Apply caveman/shrink token compression (33-65%% token drop).")
126
155
  args = parser.parse_args()
127
156
 
128
157
  if args.file:
@@ -147,6 +176,8 @@ def main():
147
176
  sys.stderr.write(f"Warning: Could not save raw log: {err}\n")
148
177
 
149
178
  summary = distill(log_text)
179
+ if args.shrink:
180
+ summary = shrink_tokens(summary)
150
181
  print(summary)
151
182
  if args.save_raw and os.path.exists(args.save_raw):
152
183
  print(f"[Full raw log saved to file://{os.path.abspath(args.save_raw)}]")
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ tools/git_worktree_manager.py — Ephemeral Git Worktree Manager for Subagents
5
+ Inspired by Jesse Vincent (obra/superpowers) and Shan Rais subagent isolation standard.
6
+ Allocates, inspects, and cleans up isolated worktrees so concurrent subagents
7
+ do not pollute or conflict with the main working directory.
8
+ 100% UTF-8 No BOM.
9
+ """
10
+
11
+ import sys
12
+ import os
13
+ import re
14
+ import subprocess
15
+ import argparse
16
+ import json
17
+ import time
18
+ from typing import Dict, List, Any, Optional
19
+
20
+ # Enforce UTF-8 stdout encoding
21
+ if hasattr(sys.stdout, "reconfigure"):
22
+ try:
23
+ sys.stdout.reconfigure(encoding="utf-8")
24
+ sys.stderr.reconfigure(encoding="utf-8")
25
+ except Exception:
26
+ pass
27
+
28
+ WORKTREES_ROOT = os.path.join(".synapse", "worktrees")
29
+
30
+ def run_git(args: List[str], cwd: Optional[str] = None) -> subprocess.CompletedProcess:
31
+ return subprocess.run(
32
+ ["git"] + args,
33
+ cwd=cwd or os.getcwd(),
34
+ capture_output=True,
35
+ text=True,
36
+ encoding="utf-8",
37
+ errors="replace"
38
+ )
39
+
40
+ class WorktreeManager:
41
+ def __init__(self, base_dir: Optional[str] = None):
42
+ self.base_dir = base_dir or os.path.join(os.getcwd(), WORKTREES_ROOT)
43
+
44
+ def list_worktrees(self) -> List[Dict[str, str]]:
45
+ res = run_git(["worktree", "list", "--porcelain"])
46
+ if res.returncode != 0:
47
+ return []
48
+
49
+ worktrees = []
50
+ current: Dict[str, str] = {}
51
+ for line in res.stdout.splitlines():
52
+ line = line.strip()
53
+ if not line:
54
+ if current:
55
+ worktrees.append(current)
56
+ current = {}
57
+ elif line.startswith("worktree "):
58
+ current["path"] = line[len("worktree "):].strip()
59
+ elif line.startswith("branch "):
60
+ current["branch"] = line[len("branch "):].strip()
61
+ elif line.startswith("HEAD "):
62
+ current["head"] = line[len("HEAD "):].strip()
63
+ if current:
64
+ worktrees.append(current)
65
+ return worktrees
66
+
67
+ def create_worktree(self, agent_id: str, branch_name: Optional[str] = None) -> Dict[str, Any]:
68
+ os.makedirs(self.base_dir, exist_ok=True)
69
+ timestamp = int(time.time())
70
+ clean_agent_id = re.sub(r'[^a-zA-Z0-9_.-]', '-', agent_id)
71
+ branch = branch_name or f"subagent/{clean_agent_id}-{timestamp}"
72
+ target_path = os.path.abspath(os.path.join(self.base_dir, f"{clean_agent_id}-{timestamp}"))
73
+
74
+ res = run_git(["worktree", "add", "-b", branch, target_path, "HEAD"])
75
+ if res.returncode != 0:
76
+ # Fallback if branch already exists
77
+ res = run_git(["worktree", "add", target_path, "HEAD"])
78
+ if res.returncode != 0:
79
+ return {
80
+ "success": False,
81
+ "error": res.stderr.strip() or "Failed to create worktree",
82
+ "path": target_path
83
+ }
84
+
85
+ return {
86
+ "success": True,
87
+ "agent_id": agent_id,
88
+ "worktree_path": target_path,
89
+ "branch": branch,
90
+ "created_at": timestamp
91
+ }
92
+
93
+ def remove_worktree(self, worktree_path: str, delete_branch: bool = True) -> Dict[str, Any]:
94
+ # Determine branch before removal
95
+ branch_to_delete = None
96
+ if delete_branch:
97
+ for wt in self.list_worktrees():
98
+ if os.path.abspath(wt.get("path", "")) == os.path.abspath(worktree_path):
99
+ branch_ref = wt.get("branch", "")
100
+ if branch_ref.startswith("refs/heads/"):
101
+ branch_to_delete = branch_ref[len("refs/heads/"):]
102
+ elif branch_ref:
103
+ branch_to_delete = branch_ref
104
+ break
105
+
106
+ res = run_git(["worktree", "remove", "--force", worktree_path])
107
+ success = res.returncode == 0
108
+
109
+ # Run git worktree prune
110
+ run_git(["worktree", "prune"])
111
+
112
+ # Clean up ephemeral subagent branch if requested
113
+ if success and delete_branch and branch_to_delete and branch_to_delete.startswith("subagent/"):
114
+ run_git(["branch", "-D", branch_to_delete])
115
+
116
+ return {
117
+ "success": success,
118
+ "path": worktree_path,
119
+ "deleted_branch": branch_to_delete if (success and delete_branch) else None,
120
+ "error": res.stderr.strip() if not success else None
121
+ }
122
+
123
+ def prune_stale(self) -> Dict[str, Any]:
124
+ res = run_git(["worktree", "prune", "-v"])
125
+ return {
126
+ "success": res.returncode == 0,
127
+ "output": res.stdout.strip()
128
+ }
129
+
130
+ def main():
131
+ parser = argparse.ArgumentParser(description="Manage ephemeral git worktrees for subagent isolation.")
132
+ parser.add_argument("action", choices=["list", "create", "remove", "prune"], help="Action to execute.")
133
+ parser.add_argument("--agent-id", help="Subagent identifier for creation.")
134
+ parser.add_argument("--path", help="Worktree path for removal.")
135
+ parser.add_argument("--json", action="store_true", help="Output JSON format.")
136
+ args = parser.parse_args()
137
+
138
+ manager = WorktreeManager()
139
+
140
+ if args.action == "list":
141
+ items = manager.list_worktrees()
142
+ if args.json:
143
+ print(json.dumps(items, indent=2))
144
+ else:
145
+ print(f"[WORKTREE MANAGER] Active Worktrees ({len(items)}):")
146
+ for it in items:
147
+ print(f" - {it.get('path')} ({it.get('branch', 'detached')})")
148
+
149
+ elif args.action == "create":
150
+ if not args.agent_id:
151
+ print("Error: --agent-id is required for create.", file=sys.stderr)
152
+ sys.exit(1)
153
+ res = manager.create_worktree(args.agent_id)
154
+ if args.json:
155
+ print(json.dumps(res, indent=2))
156
+ else:
157
+ if res["success"]:
158
+ print(f"[WORKTREE CREATED] Path: {res['worktree_path']} (Branch: {res['branch']})")
159
+ else:
160
+ print(f"[ERROR] Failed to create worktree: {res.get('error')}", file=sys.stderr)
161
+ sys.exit(1)
162
+
163
+ elif args.action == "remove":
164
+ if not args.path:
165
+ print("Error: --path is required for remove.", file=sys.stderr)
166
+ sys.exit(1)
167
+ res = manager.remove_worktree(args.path)
168
+ if args.json:
169
+ print(json.dumps(res, indent=2))
170
+ else:
171
+ if res["success"]:
172
+ print(f"[WORKTREE REMOVED] {res['path']} - Deleted branch: {res.get('deleted_branch')}")
173
+ else:
174
+ print(f"[ERROR] Failed to remove worktree: {res.get('error')}", file=sys.stderr)
175
+ sys.exit(1)
176
+
177
+ elif args.action == "prune":
178
+ res = manager.prune_stale()
179
+ if args.json:
180
+ print(json.dumps(res, indent=2))
181
+ else:
182
+ print(f"[WORKTREE PRUNED] Output: {res['output'] or 'Zero stale worktrees.'}")
183
+
184
+ if __name__ == "__main__":
185
+ main()
@@ -176,6 +176,10 @@ CLICHE_PHRASES: List[Tuple[str, str]] = [
176
176
  (r"\breflects a broader trend\b", "say 'shows a trend'"),
177
177
  (r"\bmarks a significant shift\b", "say 'marks a shift'"),
178
178
  (r"\bin today's ever-evolving landscape\b", "say 'today'"),
179
+ (r"\brest assured\b", "state verifiable evidence instead"),
180
+ (r"\bwithout further ado\b", "dive directly into technical content"),
181
+ (r"\bi hope this helps\b", "omit conversational fluff"),
182
+ (r"\bhere is the updated code\b", "deliver code directly"),
179
183
  ]
180
184
 
181
185
  # Words that are fine in isolation, but suspicious when piled up (>= 3 times)