@teevee98/synapse-hub 3.9.1 → 3.10.0

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.
@@ -10,7 +10,7 @@ When mounted alongside a target project and the user requests *"push"*, *"push c
10
10
 
11
11
  > ⚠️ **Scope Isolation Invariant:** Only push to the target project. Absolutely never push or stage changes to the Hub repo (`Synapse-Hub` / `agent-skills`) unless the user explicitly requests *"push hub"* or *"push synapse-hub"*.
12
12
 
13
- 1. **Pre-Push Gate (DoD Verification):** Run verification before committing (`python tools/verify_all.py` or test runner). Never push unverified code or failing tests.
13
+ 1. **Pre-Push Gate (DoD Verification):** Run verification before committing (if `tools/verify_all.py` exists, execute it; otherwise, execute target project native test runner `npm test`, `pytest`, `mvn test`). Never push unverified code or failing tests.
14
14
  2. **Selective Staging:** Stage specifically changed project files (`git add <files>`). Never stage temporary artifacts (`Screenshots/`, `Reports/`, `*.log`). Avoid blind `git add -A` on target projects.
15
15
  3. **Conventional Commit:** Create structured semantic commits: `git commit -m "<type>(<scope>): <summary>"`.
16
16
  4. **User Confirmation Required:** Always ask user confirmation before running `git push origin <branch>`.
@@ -1,10 +1,12 @@
1
1
  ---
2
- trigger: always_on
3
- description: Mandatory rules for Autonomous Multi-Agent Swarm, Pure Headless Playwright Live interaction (1920x1080), and Zero-Second Auth.
2
+ trigger: on_demand
3
+ description: Rules for Autonomous Multi-Agent Swarm, Pure Headless Playwright Live interaction (1920x1080), and Zero-Second Auth. Activated strictly when Web Playwright or browser automation suites are mounted.
4
4
  ---
5
5
 
6
6
  # Mandatory Playwright Live Interaction & Swarm Protocols
7
7
 
8
+ > ⚠️ **Contextual Activation Scope:** This rule is activated ONLY when `playwright.config.*` exists or when running Web / Browser E2E automation. For pure API, Mobile Appium, or Performance tests, strictly adhere to their respective rules (`stack-auto-router.md`, `mobile_appium_rules.md`, `performance_testing_rules.md`) and do not apply browser session/viewport constraints.
9
+
8
10
  1. **Autonomous Swarm FSM (5 Stages):**
9
11
  - Main AI acts as **Lead QA Orchestrator**, coordinating specialized subagents:
10
12
  * **`test-designer`:** Transforms requirements into risk-based test matrices (AI-RBT), 15-field validation checklists, and 12-column Excel test suites.
@@ -1,43 +1,18 @@
1
- ---
2
- trigger: on_demand
3
- description: Mobile Automation standards, Screen Object Model (SOM), and Appium driver invariants for iOS/Android suites.
4
- status: upcoming_extension
5
- ---
1
+ # Mobile Automation Rules — Appium iOS & Android (Full Standard)
6
2
 
7
- # Mobile Automation Standards & Appium Rules (Enterprise Extension)
3
+ > Nâng cấp hoàn chỉnh từ bản `upcoming_extension` trong Synapse-Hub cho UIAutomator2 (Android) và XCUITest (iOS).
8
4
 
9
- > **Status:** Upcoming extension module for Appium / Mobile SOM architectures. Activated when mobile drivers or native iOS/Android test suites are mounted.
10
- > **Scope:** Applies to Mobile Automation using Appium, UIAutomator2 (Android), and XCUITest (iOS).
11
- > **Objective:** Deliver resilient, independent, flake-free mobile suites supporting parallel multi-device execution.
5
+ ## 1. Screen Object Model (SOM)
6
+ * Đóng gói 100% locator và thao tác màn hình vào `screens/` (tối đa 1 `BaseScreen`). Tuyệt đối không viết selector trực tiếp trong `tests/`.
7
+ * Tách biệt locator theo nền tảng khi cây UI khác nhau (`locators/ios/` và `locators/android/`).
12
8
 
13
- ---
9
+ ## 2. Mobile Locator Hierarchy (Strict)
10
+ 1. **Accessibility ID (Ưu tiên 1 — Đa nền tảng):** `~accessibilityId` (iOS `accessibilityIdentifier` / Android `content-desc`).
11
+ 2. **iOS Native (Ưu tiên 2 cho iOS):** `-ios predicate string` (vd: `label == "Login" AND visible == 1`) hoặc `-ios class chain`.
12
+ 3. **Android Native (Ưu tiên 3 cho Android):** `id` / `resource-id` (`new UiSelector().resourceId(...)`).
13
+ 4. **Cấm tuyệt đối:** XPath chứa chỉ số index (`//XCUIElementTypeCell[3]`, `//android.widget.TextView[2]`) và tọa độ cứng `tap(x, y)`.
14
14
 
15
- ## 1. Native Locator Priority Hierarchy
16
- 1. **Accessibility ID / Content-Desc** (Top priority, cross-platform): `driver.findElement(AppiumBy.accessibilityId("btn_login"))`
17
- 2. **Resource-ID (Android Native):** `driver.findElement(AppiumBy.id("com.app:id/username"))`
18
- 3. **iOS Predicate String (iOS Native):** `driver.findElement(AppiumBy.iOSNsPredicateString("label == 'Sign In' AND visible == 1"))`
19
- 4. **iOS Class Chain:** `driver.findElement(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`label == 'Submit'`]"))`
20
- 5. **Dynamic XPath (Last Resort):** Relative XPath with attributes only. Absolute structural XPath is **FORBIDDEN**.
21
-
22
- ---
23
-
24
- ## 2. Strict Anti-Patterns & Prohibitions
25
- - ❌ **FORBIDDEN:** Absolute hierarchy XPath (e.g., `//android.widget.FrameLayout[1]/.../Button[1]`).
26
- - ❌ **FORBIDDEN:** Static delays (`Thread.sleep()`).
27
- - ❌ **FORBIDDEN:** Interacting with off-screen elements without scrolling into view first.
28
- - ❌ **FORBIDDEN:** Hardcoded device identifiers (UDID, device name must come from environment/profiles).
29
-
30
- ---
31
-
32
- ## 3. Screen Object Model (SOM) & Synchronization
33
- - Screen classes end with `Screen` suffix (e.g., `LoginScreen.java`) extending `BaseScreen`.
34
- - Encapsulate locators in Screen classes; test scripts call business actions only.
35
- - **Smart Waits:** Always use `WebDriverWait` with explicit `Duration.ofSeconds(N)`.
36
- - **Smart Scroll:** Use `UiScrollable(...).scrollIntoView(...)` or native iOS scroll gestures.
37
-
38
- ---
39
-
40
- ## 4. Mobile Lifecycle & Driver Invariants
41
- - **Permissions:** Auto-grant system permissions via capabilities (`autoGrantPermissions: true`).
42
- - **Resilience:** Validate backgrounding (`driver.runAppInBackground(...)`) and hide virtual keyboard before actions.
43
- - **Driver Isolation:** Screen classes speak intent; platform drivers (UIAutomator2/XCUITest) encapsulate mechanics. Capabilities reside in profiles, never in scripts. Always explicitly quit sessions.
15
+ ## 3. Stability, Alerts & Context Switching
16
+ * **Capabilities:** Khai báo rõ `automationName`, `newCommandTimeout`, và chiến lược `noReset`/`fullReset` để đảm bảo test độc lập.
17
+ * **System Alerts & Keyboard:** Chủ động xử lý hộp thoại quyền hệ điều hành (Location, Camera, Notification) và gọi `hideKeyboard()` trước khi tương tác phần tử bị che.
18
+ * **Smart Scroll & WebView:** Dùng cuộn động có điều kiện dừng khi tìm phần tử ngoài màn hình. Khi thao tác Hybrid/WebView, kiểm tra `getContexts()` và quay lại `NATIVE_APP` ngay sau khi xong.
@@ -0,0 +1,24 @@
1
+ # Security & Pentest Testing Invariants (5-Layer Safety Gate)
2
+
3
+ > Rule chốt chặn bắt buộc khi thực thi `security-dast-sentinel` hoặc `skillspector-security-guard` trong Synapse-Hub.
4
+
5
+ ## 1. Layer 1 — Scope & Production Blocklist (Allowlist Gate)
6
+ * Mọi script DAST/Fuzzing/Pentest (Burp Suite, OWASP ZAP, Nuclei, Python) bắt buộc đọc `TARGET_BASE_URL` và kiểm tra khớp với `ALLOWED_PENTEST_HOSTS` trong cấu hình môi trường.
7
+ * **Từ chối thực thi ngay** nếu URL mục tiêu thuộc môi trường Production (`prod`, tên miền chính thức chưa nằm trong `ALLOWED_PENTEST_HOSTS`).
8
+ * Bắt buộc hỏi xác nhận người dùng trước khi chạy bất kỳ lệnh quét chủ động (Active Scan / Fuzzing) nào.
9
+
10
+ ## 2. Layer 2 — Rate-Limit & Concurrency Cap
11
+ * Giới hạn cứng tốc độ gửi request trong script tự động: tối đa `5–10 req/s` và tối đa `3–5` luồng song song (trừ bài test Rate-Limit có xác nhận riêng).
12
+ * Bắt buộc đặt `timeout <= 10s` cho mọi HTTP request và tự ngắt script nếu gặp `5xx` hoặc `429` liên tiếp vượt ngưỡng.
13
+
14
+ ## 3. Layer 3 — Non-Destructive PoC & Account Isolation
15
+ * Chỉ dùng payload chứng minh lỗ hổng vô hại (SQLi đọc an toàn, canary string, time-delay nhỏ). Cấm tuyệt đối payload xóa/sửa dữ liệu (`DROP`, `DELETE`, `UPDATE` không điều kiện) hoặc gây DoS.
16
+ * Kiểm thử phân quyền chéo (BOLA/IDOR) chỉ được sử dụng cặp tài khoản test cô lập (`PENTEST_USER_A`, `PENTEST_USER_B`), không chạm dữ liệu người dùng thật.
17
+
18
+ ## 4. Layer 4 — Script Secret Protection & SAST Check
19
+ * Cấm hardcode Token, Session Cookie, API Key mục tiêu trong script pentest; phải nạp từ `.env` (đã khai báo trong `.gitignore`).
20
+ * Kết hợp rà soát nhanh lỗ hổng cấu hình tĩnh (`CORS *`, thiếu CSP/HSTS, lộ secret) trên mã nguồn nếu có quyền đọc repo.
21
+
22
+ ## 5. Layer 5 — Sanitized Evidence Standard
23
+ * Mọi lỗ hổng báo cáo phải kèm đủ: Severity (Critical/High/Medium/Low), cặp HTTP Request/Response (hoặc lệnh `curl`) tái hiện được ngay, và hướng dẫn vá lỗi.
24
+ * Bắt buộc che mờ (mask) JWT, Cookie, Password, PII trước khi ghi log hoặc xuất báo cáo.
@@ -0,0 +1,17 @@
1
+ # Context-Aware Stack Router & Token-Minimal Loader
2
+
3
+ > Bổ sung vào `.agents/rules/` của Synapse-Hub để giảm tối đa tiêu thụ token và dùng chung được cho mọi dự án.
4
+
5
+ ## 1. Lazy-Loading Rule & Skill (Chỉ nạp thứ dự án cần)
6
+ Khi bắt đầu phiên làm việc, AI Agent **chỉ quét thư mục gốc tối đa 2 cấp** và chỉ đọc đúng nhóm rule/skill khớp với dự án hiện tại (KHÔNG nạp toàn bộ 53 skill hay rule của nền tảng khác):
7
+
8
+ * **Web / API (`playwright.config.*`, `cypress.config.*`, `openapi.*`, `pytest`, `jest`):** Chỉ nạp `mandatory-playwright-live.md` (nếu dùng Playwright) + `clean-pom-crafter` + `api-network-mocking-interception`.
9
+ * **Mobile (`appium`, `*.xcodeproj`, `build.gradle`):** Chỉ nạp `mobile_appium_rules.md` + `clean-pom-crafter` (theo chuẩn SOM). Bỏ qua `mandatory-playwright-live.md`.
10
+ * **Performance (`k6`, `*.jmx`, `locustfile.py`):** Chỉ nạp `performance_testing_rules.md` + `backend-load-and-stress-patterns`.
11
+ * **Security (`burp`, `zap`, `nuclei`, pentest/DAST):** Chỉ nạp `security_testing_rules.md` + `security-dast-sentinel` + `skillspector-security-guard`.
12
+
13
+ ## 2. Adaptive Verification (Fast Mode vs Full Gate)
14
+ * **Fast Mode (Sửa nhanh / viết 1–2 test case):** Kiểm tra tĩnh (0 sleep cứng, 0 secret, có `assert`) và chạy lệnh test gốc cho **đúng tệp vừa sửa** đạt `Exit Code 0`.
15
+ * **Full Gate (Chốt PR / Release):**
16
+ * Nếu dự án có `tools/verify_all.py` (môi trường Synapse-Hub đầy đủ): chạy `python3 tools/verify_all.py`.
17
+ * Nếu là dự án bên ngoài không có `tools/verify_all.py`: chạy toàn bộ test suite bằng lệnh gốc trong `package.json` / `pyproject.toml` / `Makefile` và quét rò rỉ secret.
@@ -9,14 +9,15 @@ description: Enforce rigorous engineering discipline, systematic debugging witho
9
9
  - **Evidence Before Action:** Never modify code on assumption. Ground every fix in concrete evidence: failing line & stack trace, screenshot (`Screenshots/FAILED_*.png`), or live DOM state.
10
10
  - **Surgical Code Preservation:** Touch only the minimal lines required. Never rewrite working methods speculatively.
11
11
 
12
- ## 2. Verification-First & Definition of Done
13
- - **Mandatory Verification Gate:** Any claim that a task, fix, or refactoring is complete MUST be verified by running:
14
- ```bash
15
- python3 tools/verify_all.py
16
- ```
17
- All 10 Quality Gates must return `PASS`. If any gate fails, the task is NOT complete.
18
- - **Targeted Re-Test:** Check impacted test cases via `python3 tools/test_impact.py --git-diff`.
19
- - **Sync Knowledge & Artifacts:** Run `python3 tools/repo_map.py` if Page Classes or helpers change; run `graphify update .` if `graphify-out/` exists.
12
+ ## 2. Verification-First & Definition of Done (Adaptive)
13
+ - **Fast-Track (Quick Fixes):**
14
+ - **Applicability:** Changes under 15 lines of code, UI locator/selector updates, adding 1 single test case, or trivial doc/comment fixes.
15
+ - **Validation:** Perform static checks (0 static sleeps, 0 leaked credentials, contains explicit assertions) and run test suite for the **impacted file only** with exit code 0. Bypasses 10 Quality Gates and mutation testing.
16
+ - **Full-Gate (Major Features, Refactoring & Release):**
17
+ - **In Hub Repository / Equipped Target (with `tools/`):** Run `python3 tools/verify_all.py`. All 10 Quality Gates must return `PASS`.
18
+ - **In External Target Projects (without `tools/`):** Graceful fallback: run native test command defined in project (`npm test`, `pytest`, `mvn test`) and verify zero secret leaks. Never invoke missing `tools/` scripts.
19
+ - **Targeted Re-Test:** Check impacted test cases via native runner or `python3 tools/test_impact.py --git-diff` (if `tools/` exists).
20
+ - **Sync Knowledge & Artifacts:** Run `python3 tools/repo_map.py` if `tools/repo_map.py` exists; run `graphify update .` if `graphify-out/` exists.
20
21
 
21
22
  ## 3. Situational Tool Autonomy (Zero-Command Invariant)
22
23
  Autonomously trigger tools on-demand per `AGENTS.md` Section 3.4 (Setup: `setup_project.py`/`analyze_project.py`; Quality: `verify_all.py`/`infer_linter.py`/`micro_mutator.py`; Healing: `pinpoint_failure.py`/`auto_heal_reflexion.py`/`reversible_sandbox.py`; Context: `distill_log.py`/`safety_firewall.py`). Never expect user to memorize CLI syntax.
@@ -106,18 +106,23 @@ python tools/db_sandbox.py rollback-test --db-path "path/to/db.sqlite"
106
106
  ```
107
107
  *Guarantees zero leftover records: state is automatically rolled back to pristine baseline upon test completion.*
108
108
 
109
- ### 2. Ephemeral Snapshot & Instant Restore (< 0.5s)
109
+ ### 2. Ephemeral Snapshot & Instant Restore (< 0.5s) [DESTRUCTIVE]
110
+ > ⚠️ **Warning [DESTRUCTIVE]:** Database restore drops existing tables/objects and repopulates from snapshot (e.g. `pg_restore --clean --if-exists`). Zero-pollution guarantee is conditional upon isolated sandbox containers and valid snapshots; never execute against staging or production databases. Requires explicit `--confirm` (or setting `SYNAPSE_FORCE_RESTORE=1`).
110
111
  ```bash
111
112
  # Before test suite runs: capture pristine database baseline
112
113
  python tools/db_sandbox.py snapshot --id pristine_baseline
113
114
 
114
- # After suite execution: instantly restore clean database
115
- python tools/db_sandbox.py restore --id pristine_baseline
115
+ # After suite execution: restore clean database (requires explicit --confirm)
116
+ python tools/db_sandbox.py restore --id pristine_baseline --confirm
116
117
  ```
117
118
 
118
119
  ### 3. Taint Pollution Audit & Cascading Purge
119
- Scan all tables for orphan records carrying test prefixes (`AUTO_`, `TEST_`) and purge them cleanly:
120
+ Scan all tables for orphan records carrying test prefixes (`AUTO_`, `TEST_`). By default, `audit` runs in **safe dry-run preview** mode:
120
121
  ```bash
122
+ # Preview orphan records without deleting (safe default):
121
123
  python tools/db_sandbox.py audit
124
+
125
+ # Explicitly apply destructive purge:
126
+ python tools/db_sandbox.py audit --apply
122
127
  ```
123
128
 
package/AGENTS.md CHANGED
@@ -73,7 +73,8 @@ You are a lazy senior developer. The best code is the code never written. Solve
73
73
  - Optimizing assertions against surviving mutants -> Run `tools/textgrad_mutation_optimizer.py`.
74
74
  - User asks to push / release hub ("push lên", "push hub") -> Autonomously bump version based on changes via `tools/bump_version.py <patch|minor|major>` then run `tools/hub_publisher.py` (Push main + Tag + Release + Packages + NPM).
75
75
  - Task progress & compaction anchoring -> Autonomously run `tools/project_state.py`.
76
- - Before completing code tasks -> Autonomously run `tools/verify_all.py` (10 Quality Gates DoD).
76
+ - Before completing code tasks -> Autonomously run `tools/verify_all.py` (10 Quality Gates DoD). For quick fixes (< 15 lines of code), apply Fast-Track mode; for external target repos lacking `tools/`, gracefully fallback to native test runners (`npm test`, `pytest`, `mvn test`) per `.agents/rules/stack-auto-router.md` and `.agents/rules/systematic-debugging.md`.
77
+ - Context-aware stack routing -> Strictly adhere to `.agents/rules/stack-auto-router.md` (Web/Mobile/Perf/Security scope) and 5-layer pentest safety gate (`.agents/rules/security_testing_rules.md`).
77
78
 
78
79
  ---
79
80
 
package/README.en.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  > **Core Mission:** A standalone linter and guardrail engine (zero external dependencies for core engine & DoD gates) safeguarding automated test suites when AI writes code — Automatically catching "fake-pass" tests (0 assertions, tautologies), eliminating fixed sleeps, compressing 95% of CI/CD log noise, and enforcing Clean POM architecture.
8
8
  > **Author:** Thế Vị ([@TeeVee98](https://github.com/TeeVee98)) | **License:** MIT License
9
- > **Version:** `v3.9.1` | **Scale:** 53 Standardized QA Skills, 9 Specialized AI Agents, 10 DoD Quality Gates.
9
+ > **Version:** `v3.10.0` | **Scale:** 53 Standardized QA Skills, 9 Specialized AI Agents, 10 DoD Quality Gates.
10
10
 
11
11
  [![npm version](https://img.shields.io/npm/v/@teevee98/synapse-hub.svg?style=flat-square&color=blue)](https://www.npmjs.com/package/@teevee98/synapse-hub)
12
12
  [![node version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg?style=flat-square)](https://nodejs.org)
@@ -154,7 +154,7 @@ Every test code change must satisfy all 10 Quality Gates before pull request mer
154
154
  # Pre-commit hook (.pre-commit-config.yaml):
155
155
  repos:
156
156
  - repo: https://github.com/TeeVee98/Synapse-Hub
157
- rev: v3.9.1
157
+ rev: v3.10.0
158
158
  hooks:
159
159
  - id: synapse-lint
160
160
  - id: synapse-verify
package/README.md CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  > **Định vị cốt lõi:** Bộ Linter & Guardrails độc lập (zero external dependencies cho core engine & DoD gates) bảo vệ độ tin cậy của test suite khi AI viết code — Tự động bắt test "pass ảo" (0 assert, tautology), loại bỏ hoàn toàn sleep cố định, nén 95% log CI/CD, và chuẩn hóa cấu trúc Clean POM.
8
8
  > **Tác giả:** Thế Vị ([@TeeVee98](https://github.com/TeeVee98)) | **Giấy phép:** MIT License
9
- > **Phiên bản:** `v3.9.1` | **Quy mô:** 53 Kỹ năng QA, 9 Vai trò AI Agent, 10 Cổng kiểm định DoD.
9
+ > **Phiên bản:** `v3.10.0` | **Quy mô:** 53 Kỹ năng QA, 9 Vai trò AI Agent, 10 Cổng kiểm định DoD.
10
10
 
11
11
  [![npm version](https://img.shields.io/npm/v/@teevee98/synapse-hub.svg?style=flat-square&color=blue)](https://www.npmjs.com/package/@teevee98/synapse-hub)
12
12
  [![node version](https://img.shields.io/badge/node-%3E%3D18.0.0-brightgreen.svg?style=flat-square)](https://nodejs.org)
@@ -154,7 +154,7 @@ Mọi thay đổi mã nguồn kiểm thử đều được kiểm chứng qua 10
154
154
  # Pre-commit hook (.pre-commit-config.yaml):
155
155
  repos:
156
156
  - repo: https://github.com/TeeVee98/Synapse-Hub
157
- rev: v3.9.1
157
+ rev: v3.10.0
158
158
  hooks:
159
159
  - id: synapse-lint
160
160
  - id: synapse-verify
package/agentskills.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://agentskills.io/schema/v1.json",
3
3
  "name": "Synapse-Hub",
4
- "version": "3.9.1",
4
+ "version": "3.10.0",
5
5
  "description": "Enterprise QA & Test Automation AI Skills Ecosystem adhering to Clean POM Flat Architecture.",
6
6
  "author": "Thế Vị (@TeeVee98)",
7
7
  "repository": "https://github.com/TeeVee98/Synapse-Hub",
@@ -3,7 +3,7 @@
3
3
  [🇻🇳 Tiếng Việt](ARCHITECTURE.md) | [🇬🇧 English Edition](ARCHITECTURE.en.md)
4
4
 
5
5
  > **Scope:** Enterprise Multi-Agent QA Hub
6
- > **Version:** `3.9.1` | **Status:** Active / Production Standard
6
+ > **Version:** `3.10.0` | **Status:** Active / Production Standard
7
7
 
8
8
  ---
9
9
 
@@ -3,7 +3,7 @@
3
3
  [🇻🇳 Tiếng Việt](ARCHITECTURE.md) | [🇬🇧 English Edition](ARCHITECTURE.en.md)
4
4
 
5
5
  > **Phạm vi:** Enterprise Multi-Agent QA Hub
6
- > **Version:** `3.9.1` | **Trạng thái:** Hoạt động / Tiêu chuẩn Sản xuất
6
+ > **Version:** `3.10.0` | **Trạng thái:** Hoạt động / Tiêu chuẩn Sản xuất
7
7
  > **Tác giả:** Thế Vị (@TeeVee98) | **Giấy phép:** MIT License
8
8
 
9
9
  ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teevee98/synapse-hub",
3
- "version": "3.9.1",
3
+ "version": "3.10.0",
4
4
  "description": "Enterprise AI Agent Intelligence Hub & Autonomous Skill Network",
5
5
  "publishConfig": {
6
6
  "access": "public"
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "synapse-hub",
3
3
  "displayName": "Synapse Hub Enterprise QA",
4
- "version": "3.9.1",
4
+ "version": "3.10.0",
5
5
  "description": "Enterprise AI Agent Intelligence Hub & Autonomous Skill Network for Quality Engineering, Clean POM, and Automated Testing.",
6
6
  "author": {
7
7
  "name": "TeeVee98",
@@ -14,6 +14,23 @@ Write-Host "`n==================================================================
14
14
  Write-Host " SYNAPSE-HUB: ANTIGRAVITY GLOBAL PLUGIN 1-CLICK INSTALLER " -ForegroundColor Cyan
15
15
  Write-Host "======================================================================`n" -ForegroundColor Cyan
16
16
 
17
+ # Preflight Validation Guard
18
+ Write-Host "[Preflight] Checking repository integrity..." -ForegroundColor Yellow
19
+ $RequiredPaths = @(
20
+ "$RepoRoot\.agents\skills",
21
+ "$RepoRoot\.agents\agents",
22
+ "$RepoRoot\tools"
23
+ )
24
+ foreach ($p in $RequiredPaths) {
25
+ if (-not (Test-Path $p)) {
26
+ Write-Error "❌ [PREFLIGHT FAILED] Mandatory source path missing: $p"
27
+ exit 1
28
+ }
29
+ }
30
+ $SkillsCount = (Get-ChildItem -Path "$RepoRoot\.agents\skills" -Directory).Count
31
+ $AgentsCount = (Get-ChildItem -Path "$RepoRoot\.agents\agents" -File -Filter "*.md").Count
32
+ Write-Host " [OK] Verified source integrity: $SkillsCount skills, $AgentsCount agent profiles.`n" -ForegroundColor Green
33
+
17
34
  $PluginsDir = "$HOME\.gemini\config\plugins"
18
35
  $TargetPluginDir = "$PluginsDir\synapse-hub"
19
36
 
@@ -87,8 +104,8 @@ Write-Host "`n==================================================================
87
104
  Write-Host " 🎉 SUCCESS: Synapse-Hub is now installed as a GLOBAL PLUGIN! " -ForegroundColor Green
88
105
  Write-Host "======================================================================" -ForegroundColor Cyan
89
106
  Write-Host "• Location : $TargetPluginDir" -ForegroundColor White
90
- Write-Host "• Skills : 53 Standardized QA Skills" -ForegroundColor White
91
- Write-Host "• Agents : 9 Swarm Subagent Profiles" -ForegroundColor White
107
+ Write-Host "• Skills : $SkillsCount Standardized QA Skills" -ForegroundColor White
108
+ Write-Host "• Agents : $AgentsCount Swarm Subagent Profiles" -ForegroundColor White
92
109
  Write-Host "`n👉 Antigravity will now automatically load Synapse-Hub across ALL projects" -ForegroundColor Yellow
93
110
  Write-Host " without needing to add Synapse-Hub as a workspace folder!" -ForegroundColor Yellow
94
111
  Write-Host "======================================================================`n" -ForegroundColor Cyan
@@ -14,6 +14,25 @@ echo " SYNAPSE-HUB: ANTIGRAVITY GLOBAL PLUGIN 1-CLICK INSTALLER "
14
14
  echo "======================================================================"
15
15
  echo ""
16
16
 
17
+ # Preflight Validation Guard
18
+ echo "[Preflight] Checking repository integrity..."
19
+ if [ ! -d "$REPO_ROOT/.agents/skills" ]; then
20
+ echo "❌ [PREFLIGHT FAILED] Missing .agents/skills directory in $REPO_ROOT"
21
+ exit 1
22
+ fi
23
+ if [ ! -d "$REPO_ROOT/.agents/agents" ]; then
24
+ echo "❌ [PREFLIGHT FAILED] Missing .agents/agents directory in $REPO_ROOT"
25
+ exit 1
26
+ fi
27
+ if [ ! -d "$REPO_ROOT/tools" ]; then
28
+ echo "❌ [PREFLIGHT FAILED] Missing tools directory in $REPO_ROOT"
29
+ exit 1
30
+ fi
31
+
32
+ SKILLS_COUNT=$(find "$REPO_ROOT/.agents/skills" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')
33
+ AGENTS_COUNT=$(find "$REPO_ROOT/.agents/agents" -mindepth 1 -maxdepth 1 -type f -name "*.md" | wc -l | tr -d ' ')
34
+ echo " [OK] Verified source integrity: $SKILLS_COUNT skills, $AGENTS_COUNT agent profiles."
35
+
17
36
  PLUGINS_DIR="$HOME/.gemini/config/plugins"
18
37
  TARGET_PLUGIN_DIR="$PLUGINS_DIR/synapse-hub"
19
38
 
@@ -40,8 +59,8 @@ echo "======================================================================"
40
59
  echo " 🎉 SUCCESS: Synapse-Hub is now installed as a GLOBAL PLUGIN! "
41
60
  echo "======================================================================"
42
61
  echo "• Location : $TARGET_PLUGIN_DIR"
43
- echo "• Skills : 53 Standardized QA Skills"
44
- echo "• Agents : 9 Swarm Subagent Profiles"
62
+ echo "• Skills : $SKILLS_COUNT Standardized QA Skills"
63
+ echo "• Agents : $AGENTS_COUNT Swarm Subagent Profiles"
45
64
  echo ""
46
65
  echo "👉 Antigravity will now automatically load Synapse-Hub across ALL projects"
47
66
  echo " without needing to add Synapse-Hub as a workspace folder!"
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "name": "Synapse-Hub",
4
- "version": "3.9.1",
4
+ "version": "3.10.0",
5
5
  "description": "Unified Catalog of 53 Specialized Skills for Autonomous AI Agents in Enterprise Software Quality Engineering, Performance, and Architecture.",
6
6
  "totalSkills": 53,
7
7
  "categories": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://raw.githubusercontent.com/TeeVee98/Synapse-Hub/main/docs/schemas/synapse.config.schema.json",
3
- "version": "3.9.1",
3
+ "version": "3.10.0",
4
4
  "quality_gates": {
5
5
  "mutation_min_score": 80,
6
6
  "gates": {
@@ -1120,7 +1120,7 @@
1120
1120
  "category": "CI/CD & Packaging",
1121
1121
  "owner_role": "orchestrator",
1122
1122
  "status": "stable",
1123
- "risk_level": "read_only",
1123
+ "risk_level": "workspace_write",
1124
1124
  "inputs": [
1125
1125
  "--output-dir",
1126
1126
  "--format zip|tar.gz|both",
package/tools/__init__.py CHANGED
@@ -14,7 +14,7 @@ Domain Packages:
14
14
  - tools.mcp: Model Context Protocol servers (core QA and Excel manipulation).
15
15
  """
16
16
 
17
- __version__ = "3.9.1"
17
+ __version__ = "3.10.0"
18
18
  __author__ = "Thế Vị (@TeeVee98)"
19
19
 
20
20
  # Expose domain packages
@@ -13,7 +13,7 @@
13
13
  (function () {
14
14
  'use strict';
15
15
 
16
- if (window.__qa && window.__qa.__version === '3.9.1') {
16
+ if (window.__qa && window.__qa.__version === '3.10.0') {
17
17
  return window.__qa;
18
18
  }
19
19
 
@@ -47,7 +47,7 @@
47
47
  }
48
48
 
49
49
  const qa = {
50
- __version: '3.9.1',
50
+ __version: '3.10.0',
51
51
 
52
52
  /**
53
53
  * 1. Smart Action Batching
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.9.1"
102
+ version = "3.10.0"
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.9.1"
683
+ version = "3.10.0"
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.9.1"
690
+ version = "3.10.0"
691
691
  return version
692
692
 
693
693
 
@@ -184,11 +184,22 @@ def kill_process_tree(pid: int, timeout: float = 2.0) -> bool:
184
184
  return True
185
185
 
186
186
 
187
- def reap_orphan_processes(target_names: Optional[Tuple[str, ...]] = None) -> int:
187
+ def reap_orphan_processes(
188
+ target_names: Optional[Tuple[str, ...]] = None,
189
+ allow_system_wide: bool = False,
190
+ tracked_pids: Optional[List[int]] = None
191
+ ) -> int:
188
192
  """
189
193
  Safeguard reaper for orphaned runner and browser processes.
190
194
  Defaults to known test drivers: chromedriver, chromium, node, java.
191
- Returns the count of reaped processes.
195
+
196
+ Safety Invariants:
197
+ 1. Only reaps genuine orphaned processes whose parent process has died (on Windows:
198
+ not psutil.pid_exists(ppid); on POSIX: ppid == 1 or not psutil.pid_exists(ppid)),
199
+ or processes explicitly matching tracked_pids.
200
+ 2. Blind OS-wide 'taskkill /IM' and 'pkill -f' are eliminated by default to prevent
201
+ killing the developer's active desktop browsers. System-wide fallback requires
202
+ explicit allow_system_wide=True opt-in.
192
203
  """
193
204
  targets = target_names or ("chromedriver", "geckodriver", "chromium", "playwright")
194
205
  reaped = 0
@@ -196,20 +207,38 @@ def reap_orphan_processes(target_names: Optional[Tuple[str, ...]] = None) -> int
196
207
  try:
197
208
  import psutil # type: ignore
198
209
  current_pid = os.getpid()
199
- for proc in psutil.process_iter(attrs=["pid", "name"]):
210
+ for proc in psutil.process_iter(attrs=["pid", "name", "ppid"]):
200
211
  try:
201
212
  pname = (proc.info.get("name") or "").lower()
202
213
  pid = proc.info.get("pid")
203
- if pid and pid != current_pid and any(t in pname for t in targets):
214
+ ppid = proc.info.get("ppid")
215
+ if not pid or pid == current_pid:
216
+ continue
217
+
218
+ if not any(t in pname for t in targets):
219
+ continue
220
+
221
+ is_tracked = bool(tracked_pids and pid in tracked_pids)
222
+ is_orphan = False
223
+ if ppid is not None:
224
+ if sys.platform == "win32":
225
+ is_orphan = not psutil.pid_exists(ppid)
226
+ else:
227
+ is_orphan = (ppid == 1) or (not psutil.pid_exists(ppid))
228
+
229
+ if is_tracked or is_orphan or allow_system_wide:
204
230
  proc.kill()
205
231
  reaped += 1
206
232
  except (psutil.NoSuchProcess, psutil.AccessDenied):
207
233
  continue
208
234
  return reaped
209
- except ImportError as err:
210
- _ = err
235
+ except ImportError:
236
+ _psutil_available = False
237
+
238
+ # Native CLI fallbacks ONLY if explicitly requested via allow_system_wide
239
+ if not allow_system_wide:
240
+ return 0
211
241
 
212
- # Native CLI fallbacks when psutil is not available
213
242
  if sys.platform == "win32":
214
243
  for target in targets:
215
244
  im_name = target if target.endswith(".exe") else f"{target}.exe"
@@ -222,8 +251,8 @@ def reap_orphan_processes(target_names: Optional[Tuple[str, ...]] = None) -> int
222
251
  )
223
252
  if res.returncode == 0:
224
253
  reaped += 1
225
- except Exception as err:
226
- _ = err
254
+ except Exception:
255
+ continue
227
256
  else:
228
257
  for target in targets:
229
258
  try:
@@ -235,8 +264,8 @@ def reap_orphan_processes(target_names: Optional[Tuple[str, ...]] = None) -> int
235
264
  )
236
265
  if res.returncode == 0:
237
266
  reaped += 1
238
- except Exception as err:
239
- _ = err
267
+ except Exception:
268
+ continue
240
269
  return reaped
241
270
 
242
271
 
@@ -202,6 +202,19 @@ def create_trace_context(
202
202
  )
203
203
 
204
204
 
205
+ RESERVED_KEYS = {
206
+ "timestamp",
207
+ "level",
208
+ "trace_id",
209
+ "span_id",
210
+ "parent_span_id",
211
+ "module",
212
+ "event",
213
+ "duration_ms",
214
+ "exception",
215
+ }
216
+
217
+
205
218
  class StructuredJsonFormatter(logging.Formatter):
206
219
  """
207
220
  Formats log records into structured JSON conforming to enterprise schema:
@@ -221,9 +234,17 @@ class StructuredJsonFormatter(logging.Formatter):
221
234
  "duration_ms": getattr(record, "duration_ms", None),
222
235
  }
223
236
 
224
- # Include custom extra fields
237
+ # Include custom extra fields safely without overwriting reserved system schema
225
238
  if hasattr(record, "extra_payload") and isinstance(record.extra_payload, dict):
226
- record_dict.update(record.extra_payload)
239
+ attrs = {}
240
+ for k, v in record.extra_payload.items():
241
+ if k in RESERVED_KEYS:
242
+ attrs[k] = v
243
+ else:
244
+ record_dict[k] = v
245
+ attrs[k] = v
246
+ if attrs:
247
+ record_dict["attributes"] = attrs
227
248
 
228
249
  # Include exception if present
229
250
  if record.exc_info:
@@ -267,7 +288,15 @@ def log_event(
267
288
  "duration_ms": duration_ms,
268
289
  }
269
290
  if extra_payload:
270
- payload.update(extra_payload)
291
+ attrs = {}
292
+ for k, v in extra_payload.items():
293
+ if k in RESERVED_KEYS:
294
+ attrs[k] = v
295
+ else:
296
+ payload[k] = v
297
+ attrs[k] = v
298
+ if attrs:
299
+ payload["attributes"] = attrs
271
300
 
272
301
  lvl_num = getattr(logging, level.upper(), logging.INFO)
273
302
  logger = get_logger(logger_name)
@@ -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.9.1 &bull; Bản quyền &copy; Thế Vị (@TeeVee98) &bull; 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.10.0 &bull; Bản quyền &copy; Thế Vị (@TeeVee98) &bull; 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.9.1 &bull; Copyright &copy; Thế Vị (@TeeVee98) &bull; Clean POM & Autonomous Testing",
1429
+ "footer_text": "Generated automatically by Synapse-Hub v3.10.0 &bull; Copyright &copy; Thế Vị (@TeeVee98) &bull; 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.9.1 &bull; Hệ Sinh Thái Kiểm Thử AI Agent Tự Chủ",
1918
+ "header_subtitle": "Synapse-Hub v3.10.0 &bull; 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.9.1 &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.10.0 &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.9.1 &bull; Autonomous AI Agent Testing Ecosystem",
1993
+ "header_subtitle": "Synapse-Hub v3.10.0 &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.9.1 &bull; Copyright &copy; Thế Vị (@TeeVee98) &bull; Autonomous AI Agent Testing Ecosystem",
2063
+ "footer_text": "Enterprise QA Executive Dashboard &bull; Synapse-Hub v3.10.0 &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)
@@ -345,15 +345,32 @@ class DBSandbox:
345
345
  "zero_pollution_verified": count_after_rollback == 0
346
346
  }
347
347
  except Exception as e:
348
+ rollback_err_msg = None
349
+ count_after_rollback = None
348
350
  try:
349
351
  cursor.execute(f"ROLLBACK TO SAVEPOINT {safe_sp};")
350
- except sqlite3.Error as rollback_err:
352
+ if target_table:
353
+ safe_tbl = target_table.replace('"', '""')
354
+ cursor.execute(f'SELECT COUNT(*) FROM "{safe_tbl}"')
355
+ count_after_rollback = cursor.fetchone()[0]
356
+ except Exception as rollback_err:
357
+ rollback_err_msg = str(rollback_err)
351
358
  sys.stderr.write(f"Notice: Savepoint rollback notice: {rollback_err}\n")
352
- return {
359
+
360
+ zero_verified = (rollback_err_msg is None)
361
+ if count_after_rollback is not None and count_after_rollback > 0:
362
+ zero_verified = False
363
+
364
+ res = {
353
365
  "status": "ERROR",
354
366
  "error": str(e),
355
- "zero_pollution_verified": True
367
+ "zero_pollution_verified": zero_verified
356
368
  }
369
+ if rollback_err_msg:
370
+ res["rollback_error"] = rollback_err_msg
371
+ if count_after_rollback is not None:
372
+ res["count_after_rollback"] = count_after_rollback
373
+ return res
357
374
  finally:
358
375
  conn.close()
359
376
 
@@ -368,7 +385,7 @@ class DBSandbox:
368
385
  def audit_and_purge_pollution(
369
386
  self,
370
387
  known_test_prefixes: Tuple[str, ...] = ("AUTO_", "TEST_", "TEMP_"),
371
- dry_run: bool = False
388
+ dry_run: bool = True
372
389
  ) -> Dict[str, Any]:
373
390
  """
374
391
  Scans all tables for orphan records carrying test prefixes and purges them.
@@ -558,10 +575,12 @@ def main():
558
575
  snap_p.add_argument("--json", action="store_true", help="Output JSON format")
559
576
 
560
577
  # Command: restore
561
- rest_p = subparsers.add_parser("restore", help="Restore pristine snapshot")
578
+ rest_p = subparsers.add_parser("restore", help="Restore pristine snapshot (DESTRUCTIVE)")
562
579
  rest_p.add_argument("--db-path", default="", help="Path to database file or network URI")
563
580
  rest_p.add_argument("--db-type", default="", help="Database engine type (sqlite, postgres, mysql, oracle)")
564
581
  rest_p.add_argument("--id", default="pristine_baseline", help="Snapshot identifier")
582
+ rest_p.add_argument("--confirm", action="store_true", default=False,
583
+ help="Explicit confirmation for destructive restore operation")
565
584
  rest_p.add_argument("--json", action="store_true", help="Output JSON format")
566
585
 
567
586
  # Command: rollback-test
@@ -572,10 +591,13 @@ def main():
572
591
  roll_p.add_argument("--json", action="store_true", help="Output JSON format")
573
592
 
574
593
  # Command: audit
575
- aud_p = subparsers.add_parser("audit", help="Audit orphan test junk and purge")
594
+ aud_p = subparsers.add_parser("audit", help="Audit orphan test junk and purge (Safe dry-run by default)")
576
595
  aud_p.add_argument("--db-path", default="", help="Path to database file")
577
596
  aud_p.add_argument("--db-type", default="", help="Database engine type (sqlite, postgres, mysql)")
578
- aud_p.add_argument("--dry-run", action="store_true", help="Preview test records to purge without deleting")
597
+ aud_p.add_argument("--dry-run", action="store_true", default=None,
598
+ help="Preview test records to purge without deleting (default: True)")
599
+ aud_p.add_argument("--apply", "--force", dest="apply", action="store_true", default=False,
600
+ help="Explicitly apply destructive purge to delete matching test records")
579
601
  aud_p.add_argument("--json", action="store_true", help="Output JSON format")
580
602
 
581
603
  # Command: wait-ready (Testcontainers-style readiness gate)
@@ -625,6 +647,24 @@ def main():
625
647
  return 0 if res.get("status") != "ERROR" else 1
626
648
 
627
649
  elif args.command == "restore":
650
+ if not args.confirm and not os.environ.get("SYNAPSE_FORCE_RESTORE"):
651
+ err_msg = (
652
+ "Refusing to execute destructive database restore without explicit confirmation. "
653
+ "Pass --confirm (or set SYNAPSE_FORCE_RESTORE=1) if target is an isolated sandbox."
654
+ )
655
+ res = {
656
+ "status": "ERROR",
657
+ "message": err_msg,
658
+ "snapshot_id": args.id,
659
+ "target_db": sandbox.db_path,
660
+ "zero_pollution_guaranteed": False
661
+ }
662
+ if args.json:
663
+ print(json.dumps(res, indent=2))
664
+ else:
665
+ print(f"❌ [DB RESTORE BLOCKED] ID: {args.id}")
666
+ print(f" Error: {err_msg}")
667
+ return 1
628
668
  res = sandbox.restore_snapshot(args.id)
629
669
  if args.json:
630
670
  print(json.dumps(res, indent=2))
@@ -654,15 +694,18 @@ def main():
654
694
  return 0
655
695
 
656
696
  elif args.command == "audit":
657
- res = sandbox.audit_and_purge_pollution(dry_run=args.dry_run)
697
+ effective_dry_run = True if args.dry_run is None else args.dry_run
698
+ if args.apply:
699
+ effective_dry_run = False
700
+ res = sandbox.audit_and_purge_pollution(dry_run=effective_dry_run)
658
701
  if args.json:
659
702
  print(json.dumps(res, indent=2))
660
703
  else:
661
- action_label = "Previewed" if args.dry_run else "Purged"
704
+ action_label = "Previewed" if effective_dry_run else "Purged"
662
705
  print(f"🧹 [TAINT POLLUTION AUDIT] {action_label} {res['total_purged_rows']} orphan test records.")
663
706
  for detail in res.get("purge_details", []):
664
707
  print(f" - {detail}")
665
- if not args.dry_run:
708
+ if not effective_dry_run:
666
709
  print(" ✅ Zero Pollution Achieved.")
667
710
  return 0
668
711
 
@@ -60,7 +60,7 @@ if hasattr(sys.stdout, 'reconfigure'):
60
60
  except Exception:
61
61
  pass
62
62
 
63
- SERVER_VERSION = "3.9.1"
63
+ SERVER_VERSION = "3.10.0"
64
64
  MAX_DOCX_SIZE = 50 * 1024 * 1024 # 50 MB
65
65
  MAX_UNCOMPRESSED_SIZE = 200 * 1024 * 1024 # 200 MB
66
66
  MAX_RATIO = 100 # 100:1 compression ratio limit
@@ -52,7 +52,7 @@ if hasattr(sys.stdout, 'reconfigure'):
52
52
  except Exception:
53
53
  pass
54
54
 
55
- SERVER_VERSION = "3.9.1"
55
+ SERVER_VERSION = "3.10.0"
56
56
  MAX_XLSX_SIZE = 50 * 1024 * 1024 # 50 MB
57
57
  MAX_UNCOMPRESSED_SIZE = 200 * 1024 * 1024 # 200 MB
58
58
  MAX_RATIO = 100 # 100:1 compression ratio limit
@@ -46,7 +46,7 @@ import gherkin_suite
46
46
  import api_fuzzer
47
47
 
48
48
  SERVER_NAME = "enterprise-agent-qa"
49
- SERVER_VERSION = "3.9.1"
49
+ SERVER_VERSION = "3.10.0"
50
50
 
51
51
  MCP_TOOLS = [
52
52
  {
@@ -24,6 +24,7 @@ Usage:
24
24
 
25
25
  import os
26
26
  import sys
27
+ import re
27
28
  import json
28
29
  import zipfile
29
30
  import tarfile
@@ -136,6 +137,16 @@ def collect_package_files(repo_root: str) -> List[Tuple[str, str]]:
136
137
  continue
137
138
 
138
139
  full_path = os.path.join(root, f)
140
+ # Symlink escape guard: verify file does not resolve outside repository root
141
+ real_file = os.path.realpath(full_path)
142
+ real_root_dir = os.path.realpath(repo_root)
143
+ try:
144
+ if os.path.commonpath([real_file, real_root_dir]) != real_root_dir:
145
+ sys.stderr.write(f"Warning: Skipping symlink escaping repo root: {full_path} -> {real_file}\n")
146
+ continue
147
+ except (ValueError, OSError):
148
+ continue
149
+
139
150
  rel_path = os.path.relpath(full_path, repo_root).replace("\\", "/")
140
151
  packaged_files.append((full_path, rel_path))
141
152
 
@@ -217,20 +228,33 @@ def package_synapse_hub(
217
228
  out_dir = os.path.join(repo_root, output_dir)
218
229
  os.makedirs(out_dir, exist_ok=True)
219
230
 
220
- # 1. Clean up old archives in dist and repo_root
231
+ # 1. Clean up old release archives safely (guarded against repo root wildcard deletion)
232
+ is_same_as_root = False
233
+ try:
234
+ is_same_as_root = os.path.samefile(out_dir, repo_root)
235
+ except (FileNotFoundError, OSError, ValueError):
236
+ is_same_as_root = os.path.realpath(out_dir).lower() == os.path.realpath(repo_root).lower()
237
+
221
238
  for f in os.listdir(out_dir):
222
- if f.endswith((".zip", ".tar.gz", ".sha256")):
239
+ if re.match(r"^synapse-hub-v\d+\.\d+\.\d+.*", f, re.IGNORECASE) and f.endswith((".zip", ".tar.gz", ".sha256")):
223
240
  try:
224
241
  os.remove(os.path.join(out_dir, f))
225
242
  except OSError as err:
226
243
  _ = err
227
- for f in os.listdir(repo_root):
228
- if f.lower().startswith("synapse-hub") and f.endswith(".zip"):
244
+ elif not is_same_as_root and f.endswith((".zip", ".tar.gz", ".sha256")) and f.lower().startswith("synapse-hub"):
229
245
  try:
230
- os.remove(os.path.join(repo_root, f))
246
+ os.remove(os.path.join(out_dir, f))
231
247
  except OSError as err:
232
248
  _ = err
233
249
 
250
+ if not is_same_as_root:
251
+ for f in os.listdir(repo_root):
252
+ if re.match(r"^synapse-hub-v\d+\.\d+\.\d+.*", f, re.IGNORECASE) and f.endswith((".zip", ".tar.gz", ".sha256")):
253
+ try:
254
+ os.remove(os.path.join(repo_root, f))
255
+ except OSError as err:
256
+ _ = err
257
+
234
258
  files = collect_package_files(repo_root)
235
259
  base_name = f"synapse-hub-v{version}"
236
260
  created_archives: List[str] = []
@@ -49,6 +49,14 @@ SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
49
49
  QA_HUB_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, ".."))
50
50
 
51
51
 
52
+ def _split_cmd(cmd_str: str) -> List[str]:
53
+ """Splits a command string into argument tokens cross-platform without losing backslashes or quoting."""
54
+ if sys.platform == "win32":
55
+ tokens = shlex.split(cmd_str, posix=False)
56
+ return [t.strip('"') for t in tokens]
57
+ return shlex.split(cmd_str)
58
+
59
+
52
60
  def _resolve_wal_path() -> str:
53
61
  cwd = os.path.abspath(os.getcwd())
54
62
  try:
@@ -78,6 +86,7 @@ class ExecutionSandbox:
78
86
 
79
87
  def __init__(self, auto_rollback_on_exit: bool = True, wal_path: Optional[str] = None):
80
88
  self.undo_stack: List[ReversibleAction] = []
89
+ self.failed_actions: List[ReversibleAction] = []
81
90
  self.auto_rollback_on_exit = auto_rollback_on_exit
82
91
  self.wal_path = wal_path if wal_path is not None else _resolve_wal_path()
83
92
  if self.wal_path:
@@ -97,6 +106,7 @@ class ExecutionSandbox:
97
106
  "target_resource": action.target_resource,
98
107
  "undo_command": action.undo_command,
99
108
  "metadata": action.metadata,
109
+ "status": "PENDING",
100
110
  "timestamp": time.time()
101
111
  }
102
112
  line = json.dumps(entry, ensure_ascii=False) + "\n"
@@ -115,7 +125,7 @@ class ExecutionSandbox:
115
125
  sys.stderr.write(f"Warning: Failed to write undo WAL journal: {e}\n")
116
126
 
117
127
  def _clear_wal(self):
118
- """Clears or resets WAL journal when stack has been completely unwound."""
128
+ """Clears or resets WAL journal when stack has been completely unwound without errors."""
119
129
  if not self.wal_path or not os.path.exists(self.wal_path):
120
130
  return
121
131
  try:
@@ -130,6 +140,51 @@ class ExecutionSandbox:
130
140
  except Exception as clear_err:
131
141
  sys.stderr.write(f"Notice: Failed to clear WAL: {clear_err}\n")
132
142
 
143
+ def _update_wal_journal(
144
+ self,
145
+ pending_actions: List[ReversibleAction],
146
+ failed_entries: Optional[List[Dict[str, Any]]] = None
147
+ ):
148
+ """
149
+ Synchronously updates WAL journal with pending and failed actions (Incremental 2PC).
150
+ Clears the journal only when 100% of actions are resolved without failure.
151
+ """
152
+ if not self.wal_path:
153
+ return
154
+ failed_list = failed_entries or []
155
+ if not pending_actions and not failed_list:
156
+ self._clear_wal()
157
+ return
158
+
159
+ lines = []
160
+ for entry in failed_list:
161
+ lines.append(json.dumps(entry, ensure_ascii=False) + "\n")
162
+ for action in pending_actions:
163
+ entry = {
164
+ "action_type": action.action_type,
165
+ "target_resource": action.target_resource,
166
+ "undo_command": action.undo_command,
167
+ "metadata": action.metadata,
168
+ "status": "PENDING",
169
+ "timestamp": time.time()
170
+ }
171
+ lines.append(json.dumps(entry, ensure_ascii=False) + "\n")
172
+
173
+ content = "".join(lines)
174
+ try:
175
+ try:
176
+ from tools.core.file_lock import file_lock
177
+ with file_lock(self.wal_path + ".lock", timeout=5.0):
178
+ with open(self.wal_path, "w", encoding="utf-8") as f:
179
+ f.write(content)
180
+ f.flush()
181
+ except ImportError:
182
+ with open(self.wal_path, "w", encoding="utf-8") as f:
183
+ f.write(content)
184
+ f.flush()
185
+ except Exception as e:
186
+ sys.stderr.write(f"Warning: Failed to update WAL journal: {e}\n")
187
+
133
188
  def record_mutation(
134
189
  self,
135
190
  action_type: str,
@@ -156,7 +211,7 @@ class ExecutionSandbox:
156
211
  ) -> bool:
157
212
  """Executes a forward shell command and immediately records its reversible undo counterpart."""
158
213
  try:
159
- args = shlex.split(forward_cmd) if isinstance(forward_cmd, str) else forward_cmd
214
+ args = _split_cmd(forward_cmd) if isinstance(forward_cmd, str) else forward_cmd
160
215
  res = subprocess.run(args, text=True, capture_output=True, timeout=60.0)
161
216
  if res.returncode == 0:
162
217
  self.record_mutation(action_type, target_resource, undo_cmd, {"forward_cmd": forward_cmd})
@@ -166,10 +221,12 @@ class ExecutionSandbox:
166
221
  return False
167
222
 
168
223
  def rollback_all(self, silent: bool = False) -> List[Dict[str, Any]]:
169
- """Unwinds the undo stack in strictly reverse (LIFO) order and cleans WAL."""
224
+ """Unwinds the undo stack in strictly reverse (LIFO) order and preserves failed entries in WAL."""
170
225
  results = []
226
+ failed_entries: List[Dict[str, Any]] = []
227
+
171
228
  while self.undo_stack:
172
- action = self.undo_stack.pop()
229
+ action = self.undo_stack[-1]
173
230
  success = True
174
231
  err_msg = ""
175
232
  cmd = action.undo_command.strip()
@@ -191,13 +248,15 @@ class ExecutionSandbox:
191
248
  except Exception as e:
192
249
  success = False
193
250
  err_msg = str(e)
251
+ elif cmd in ("NOOP", ":"):
252
+ success = True
194
253
  elif cmd:
195
254
  try:
196
- args = shlex.split(cmd) if isinstance(cmd, str) else cmd
255
+ args = _split_cmd(cmd) if isinstance(cmd, str) else cmd
197
256
  res = subprocess.run(args, text=True, capture_output=True, timeout=60.0)
198
257
  success = (res.returncode == 0)
199
258
  if not success:
200
- err_msg = res.stderr.strip()
259
+ err_msg = res.stderr.strip() or f"Command exited with code {res.returncode}"
201
260
  except Exception as e:
202
261
  success = False
203
262
  err_msg = str(e)
@@ -210,11 +269,30 @@ class ExecutionSandbox:
210
269
  "error": err_msg
211
270
  }
212
271
  results.append(result_entry)
272
+
273
+ self.undo_stack.pop()
274
+
275
+ if success:
276
+ self._update_wal_journal(self.undo_stack, failed_entries=failed_entries)
277
+ else:
278
+ self.failed_actions.append(action)
279
+ failed_entry = {
280
+ "action_type": action.action_type,
281
+ "target_resource": action.target_resource,
282
+ "undo_command": action.undo_command,
283
+ "metadata": action.metadata,
284
+ "status": "FAILED",
285
+ "error": err_msg,
286
+ "timestamp": time.time()
287
+ }
288
+ failed_entries.append(failed_entry)
289
+ self._update_wal_journal(self.undo_stack, failed_entries=failed_entries)
290
+
213
291
  if not silent:
214
292
  status_icon = "✅" if success else "⚠️"
215
293
  print(f" {status_icon} [ROLLBACK] {action.action_type} on '{action.target_resource}': {action.undo_command}")
216
294
 
217
- if not self.undo_stack:
295
+ if not self.undo_stack and not self.failed_actions and not failed_entries:
218
296
  self._clear_wal()
219
297
 
220
298
  return results
@@ -236,7 +236,7 @@ class SynapseUiHandler(BaseHTTPRequestHandler):
236
236
  if path == "/api/status":
237
237
  active_target = JOB_MANAGER.target_dir or REPO_ROOT
238
238
  self.send_json(200, {
239
- "version": "3.9.1",
239
+ "version": "3.10.0",
240
240
  "status": "ONLINE",
241
241
  "os": sys.platform,
242
242
  "workspace": active_target,
@@ -65,7 +65,7 @@ def get_local_version():
65
65
  try:
66
66
  with open(pkg_file, "r", encoding="utf-8") as f:
67
67
  data = json.load(f)
68
- return data.get("version", "3.9.1")
68
+ return data.get("version", "3.10.0")
69
69
  except (OSError, json.JSONDecodeError):
70
70
  data = {}
71
71
 
@@ -74,11 +74,11 @@ def get_local_version():
74
74
  try:
75
75
  with open(manifest_file, "r", encoding="utf-8") as f:
76
76
  data = json.load(f)
77
- return data.get("version", "3.9.1")
77
+ return data.get("version", "3.10.0")
78
78
  except (OSError, json.JSONDecodeError):
79
79
  data = {}
80
80
 
81
- return "3.9.1"
81
+ return "3.10.0"
82
82
 
83
83
 
84
84
  def fetch_remote_version():
@@ -47,7 +47,7 @@ def get_hub_metadata() -> Dict[str, Any]:
47
47
  """Retrieves version and catalog count from skills_manifest.json."""
48
48
  manifest_path = os.path.join(HUB_ROOT, "skills_manifest.json")
49
49
  meta = {
50
- "version": "3.9.1",
50
+ "version": "3.10.0",
51
51
  "totalSkills": 42,
52
52
  "author": "Thế Vị (@TeeVee98)",
53
53
  "repo": "https://github.com/TeeVee98/Synapse-Hub"