Compare commits
3 Commits
claude/iss
...
claude/iss
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f5067e94a | ||
|
|
5d3e13ede2 | ||
|
|
9e00a59791 |
@@ -1981,73 +1981,6 @@ async def update_config_raw(body: RawConfigUpdate):
|
||||
raise HTTPException(status_code=400, detail=f"Invalid YAML: {e}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action endpoints — restart gateway / update Hermes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ActionResponse(BaseModel):
|
||||
ok: bool
|
||||
detail: str = ""
|
||||
|
||||
|
||||
@app.post("/api/actions/restart-gateway")
|
||||
async def restart_gateway():
|
||||
"""Send SIGUSR1 to the running gateway so it drains and restarts.
|
||||
|
||||
Falls back to a hard kill+restart if no PID is found or the signal
|
||||
fails (e.g. the gateway is managed by a remote process / container).
|
||||
Returns immediately with ``{"ok": true}`` if the signal was delivered;
|
||||
the caller should poll ``/api/status`` to confirm the new state.
|
||||
"""
|
||||
from gateway.status import get_running_pid
|
||||
|
||||
pid = get_running_pid()
|
||||
if pid is None:
|
||||
raise HTTPException(status_code=409, detail="Gateway is not running")
|
||||
|
||||
import signal as _signal
|
||||
|
||||
try:
|
||||
os.kill(pid, _signal.SIGUSR1)
|
||||
except (ProcessLookupError, PermissionError, OSError, AttributeError) as exc:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to signal gateway: {exc}")
|
||||
|
||||
return {"ok": True, "detail": f"Restart signal sent to PID {pid}"}
|
||||
|
||||
|
||||
@app.post("/api/actions/update-hermes")
|
||||
async def update_hermes():
|
||||
"""Run ``hermes update`` in a subprocess and return the output.
|
||||
|
||||
The update is performed synchronously (in a thread pool executor) so
|
||||
the endpoint blocks until completion. Clients should treat a 200
|
||||
response with ``"ok": true`` as success; ``"ok": false`` means the
|
||||
subprocess exited non-zero.
|
||||
"""
|
||||
import subprocess
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def _run_update():
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "hermes_cli.main", "update", "--yes"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=300,
|
||||
)
|
||||
combined = (result.stdout + result.stderr).strip()
|
||||
return result.returncode == 0, combined
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "Update timed out after 5 minutes"
|
||||
except Exception as exc:
|
||||
return False, str(exc)
|
||||
|
||||
ok, detail = await loop.run_in_executor(None, _run_update)
|
||||
return {"ok": ok, "detail": detail}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Token / cost analytics endpoint
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
68
hooks/pre-commit-path-guard.py
Normal file
68
hooks/pre-commit-path-guard.py
Normal file
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Pre-commit hook: Reject hardcoded home-directory paths.
|
||||
|
||||
Scans staged Python files for patterns like:
|
||||
- /Users/<name>/...
|
||||
- /home/<name>/...
|
||||
- ~/... (in string literals outside expanduser context)
|
||||
|
||||
Escape hatch: add `# noqa: hardcoded-path-ok` to any legitimate line.
|
||||
|
||||
Install:
|
||||
cp hooks/pre-commit-path-guard.py .git/hooks/pre-commit
|
||||
chmod +x .git/hooks/pre-commit
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add project root to path so we can import path_guard
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from tools.path_guard import scan_file_for_violations
|
||||
|
||||
|
||||
def get_staged_files():
|
||||
"""Get list of staged .py files."""
|
||||
result = subprocess.run(
|
||||
["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
return [f for f in result.stdout.strip().splitlines() if f.endswith(".py")]
|
||||
|
||||
|
||||
def main():
|
||||
files = get_staged_files()
|
||||
if not files:
|
||||
sys.exit(0)
|
||||
|
||||
all_violations = []
|
||||
for filepath in files:
|
||||
if not Path(filepath).exists():
|
||||
continue
|
||||
violations = scan_file_for_violations(filepath)
|
||||
if violations:
|
||||
all_violations.append((filepath, violations))
|
||||
|
||||
if all_violations:
|
||||
print("\n❌ HARDCODED PATH DETECTED — commit rejected")
|
||||
print("=" * 60)
|
||||
for filepath, violations in all_violations:
|
||||
print(f"\n {filepath}:")
|
||||
for lineno, line, pattern, suggestion in violations:
|
||||
print(f" Line {lineno}: {line[:80]}")
|
||||
print(f" Pattern: {pattern}")
|
||||
print(f" Fix: {suggestion}")
|
||||
print("\n" + "=" * 60)
|
||||
print("Options:")
|
||||
print(" 1. Use get_hermes_home(), os.environ['HOME'], or relative paths")
|
||||
print(" 2. Add # noqa: hardcoded-path-ok to the line for legitimate cases")
|
||||
print("")
|
||||
sys.exit(1)
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1176,135 +1176,3 @@ class TestStatusRemoteGateway:
|
||||
assert data["gateway_running"] is True
|
||||
assert data["gateway_pid"] is None
|
||||
assert data["gateway_state"] == "running"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action endpoint tests — restart-gateway / update-hermes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestActionEndpoints:
|
||||
"""Test the /api/actions/* endpoints."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _setup_test_client(self):
|
||||
try:
|
||||
from starlette.testclient import TestClient
|
||||
except ImportError:
|
||||
pytest.skip("fastapi/starlette not installed")
|
||||
|
||||
from hermes_cli.web_server import app, _SESSION_TOKEN
|
||||
self.client = TestClient(app)
|
||||
self.client.headers["Authorization"] = f"Bearer {_SESSION_TOKEN}"
|
||||
|
||||
# ── restart-gateway ────────────────────────────────────────────────────
|
||||
|
||||
def test_restart_gateway_sends_sigusr1(self, monkeypatch):
|
||||
"""POST /api/actions/restart-gateway signals the running PID."""
|
||||
killed = {}
|
||||
|
||||
def _fake_kill(pid, sig):
|
||||
killed["pid"] = pid
|
||||
killed["sig"] = sig
|
||||
|
||||
monkeypatch.setattr("gateway.status.get_running_pid", lambda: 12345)
|
||||
monkeypatch.setattr("hermes_cli.web_server.os.kill", _fake_kill)
|
||||
|
||||
resp = self.client.post("/api/actions/restart-gateway")
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is True
|
||||
assert "12345" in data["detail"]
|
||||
assert killed["pid"] == 12345
|
||||
|
||||
def test_restart_gateway_409_when_not_running(self, monkeypatch):
|
||||
"""POST /api/actions/restart-gateway returns 409 when gateway is not running."""
|
||||
monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)
|
||||
|
||||
resp = self.client.post("/api/actions/restart-gateway")
|
||||
|
||||
assert resp.status_code == 409
|
||||
|
||||
def test_restart_gateway_500_on_signal_error(self, monkeypatch):
|
||||
"""POST /api/actions/restart-gateway returns 500 when the signal fails."""
|
||||
monkeypatch.setattr("gateway.status.get_running_pid", lambda: 99999)
|
||||
monkeypatch.setattr("hermes_cli.web_server.os.kill", lambda pid, sig: (_ for _ in ()).throw(ProcessLookupError("no such process")))
|
||||
|
||||
resp = self.client.post("/api/actions/restart-gateway")
|
||||
|
||||
assert resp.status_code == 500
|
||||
assert "Failed to signal" in resp.json()["detail"]
|
||||
|
||||
# ── update-hermes ──────────────────────────────────────────────────────
|
||||
|
||||
def test_update_hermes_success(self, monkeypatch):
|
||||
"""POST /api/actions/update-hermes returns ok=true on zero exit."""
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
class _FakeResult:
|
||||
returncode = 0
|
||||
stdout = "Already up to date.\n"
|
||||
stderr = ""
|
||||
|
||||
def _fake_run(cmd, **kwargs):
|
||||
assert "--yes" in cmd
|
||||
return _FakeResult()
|
||||
|
||||
monkeypatch.setattr("subprocess.run", _fake_run)
|
||||
|
||||
resp = self.client.post("/api/actions/update-hermes")
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is True
|
||||
assert "Already up to date" in data["detail"]
|
||||
|
||||
def test_update_hermes_failure_on_nonzero_exit(self, monkeypatch):
|
||||
"""POST /api/actions/update-hermes returns ok=false on non-zero exit."""
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
class _FakeResult:
|
||||
returncode = 1
|
||||
stdout = ""
|
||||
stderr = "error: update failed\n"
|
||||
|
||||
monkeypatch.setattr("subprocess.run", lambda cmd, **kw: _FakeResult())
|
||||
|
||||
resp = self.client.post("/api/actions/update-hermes")
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is False
|
||||
assert "error: update failed" in data["detail"]
|
||||
|
||||
def test_update_hermes_timeout(self, monkeypatch):
|
||||
"""POST /api/actions/update-hermes returns ok=false on timeout."""
|
||||
import subprocess
|
||||
import hermes_cli.web_server as ws
|
||||
|
||||
def _fake_run(cmd, **kwargs):
|
||||
raise subprocess.TimeoutExpired(cmd, 300)
|
||||
|
||||
monkeypatch.setattr("subprocess.run", _fake_run)
|
||||
|
||||
resp = self.client.post("/api/actions/update-hermes")
|
||||
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["ok"] is False
|
||||
assert "timed out" in data["detail"].lower()
|
||||
|
||||
def test_action_endpoints_require_auth(self):
|
||||
"""Action endpoints reject requests without a valid Bearer token."""
|
||||
try:
|
||||
from starlette.testclient import TestClient
|
||||
except ImportError:
|
||||
pytest.skip("fastapi/starlette not installed")
|
||||
|
||||
from hermes_cli.web_server import app
|
||||
unauthed = TestClient(app)
|
||||
|
||||
for path in ["/api/actions/restart-gateway", "/api/actions/update-hermes"]:
|
||||
resp = unauthed.post(path)
|
||||
assert resp.status_code in (401, 403), f"{path} should require auth"
|
||||
|
||||
127
tests/test_path_guard.py
Normal file
127
tests/test_path_guard.py
Normal file
@@ -0,0 +1,127 @@
|
||||
"""Tests for tools/path_guard.py — poka-yoke hardcoded path detection."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tools.path_guard import (
|
||||
PathGuardError,
|
||||
scan_directory,
|
||||
scan_file_for_violations,
|
||||
validate_path,
|
||||
validate_tool_paths,
|
||||
)
|
||||
|
||||
|
||||
class TestValidatePath:
|
||||
"""Runtime path validation."""
|
||||
|
||||
def test_valid_relative_path(self):
|
||||
assert validate_path("tools/file_tools.py") == "tools/file_tools.py"
|
||||
|
||||
def test_valid_absolute_path(self):
|
||||
assert validate_path("/tmp/test.txt") == "/tmp/test.txt"
|
||||
|
||||
def test_valid_hermes_home(self):
|
||||
assert validate_path(os.path.expanduser("~/.hermes/config.yaml")) is not None
|
||||
|
||||
def test_reject_users_hardcoded(self):
|
||||
with pytest.raises(PathGuardError, match="/Users/"):
|
||||
validate_path("/Users/someone_else/.hermes/config")
|
||||
|
||||
def test_reject_home_hardcoded(self):
|
||||
with pytest.raises(PathGuardError, match="/home/"):
|
||||
validate_path("/home/user/.hermes/config")
|
||||
|
||||
def test_empty_path(self):
|
||||
assert validate_path("") == ""
|
||||
assert validate_path(None) is None
|
||||
|
||||
def test_non_string(self):
|
||||
assert validate_path(42) == 42
|
||||
|
||||
|
||||
class TestValidateToolPaths:
|
||||
"""Batch path validation."""
|
||||
|
||||
def test_all_valid(self):
|
||||
paths = ["tools/file.py", "/tmp/x.txt", "relative/path.py"]
|
||||
assert validate_tool_paths(paths) == paths
|
||||
|
||||
def test_mixed_invalid(self):
|
||||
with pytest.raises(PathGuardError):
|
||||
validate_tool_paths(["tools/file.py", "/Users/someone_else/secret.txt"])
|
||||
|
||||
def test_skips_non_strings(self):
|
||||
assert validate_tool_paths([None, 42, "valid.py"]) == ["valid.py"]
|
||||
|
||||
|
||||
class TestScanFileForViolations:
|
||||
"""Static file scanning."""
|
||||
|
||||
def test_clean_file(self, tmp_path):
|
||||
f = tmp_path / "clean.py"
|
||||
f.write_text("import os\nHOME = os.environ['HOME']\n")
|
||||
assert scan_file_for_violations(str(f)) == []
|
||||
|
||||
def test_hardcoded_users(self, tmp_path):
|
||||
f = tmp_path / "bad.py"
|
||||
f.write_text("CONFIG = '/Users/apayne/.hermes/config.yaml'\n")
|
||||
violations = scan_file_for_violations(str(f))
|
||||
assert len(violations) == 1
|
||||
assert "/Users/<name>/" in violations[0][2]
|
||||
|
||||
def test_hardcoded_home(self, tmp_path):
|
||||
f = tmp_path / "bad2.py"
|
||||
f.write_text("PATH = '/home/deploy/.hermes/state.db'\n")
|
||||
violations = scan_file_for_violations(str(f))
|
||||
assert len(violations) == 1
|
||||
assert "/home/<name>/" in violations[0][2]
|
||||
|
||||
def test_tilde_in_expanduser_ok(self, tmp_path):
|
||||
f = tmp_path / "ok.py"
|
||||
f.write_text("p = os.path.expanduser('~/.hermes/config')\n")
|
||||
assert scan_file_for_violations(str(f)) == []
|
||||
|
||||
def test_tilde_in_display_ok(self, tmp_path):
|
||||
f = tmp_path / "ok2.py"
|
||||
f.write_text('print("~/config saved")\n')
|
||||
assert scan_file_for_violations(str(f)) == []
|
||||
|
||||
def test_noqa_escape(self, tmp_path):
|
||||
f = tmp_path / "noqa.py"
|
||||
f.write_text("PATH = '/Users/apayne/test' # noqa: hardcoded-path-ok\n")
|
||||
assert scan_file_for_violations(str(f)) == []
|
||||
|
||||
def test_comments_skipped(self, tmp_path):
|
||||
f = tmp_path / "comment.py"
|
||||
f.write_text("# PATH = '/Users/apayne/test'\n")
|
||||
assert scan_file_for_violations(str(f)) == []
|
||||
|
||||
|
||||
class TestScanDirectory:
|
||||
"""Directory scanning."""
|
||||
|
||||
def test_clean_tree(self, tmp_path):
|
||||
(tmp_path / "clean.py").write_text("import os\n")
|
||||
(tmp_path / "sub").mkdir()
|
||||
(tmp_path / "sub" / "also_clean.py").write_text("x = 1\n")
|
||||
assert scan_directory(str(tmp_path)) == []
|
||||
|
||||
def test_finds_violations(self, tmp_path):
|
||||
(tmp_path / "bad.py").write_text("P = '/Users/x/.hermes'\n")
|
||||
results = scan_directory(str(tmp_path))
|
||||
assert len(results) == 1
|
||||
assert results[0][0].endswith("bad.py")
|
||||
|
||||
def test_skips_tests(self, tmp_path):
|
||||
(tmp_path / "test_something.py").write_text("P = '/Users/x/.hermes'\n")
|
||||
assert scan_directory(str(tmp_path)) == []
|
||||
|
||||
def test_skips_pycache(self, tmp_path):
|
||||
cache = tmp_path / "__pycache__"
|
||||
cache.mkdir()
|
||||
(cache / "cached.py").write_text("P = '/Users/x/.hermes'\n")
|
||||
assert scan_directory(str(tmp_path)) == []
|
||||
165
tools/path_guard.py
Normal file
165
tools/path_guard.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
tools/path_guard.py — Poka-yoke: Prevent hardcoded home-directory paths.
|
||||
|
||||
Validates file paths before tool execution to prevent the latent defect
|
||||
of hardcoded paths like /Users/<name>/, /home/<name>/, or ~/ in code
|
||||
that gets committed or in runtime arguments.
|
||||
|
||||
Usage:
|
||||
from tools.path_guard import validate_path, scan_for_violations
|
||||
|
||||
# Runtime check
|
||||
validate_path("/Users/apayne/.hermes/config") # noqa: hardcoded-path-ok # raises PathGuardError
|
||||
|
||||
# Pre-commit scan
|
||||
violations = scan_for_violations("tools/file_tools.py")
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import List, Tuple
|
||||
|
||||
# ── Patterns ────────────────────────────────────────────────────────
|
||||
|
||||
# Matches hardcoded home-directory paths in string content
|
||||
HARDCODED_PATH_PATTERNS = [
|
||||
# /Users/<name>/... (macOS)
|
||||
(re.compile(r"""['"]/(Users)/[\w.-]+/"""), "/Users/<name>/"),
|
||||
# /home/<name>/... (Linux)
|
||||
(re.compile(r"""['"]/home/[\w.-]+/"""), "/home/<name>/"),
|
||||
# Bare ~/... (unexpanded tilde in code — NOT in expanduser() calls)
|
||||
(re.compile(r"""['"]~/[^'"]+['"]"""), "~/..."), # noqa: hardcoded-path-ok
|
||||
# /root/... (Linux root home)
|
||||
(re.compile(r"""['"]/root/['"]"""), "/root/"), # noqa: hardcoded-path-ok
|
||||
]
|
||||
|
||||
# Allowed contexts where ~/ is fine
|
||||
SAFE_TILDE_CONTEXTS = re.compile(
|
||||
r"""expanduser|display_path|relpath|os\.path|Path\(|str\(.*home|"""
|
||||
r"""noqa:\s*hardcoded-path-ok|""" # explicit escape hatch
|
||||
r"""\bprint\(|f['"]|\.format\(|""" # display/formatting contexts
|
||||
r"""["']~/["']\s*$""", # just displaying ~/ as prefix
|
||||
re.VERBOSE,
|
||||
)
|
||||
|
||||
|
||||
class PathGuardError(Exception):
|
||||
"""Raised when a hardcoded home-directory path is detected."""
|
||||
|
||||
def __init__(self, path: str, pattern_name: str, suggestion: str):
|
||||
self.path = path
|
||||
self.pattern_name = pattern_name
|
||||
self.suggestion = suggestion
|
||||
super().__init__(
|
||||
f"Hardcoded path detected: {path} matches {pattern_name}. "
|
||||
f"Suggestion: {suggestion}. "
|
||||
f"Use get_hermes_home(), os.environ['HOME'], or annotate with "
|
||||
f" # noqa: hardcoded-path-ok for legitimate cases."
|
||||
)
|
||||
|
||||
|
||||
# ── Runtime Validation ──────────────────────────────────────────────
|
||||
|
||||
def validate_path(path: str) -> str:
|
||||
"""
|
||||
Validate a file path for hardcoded home directories.
|
||||
Returns the path if valid, raises PathGuardError if not.
|
||||
|
||||
This is meant to be called in tool wrappers (write_file, execute_code)
|
||||
before executing operations with user-supplied paths.
|
||||
|
||||
Note: At runtime, paths from os.path.expanduser() will resolve to
|
||||
/Users/<name>/... — this is expected and allowed. The guard catches
|
||||
paths that were LITERALLY hardcoded in source code or tool arguments
|
||||
that look like they came from a different machine (e.g., a path
|
||||
containing a different username than the current user).
|
||||
"""
|
||||
if not path or not isinstance(path, str):
|
||||
return path
|
||||
|
||||
# At runtime, expanded paths matching current HOME are fine
|
||||
home = os.environ.get("HOME", "")
|
||||
if home and path.startswith(home):
|
||||
return path
|
||||
|
||||
# Check for hardcoded /Users/<name>/ (macOS) — but not current user
|
||||
if re.match(r"^/Users/[\w.-]+/", path):
|
||||
raise PathGuardError(
|
||||
path, "/Users/<name>/",
|
||||
f"Use $HOME or os.path.expanduser('~') instead. "
|
||||
f"Got: {path}"
|
||||
)
|
||||
|
||||
# Check for hardcoded /home/<name>/ (Linux)
|
||||
if re.match(r"^/home/[\w.-]+/", path):
|
||||
raise PathGuardError(
|
||||
path, "/home/<name>/",
|
||||
f"Use $HOME or os.path.expanduser('~') instead. "
|
||||
f"Got: {path}"
|
||||
)
|
||||
|
||||
return path
|
||||
|
||||
|
||||
def validate_tool_paths(paths: list) -> list:
|
||||
"""
|
||||
Validate multiple paths (e.g., from tool arguments).
|
||||
Returns validated list. Raises PathGuardError on first violation.
|
||||
"""
|
||||
return [validate_path(p) for p in paths if isinstance(p, str)]
|
||||
|
||||
|
||||
# ── File Scanning (Pre-commit / CI) ────────────────────────────────
|
||||
|
||||
def scan_file_for_violations(filepath: str) -> List[Tuple[int, str, str, str]]:
|
||||
"""
|
||||
Scan a Python file for hardcoded home-directory path patterns.
|
||||
Returns list of (line_number, line_content, pattern_name, suggestion).
|
||||
"""
|
||||
violations = []
|
||||
try:
|
||||
with open(filepath) as f:
|
||||
for lineno, line in enumerate(f, 1):
|
||||
# Skip comments and noqa lines
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("#"):
|
||||
continue
|
||||
if "noqa: hardcoded-path-ok" in line:
|
||||
continue
|
||||
|
||||
for pattern, name in HARDCODED_PATH_PATTERNS:
|
||||
if pattern.search(line):
|
||||
# Special case: ~/ in expanduser/display context is OK
|
||||
if name == "~/..." and SAFE_TILDE_CONTEXTS.search(line): # noqa: hardcoded-path-ok
|
||||
continue
|
||||
violations.append((lineno, line.rstrip(), name,
|
||||
f"Use get_hermes_home(), os.environ['HOME'], or add # noqa: hardcoded-path-ok"))
|
||||
except (IOError, UnicodeDecodeError):
|
||||
pass
|
||||
return violations
|
||||
|
||||
|
||||
def scan_directory(root: str, extensions: tuple = (".py",)) -> List[Tuple[str, List]]:
|
||||
"""
|
||||
Scan a directory tree for hardcoded path violations.
|
||||
Returns list of (filepath, violations) tuples.
|
||||
"""
|
||||
results = []
|
||||
for dirpath, _, filenames in os.walk(root):
|
||||
# Skip hidden dirs, __pycache__, venv, test dirs
|
||||
skip_dirs = {"__pycache__", ".git", "venv", "node_modules", ".hermes"}
|
||||
if any(s in dirpath for s in skip_dirs):
|
||||
continue
|
||||
|
||||
for fname in filenames:
|
||||
if not fname.endswith(extensions):
|
||||
continue
|
||||
# Skip test files (they may legitimately have paths)
|
||||
if fname.startswith("test_") or "/tests/" in dirpath:
|
||||
continue
|
||||
fpath = os.path.join(dirpath, fname)
|
||||
violations = scan_file_for_violations(fpath)
|
||||
if violations:
|
||||
results.append((fpath, violations))
|
||||
return results
|
||||
@@ -86,15 +86,6 @@ export const en: Translations = {
|
||||
lastUpdate: "Last update",
|
||||
platformError: "error",
|
||||
platformDisconnected: "disconnected",
|
||||
actions: "Actions",
|
||||
restartGateway: "Restart Gateway",
|
||||
restarting: "Restarting…",
|
||||
restartSuccess: "Gateway restart signal sent",
|
||||
restartFailed: "Restart failed",
|
||||
updateHermes: "Update Hermes",
|
||||
updating: "Updating…",
|
||||
updateSuccess: "Update complete",
|
||||
updateFailed: "Update failed",
|
||||
},
|
||||
|
||||
sessions: {
|
||||
|
||||
@@ -89,15 +89,6 @@ export interface Translations {
|
||||
lastUpdate: string;
|
||||
platformError: string;
|
||||
platformDisconnected: string;
|
||||
actions: string;
|
||||
restartGateway: string;
|
||||
restarting: string;
|
||||
restartSuccess: string;
|
||||
restartFailed: string;
|
||||
updateHermes: string;
|
||||
updating: string;
|
||||
updateSuccess: string;
|
||||
updateFailed: string;
|
||||
};
|
||||
|
||||
// ── Sessions page ──
|
||||
|
||||
@@ -86,15 +86,6 @@ export const zh: Translations = {
|
||||
lastUpdate: "最后更新",
|
||||
platformError: "错误",
|
||||
platformDisconnected: "已断开",
|
||||
actions: "操作",
|
||||
restartGateway: "重启网关",
|
||||
restarting: "重启中…",
|
||||
restartSuccess: "重启信号已发送",
|
||||
restartFailed: "重启失败",
|
||||
updateHermes: "更新 Hermes",
|
||||
updating: "更新中…",
|
||||
updateSuccess: "更新完成",
|
||||
updateFailed: "更新失败",
|
||||
},
|
||||
|
||||
sessions: {
|
||||
|
||||
@@ -182,12 +182,6 @@ export const api = {
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
// Dashboard actions
|
||||
restartGateway: () =>
|
||||
fetchJSON<ActionResponse>("/api/actions/restart-gateway", { method: "POST" }),
|
||||
updateHermes: () =>
|
||||
fetchJSON<ActionResponse>("/api/actions/update-hermes", { method: "POST" }),
|
||||
};
|
||||
|
||||
export interface PlatformStatus {
|
||||
@@ -415,15 +409,9 @@ export interface OAuthSubmitResponse {
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ActionResponse {
|
||||
ok: boolean;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export interface OAuthPollResponse {
|
||||
session_id: string;
|
||||
status: "pending" | "approved" | "denied" | "expired" | "error";
|
||||
error_message?: string | null;
|
||||
expires_at?: number | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Activity,
|
||||
AlertTriangle,
|
||||
@@ -6,30 +6,19 @@ import {
|
||||
Cpu,
|
||||
Database,
|
||||
Radio,
|
||||
RefreshCw,
|
||||
TriangleAlert,
|
||||
Wifi,
|
||||
WifiOff,
|
||||
Zap,
|
||||
} from "lucide-react";
|
||||
import { api } from "@/lib/api";
|
||||
import type { PlatformStatus, SessionInfo, StatusResponse } from "@/lib/api";
|
||||
import { timeAgo, isoTimeAgo } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { useI18n } from "@/i18n";
|
||||
|
||||
type ActionState = "idle" | "running" | "success" | "failure";
|
||||
|
||||
export default function StatusPage() {
|
||||
const [status, setStatus] = useState<StatusResponse | null>(null);
|
||||
const [sessions, setSessions] = useState<SessionInfo[]>([]);
|
||||
const [restartState, setRestartState] = useState<ActionState>("idle");
|
||||
const [restartDetail, setRestartDetail] = useState("");
|
||||
const [updateState, setUpdateState] = useState<ActionState>("idle");
|
||||
const [updateDetail, setUpdateDetail] = useState("");
|
||||
const resetTimers = useRef<Record<string, ReturnType<typeof setTimeout>>>({});
|
||||
const { t } = useI18n();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -42,39 +31,6 @@ export default function StatusPage() {
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
function scheduleReset(key: string, setter: (s: ActionState) => void) {
|
||||
clearTimeout(resetTimers.current[key]);
|
||||
resetTimers.current[key] = setTimeout(() => setter("idle"), 8000);
|
||||
}
|
||||
|
||||
async function handleRestartGateway() {
|
||||
setRestartState("running");
|
||||
setRestartDetail("");
|
||||
try {
|
||||
const resp = await api.restartGateway();
|
||||
setRestartState(resp.ok ? "success" : "failure");
|
||||
setRestartDetail(resp.detail);
|
||||
} catch (err: unknown) {
|
||||
setRestartState("failure");
|
||||
setRestartDetail(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
scheduleReset("restart", setRestartState);
|
||||
}
|
||||
|
||||
async function handleUpdateHermes() {
|
||||
setUpdateState("running");
|
||||
setUpdateDetail("");
|
||||
try {
|
||||
const resp = await api.updateHermes();
|
||||
setUpdateState(resp.ok ? "success" : "failure");
|
||||
setUpdateDetail(resp.detail);
|
||||
} catch (err: unknown) {
|
||||
setUpdateState("failure");
|
||||
setUpdateDetail(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
scheduleReset("update", setUpdateState);
|
||||
}
|
||||
|
||||
if (!status) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-24">
|
||||
@@ -203,57 +159,6 @@ export default function StatusPage() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Action buttons — restart gateway / update Hermes */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle className="text-base">{t.status.actions}</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-wrap gap-3">
|
||||
{/* Restart Gateway */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={restartState === "running"}
|
||||
onClick={handleRestartGateway}
|
||||
>
|
||||
<RefreshCw className={`h-3.5 w-3.5 mr-1 ${restartState === "running" ? "animate-spin" : ""}`} />
|
||||
{restartState === "running" ? t.status.restarting : t.status.restartGateway}
|
||||
</Button>
|
||||
{(restartDetail || restartState === "success") && (
|
||||
<p className={`text-xs max-w-xs truncate ${restartState === "failure" ? "text-destructive" : "text-muted-foreground"}`}>
|
||||
{restartState === "failure" && <TriangleAlert className="inline h-3 w-3 mr-1" />}
|
||||
{restartState === "success" ? t.status.restartSuccess : restartState === "failure" ? t.status.restartFailed : ""}
|
||||
{restartDetail && ` — ${restartDetail}`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Update Hermes */}
|
||||
<div className="flex flex-col gap-1">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={updateState === "running"}
|
||||
onClick={handleUpdateHermes}
|
||||
>
|
||||
<RefreshCw className={`h-3.5 w-3.5 mr-1 ${updateState === "running" ? "animate-spin" : ""}`} />
|
||||
{updateState === "running" ? t.status.updating : t.status.updateHermes}
|
||||
</Button>
|
||||
{(updateDetail || updateState === "success" || updateState === "failure") && (
|
||||
<p className={`text-xs max-w-xs ${updateState === "failure" ? "text-destructive" : "text-muted-foreground"}`}>
|
||||
{updateState === "failure" && <TriangleAlert className="inline h-3 w-3 mr-1" />}
|
||||
{updateState === "success" ? t.status.updateSuccess : updateState === "failure" ? t.status.updateFailed : ""}
|
||||
{updateDetail && ` — ${updateDetail}`}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{platforms.length > 0 && (
|
||||
<PlatformsCard platforms={platforms} platformStateBadge={PLATFORM_STATE_BADGE} />
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user