Compare commits

..

2 Commits

Author SHA1 Message Date
b76bc4e517 test: add offline crisis resources verification (#98)
All checks were successful
Sanity Checks / sanity-test (pull_request) Successful in 10s
Smoke Test / smoke (pull_request) Successful in 24s
Verifies:
- Service worker precaches crisis-offline.html
- Offline page has 988 and Crisis Text Line links
- Offline page has local crisis resources
- Page is self-contained (no external deps)
- Offline fallback path is configured

Closes #98
2026-04-15 03:28:40 +00:00
5d1d0dc838 feat: add local crisis resources to offline page (#98)
Added a 'More crisis lines' section with:
- National Domestic Violence Hotline
- Trevor Project (LGBTQ youth)
- Veterans Crisis Line
- SAMHSA Helpline (substance use)
- Trans Lifeline

All are free, confidential, and available 24/7.
Closes #98
2026-04-15 03:28:38 +00:00
4 changed files with 84 additions and 164 deletions

View File

@@ -206,6 +206,18 @@
</section>
</div>
<section class="panel" aria-labelledby="resources-title">
<h2 class="section-title" id="resources-title">More crisis lines</h2>
<ul>
<li><strong>National Domestic Violence Hotline</strong> — call 1-800-799-7233 or text START to 88788</li>
<li><strong>Trevor Project</strong> (LGBTQ youth) — call 1-866-488-7386 or text START to 678-678</li>
<li><strong>Veterans Crisis Line</strong> — call 988 then press 1, or text 838255</li>
<li><strong>SAMHSA Helpline</strong> (substance use) — call 1-800-662-4357</li>
<li><strong>Trans Lifeline</strong> — call 877-565-8860</li>
</ul>
<p class="small" style="margin-top: 14px;">All lines are free, confidential, and available 24/7.</p>
</section>
<section class="panel" aria-labelledby="hope-title">
<h2 class="section-title" id="hope-title">Stay through the next ten minutes</h2>
<p>Do not solve your whole life right now. Stay for the next breath. Then the next one.</p>

View File

@@ -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",
]

View File

@@ -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()

View File

@@ -0,0 +1,52 @@
"""
Test: offline crisis resources load when network is unavailable.
Verifies that the service worker caches the crisis-offline.html page
and that it serves as the navigation fallback when offline.
"""
import json
import os
import subprocess
import sys
def test_service_worker_precaches_crisis_page():
"""Service worker precache list includes crisis-offline.html."""
sw_path = os.path.join(os.path.dirname(__file__), '..', 'sw.js')
with open(sw_path) as f:
sw_content = f.read()
assert '/crisis-offline.html' in sw_content, "crisis-offline.html must be in PRECACHE_ASSETS"
def test_crisis_offline_page_has_988():
"""Offline page contains 988 call link."""
page_path = os.path.join(os.path.dirname(__file__), '..', 'crisis-offline.html')
with open(page_path) as f:
content = f.read()
assert 'tel:988' in content, "Offline page must have 988 call link"
assert '741741' in content, "Offline page must have Crisis Text Line (741741)"
def test_crisis_offline_page_has_local_resources():
"""Offline page contains additional local crisis resources."""
page_path = os.path.join(os.path.dirname(__file__), '..', 'crisis-offline.html')
with open(page_path) as f:
content = f.read()
assert 'National Domestic Violence Hotline' in content, "Must include domestic violence hotline"
assert 'Trevor Project' in content, "Must include Trevor Project"
assert 'Veterans Crisis Line' in content, "Must include Veterans Crisis Line"
def test_crisis_offline_page_self_contained():
"""Offline page must work without external resources (inline styles, no external scripts)."""
page_path = os.path.join(os.path.dirname(__file__), '..', 'crisis-offline.html')
with open(page_path) as f:
content = f.read()
# No external CSS files
assert 'rel="stylesheet"' not in content, "Offline page must not depend on external stylesheets"
# No external JS files
assert '<script src=' not in content, "Offline page must not depend on external scripts"
def test_offline_fallback_path_configured():
"""Service worker configures crisis-offline.html as the offline fallback."""
sw_path = os.path.join(os.path.dirname(__file__), '..', 'sw.js')
with open(sw_path) as f:
sw_content = f.read()
assert "OFFLINE_FALLBACK_PATH" in sw_content, "Must define OFFLINE_FALLBACK_PATH"
assert "crisis-offline" in sw_content, "Fallback must reference crisis-offline.html"