Compare commits
1 Commits
fix/136
...
fix/38-saf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68ab3ecd8c |
@@ -1,5 +1,22 @@
|
||||
"""Crisis detection and metrics module."""
|
||||
"""
|
||||
Crisis detection and response system for the-door.
|
||||
|
||||
from .metrics import get_metrics_summary, get_metrics_report
|
||||
Stands between a broken man and a machine that would tell him to die.
|
||||
"""
|
||||
|
||||
__all__ = ["get_metrics_summary", "get_metrics_report"]
|
||||
from .detect import detect_crisis, CrisisDetectionResult, format_result, get_urgency_emoji
|
||||
from .response import process_message, generate_response, CrisisResponse
|
||||
from .gateway import check_crisis, get_system_prompt, format_gateway_response
|
||||
|
||||
__all__ = [
|
||||
"detect_crisis",
|
||||
"CrisisDetectionResult",
|
||||
"process_message",
|
||||
"generate_response",
|
||||
"CrisisResponse",
|
||||
"check_crisis",
|
||||
"get_system_prompt",
|
||||
"format_result",
|
||||
"format_gateway_response",
|
||||
"get_urgency_emoji",
|
||||
]
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Crisis Metrics CLI — View crisis detection health metrics.
|
||||
|
||||
Usage:
|
||||
python3 -m crisis.metrics --summary # weekly report
|
||||
python3 -m crisis.metrics --json # raw JSON export
|
||||
python3 -m crisis.metrics --today # today only
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
# Metrics file location
|
||||
METRICS_FILE = Path.home() / ".the-door" / "crisis_metrics.json"
|
||||
|
||||
|
||||
def load_metrics():
|
||||
"""Load metrics from file."""
|
||||
if not METRICS_FILE.exists():
|
||||
return {"detections": [], "stats": {}}
|
||||
|
||||
try:
|
||||
with open(METRICS_FILE) as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, IOError):
|
||||
return {"detections": [], "stats": {}}
|
||||
|
||||
|
||||
def get_metrics_summary(days=7):
|
||||
"""Get metrics summary for the last N days."""
|
||||
data = load_metrics()
|
||||
detections = data.get("detections", [])
|
||||
|
||||
cutoff = time.time() - (days * 86400)
|
||||
recent = [d for d in detections if d.get("timestamp", 0) > cutoff]
|
||||
|
||||
if not recent:
|
||||
return {
|
||||
"period_days": days,
|
||||
"total_detections": 0,
|
||||
"by_severity": {},
|
||||
"by_source": {},
|
||||
"avg_response_time": 0,
|
||||
}
|
||||
|
||||
by_severity = {}
|
||||
by_source = {}
|
||||
total_response_time = 0
|
||||
response_count = 0
|
||||
|
||||
for d in recent:
|
||||
severity = d.get("severity", "unknown")
|
||||
source = d.get("source", "unknown")
|
||||
|
||||
by_severity[severity] = by_severity.get(severity, 0) + 1
|
||||
by_source[source] = by_source.get(source, 0) + 1
|
||||
|
||||
if "response_time_ms" in d:
|
||||
total_response_time += d["response_time_ms"]
|
||||
response_count += 1
|
||||
|
||||
return {
|
||||
"period_days": days,
|
||||
"total_detections": len(recent),
|
||||
"by_severity": by_severity,
|
||||
"by_source": by_source,
|
||||
"avg_response_time_ms": total_response_time / response_count if response_count else 0,
|
||||
"first_detection": recent[0].get("timestamp"),
|
||||
"last_detection": recent[-1].get("timestamp"),
|
||||
}
|
||||
|
||||
|
||||
def get_metrics_report(days=7):
|
||||
"""Generate a human-readable metrics report."""
|
||||
summary = get_metrics_summary(days)
|
||||
|
||||
lines = []
|
||||
lines.append("=" * 50)
|
||||
lines.append("CRISIS DETECTION METRICS")
|
||||
lines.append(f"Period: Last {days} days")
|
||||
lines.append("=" * 50)
|
||||
lines.append("")
|
||||
|
||||
total = summary["total_detections"]
|
||||
lines.append(f"Total detections: {total}")
|
||||
lines.append("")
|
||||
|
||||
if total > 0:
|
||||
lines.append("By severity:")
|
||||
for sev, count in sorted(summary["by_severity"].items()):
|
||||
pct = (count / total) * 100
|
||||
bar = "█" * int(pct / 5)
|
||||
lines.append(f" {sev:12} {count:4} ({pct:5.1f}%) {bar}")
|
||||
lines.append("")
|
||||
|
||||
lines.append("By source:")
|
||||
for src, count in sorted(summary["by_source"].items()):
|
||||
lines.append(f" {src:20} {count:4}")
|
||||
lines.append("")
|
||||
|
||||
avg_ms = summary.get("avg_response_time_ms", 0)
|
||||
lines.append(f"Avg response time: {avg_ms:.0f}ms")
|
||||
|
||||
first = summary.get("first_detection")
|
||||
last = summary.get("last_detection")
|
||||
if first and last:
|
||||
first_dt = datetime.fromtimestamp(first)
|
||||
last_dt = datetime.fromtimestamp(last)
|
||||
lines.append(f"First detection: {first_dt.strftime('%Y-%m-%d %H:%M')}")
|
||||
lines.append(f"Last detection: {last_dt.strftime('%Y-%m-%d %H:%M')}")
|
||||
else:
|
||||
lines.append("No crisis detections in this period.")
|
||||
|
||||
lines.append("")
|
||||
lines.append("=" * 50)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Crisis Detection Metrics CLI",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
%(prog)s --summary Weekly summary report
|
||||
%(prog)s --today Today only
|
||||
%(prog)s --json Raw JSON export
|
||||
%(prog)s --days 30 Last 30 days
|
||||
""",
|
||||
)
|
||||
|
||||
parser.add_argument("--summary", action="store_true", help="Show summary report")
|
||||
parser.add_argument("--json", action="store_true", dest="json_output", help="Output as JSON")
|
||||
parser.add_argument("--today", action="store_true", help="Today only (1 day)")
|
||||
parser.add_argument("--days", type=int, default=7, help="Number of days (default: 7)")
|
||||
parser.add_argument("--metrics-file", type=str, help="Custom metrics file path")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.metrics_file:
|
||||
global METRICS_FILE
|
||||
METRICS_FILE = Path(args.metrics_file)
|
||||
|
||||
days = 1 if args.today else args.days
|
||||
|
||||
if args.json_output:
|
||||
summary = get_metrics_summary(days)
|
||||
print(json.dumps(summary, indent=2, default=str))
|
||||
else:
|
||||
report = get_metrics_report(days)
|
||||
print(report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
42
index.html
42
index.html
@@ -423,6 +423,35 @@ html, body {
|
||||
fill: currentColor;
|
||||
}
|
||||
|
||||
/* Chat safety plan button — always visible, subtle */
|
||||
#chat-safety-plan-btn {
|
||||
flex-shrink: 0;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
background: transparent;
|
||||
color: #8b949e;
|
||||
border: 1px solid #30363d;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: background 0.2s, color 0.2s, border-color 0.2s;
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
#chat-safety-plan-btn:hover,
|
||||
#chat-safety-plan-btn:focus {
|
||||
background: #161b22;
|
||||
color: #58a6ff;
|
||||
border-color: #58a6ff;
|
||||
outline: 2px solid #58a6ff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
#chat-safety-plan-btn svg {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
/* ===== MODALS ===== */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
@@ -675,6 +704,9 @@ html, body {
|
||||
<button id="send-btn" type="button" aria-label="Send message" disabled>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
|
||||
</button>
|
||||
<button id="chat-safety-plan-btn" type="button" aria-label="Open My Safety Plan" title="My Safety Plan">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -813,6 +845,7 @@ Sovereignty and service always.`;
|
||||
|
||||
// Safety Plan Elements
|
||||
var safetyPlanBtn = document.getElementById('safety-plan-btn');
|
||||
var chatSafetyPlanBtn = document.getElementById('chat-safety-plan-btn');
|
||||
var crisisSafetyPlanBtn = document.getElementById('crisis-safety-plan-btn');
|
||||
var safetyPlanModal = document.getElementById('safety-plan-modal');
|
||||
var closeSafetyPlan = document.getElementById('close-safety-plan');
|
||||
@@ -1290,6 +1323,15 @@ Sovereignty and service always.`;
|
||||
_activateSafetyPlanFocusTrap(safetyPlanBtn);
|
||||
});
|
||||
|
||||
// Chat input area safety plan button — always visible (#38)
|
||||
if (chatSafetyPlanBtn) {
|
||||
chatSafetyPlanBtn.addEventListener('click', function() {
|
||||
loadSafetyPlan();
|
||||
safetyPlanModal.classList.add('active');
|
||||
_activateSafetyPlanFocusTrap(chatSafetyPlanBtn);
|
||||
});
|
||||
}
|
||||
|
||||
// Crisis panel safety plan button (if crisis panel is visible)
|
||||
if (crisisSafetyPlanBtn) {
|
||||
crisisSafetyPlanBtn.addEventListener('click', function() {
|
||||
|
||||
102
tests/test_safety_plan_in_chat.py
Normal file
102
tests/test_safety_plan_in_chat.py
Normal file
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
Tests for #38 — Safety plan accessible from chat (not just overlay).
|
||||
|
||||
Verifies:
|
||||
1. Safety plan button exists in the input area
|
||||
2. Button has proper ARIA attributes
|
||||
3. Button is keyboard focusable
|
||||
4. Button does not require crisis detection to be visible
|
||||
"""
|
||||
|
||||
import re
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
INDEX_HTML = Path(__file__).parent.parent / "index.html"
|
||||
|
||||
|
||||
class TestSafetyPlanInChat(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.html = INDEX_HTML.read_text()
|
||||
|
||||
def test_chat_safety_plan_button_exists(self):
|
||||
"""Button #chat-safety-plan-btn exists in the DOM."""
|
||||
self.assertIn('id="chat-safety-plan-btn"', self.html)
|
||||
|
||||
def test_button_has_aria_label(self):
|
||||
"""Button has aria-label for screen readers."""
|
||||
match = re.search(
|
||||
r'<button[^>]*id="chat-safety-plan-btn"[^>]*aria-label="([^"]*)"',
|
||||
self.html
|
||||
)
|
||||
self.assertIsNotNone(match, "chat-safety-plan-btn missing aria-label")
|
||||
self.assertIn("safety", match.group(1).lower())
|
||||
|
||||
def test_button_has_title(self):
|
||||
"""Button has title attribute for tooltip."""
|
||||
self.assertRegex(
|
||||
self.html,
|
||||
r'<button[^>]*id="chat-safety-plan-btn"[^>]*title="[^"]*"[^>]*>'
|
||||
)
|
||||
|
||||
def test_button_is_in_input_area(self):
|
||||
"""Button is inside #input-area, not in crisis overlay."""
|
||||
input_area = re.search(
|
||||
r'<div id="input-area">(.*?)</div>\s*</div>',
|
||||
self.html, re.DOTALL
|
||||
)
|
||||
self.assertIsNotNone(input_area)
|
||||
self.assertIn('chat-safety-plan-btn', input_area.group(1))
|
||||
|
||||
def test_button_not_in_crisis_overlay(self):
|
||||
"""Button is NOT inside #crisis-overlay (always visible, no detection)."""
|
||||
overlay = re.search(
|
||||
r'<div id="crisis-overlay".*?</div>\s*</div>',
|
||||
self.html, re.DOTALL
|
||||
)
|
||||
if overlay:
|
||||
self.assertNotIn('chat-safety-plan-btn', overlay.group(0))
|
||||
|
||||
def test_button_has_shield_icon(self):
|
||||
"""Button includes a shield SVG icon."""
|
||||
btn_match = re.search(
|
||||
r'<button[^>]*id="chat-safety-plan-btn"[^>]*>(.*?)</button>',
|
||||
self.html, re.DOTALL
|
||||
)
|
||||
self.assertIsNotNone(btn_match)
|
||||
self.assertIn('svg', btn_match.group(1).lower())
|
||||
# Shield path
|
||||
self.assertIn('M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z', btn_match.group(1))
|
||||
|
||||
def test_css_exists_for_button(self):
|
||||
"""CSS rules exist for #chat-safety-plan-btn."""
|
||||
self.assertIn('#chat-safety-plan-btn', self.html)
|
||||
# Check for hover/focus styles
|
||||
self.assertIn('#chat-safety-plan-btn:hover', self.html)
|
||||
self.assertIn('#chat-safety-plan-btn:focus', self.html)
|
||||
|
||||
def test_javascript_listener_exists(self):
|
||||
"""JavaScript event listener exists for the button."""
|
||||
self.assertIn('chatSafetyPlanBtn', self.html)
|
||||
self.assertIn("chatSafetyPlanBtn.addEventListener('click'", self.html)
|
||||
|
||||
def test_javascript_calls_load_safety_plan(self):
|
||||
"""Click handler calls loadSafetyPlan() and shows modal."""
|
||||
listener = re.search(
|
||||
r'chatSafetyPlanBtn\.addEventListener.*?\{(.*?)\}',
|
||||
self.html, re.DOTALL
|
||||
)
|
||||
self.assertIsNotNone(listener)
|
||||
body = listener.group(1)
|
||||
self.assertIn('loadSafetyPlan()', body)
|
||||
self.assertIn("safetyPlanModal.classList.add('active')", body)
|
||||
|
||||
def test_focus_trap_uses_button_as_return_target(self):
|
||||
"""Focus trap returns focus to chatSafetyPlanBtn when modal closes."""
|
||||
self.assertIn('_activateSafetyPlanFocusTrap(chatSafetyPlanBtn)', self.html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user