Compare commits
2 Commits
feat/136-c
...
fix/673-ge
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
32dff947cc | ||
| d412939b4f |
124
GENOME.md
Normal file
124
GENOME.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# GENOME.md — the-door
|
||||
|
||||
> Codebase analysis generated 2026-04-13. Crisis intervention web app — a door that's always open.
|
||||
|
||||
## Project Overview
|
||||
|
||||
the-door is a single-URL crisis intervention web app. A man at 3am can talk to Timmy. No login. No signup. No tracking. Just a door that's always open.
|
||||
|
||||
**Mission**: Stand between a broken man and a machine that would tell him to die.
|
||||
|
||||
48 files. Static HTML frontend (<25KB, works on 3G). Python crisis detection backend. Safety-critical — a broken deployment could prevent someone from reaching the 988 Lifeline.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Browser → nginx (SSL) → index.html → /api/* proxy → Hermes Gateway
|
||||
↓
|
||||
crisis/detect.py
|
||||
↓
|
||||
988 Lifeline overlay
|
||||
```
|
||||
|
||||
## Entry Points
|
||||
|
||||
- **index.html** — The entire frontend. One file. <25KB. Works on 3G.
|
||||
- **system-prompt.txt** — Crisis-aware system prompt for the AI.
|
||||
- **deploy/deploy.sh** — Deployment script for VPS.
|
||||
- **deploy/playbook.yml** — Ansible playbook for deployment.
|
||||
- **crisis/detect.py** — Core crisis detection module (canonical).
|
||||
- **crisis_detector.py** — Legacy class API wrapper around detect.py.
|
||||
- **crisis_responder.py** — Response formatting for crisis levels.
|
||||
|
||||
## Data Flow
|
||||
|
||||
```
|
||||
User message → browser
|
||||
↓
|
||||
index.html → client-side crisis keyword scan
|
||||
↓
|
||||
/api/chat → Hermes Gateway
|
||||
↓
|
||||
system-prompt.txt → injected into AI system prompt
|
||||
↓
|
||||
crisis/detect.py → 5-tier classification (NONE/LOW/MEDIUM/HIGH/CRITICAL)
|
||||
↓
|
||||
crisis/response.py → appropriate response with 988 Lifeline info
|
||||
↓
|
||||
Response → browser → crisis overlay if HIGH/CRITICAL
|
||||
```
|
||||
|
||||
## Key Abstractions
|
||||
|
||||
### Crisis Detection (crisis/detect.py)
|
||||
Canonical detection module. Regex-based keyword matching across 4 tiers:
|
||||
- CRITICAL: immediate self-harm risk (single match triggers)
|
||||
- HIGH: strong despair signals (single match triggers)
|
||||
- MEDIUM: distress signals (requires 2+ indicators)
|
||||
- LOW: emotional difficulty (single match)
|
||||
|
||||
Design principles:
|
||||
- Never computes the value of a human life
|
||||
- Never suggests death is a solution
|
||||
- Always errs on side of higher risk
|
||||
|
||||
### Crisis Profiles (crisis/profiles.py)
|
||||
Compassion profiles that shape AI response tone based on crisis level.
|
||||
|
||||
### Session Tracker (crisis/session_tracker.py)
|
||||
Tracks crisis interactions across sessions. Persistent state for ongoing support.
|
||||
|
||||
### Gateway (crisis/gateway.py)
|
||||
HTTP gateway for crisis detection API. Endpoints for scanning text and getting responses.
|
||||
|
||||
### Offline Fallback (crisis-offline.html, sw.js)
|
||||
Service worker caches crisis resources. When network is down, users still see 988 Lifeline info and crisis resources.
|
||||
|
||||
## File Types
|
||||
|
||||
| Type | Count | Purpose |
|
||||
|------|-------|---------|
|
||||
| .py | 16 | Crisis detection, response, tests |
|
||||
| .html | 4 | Frontend, offline fallback, tests |
|
||||
| .yml | 2 | CI workflows |
|
||||
| .sh | 2 | Health check, service restart |
|
||||
| .md | 5 | Documentation, safety audits |
|
||||
|
||||
## Test Coverage
|
||||
|
||||
### Existing Tests
|
||||
- test_crisis_overlay_focus_trap.py — Accessibility: focus trap in crisis overlay
|
||||
- test_dying_detection_deprecation.py — Legacy API deprecation
|
||||
- test_false_positive_fixes.py — Crisis detection false positive resistance
|
||||
- test_service_worker_offline.py — Offline fallback verification
|
||||
- test_session_tracker.py — Session tracking persistence
|
||||
- crisis/test_rescue.py — Rescue flow testing
|
||||
- crisis/tests.py — Core crisis detection tests
|
||||
|
||||
### Coverage Gaps
|
||||
- No integration tests for full browser → API → response → overlay flow
|
||||
- No tests for system-prompt.txt injection into AI system prompt
|
||||
- No load tests (what happens at 1000 concurrent crisis users?)
|
||||
- No tests for deploy.sh idempotency
|
||||
|
||||
### Critical paths that need tests:
|
||||
1. **Full crisis flow**: user message → detection → 988 overlay → response
|
||||
2. **Offline fallback**: network down → service worker → cached crisis resources
|
||||
3. **Deploy safety**: deploy.sh doesn't break running service
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **SAFETY-CRITICAL**: the-door serves users in crisis. Broken deployment could prevent someone from reaching 988 Lifeline.
|
||||
- **PR safety**: the-door PRs NEVER auto-merge. Requires-human label on all PRs. (fleet-ops#183)
|
||||
- **No authentication by design**: no login, no signup, no tracking. Privacy is a safety feature.
|
||||
- **Rate limiting**: deploy/rate-limit.conf prevents abuse while allowing crisis access.
|
||||
- **Offline resilience**: service worker ensures crisis resources available even without network.
|
||||
- **System prompt is safety boundary**: system-prompt.txt defines the AI's crisis behavior. Changes require human review.
|
||||
|
||||
## Design Decisions
|
||||
|
||||
- **Single HTML file**: no build step, no framework, no dependencies. Works on 3G. Loads instantly.
|
||||
- **Client-side detection first**: browser scans for crisis keywords before sending to server. Instant response for critical cases.
|
||||
- **Server-side detection second**: crisis/detect.py provides deeper analysis with tiered classification.
|
||||
- **Offline-first for crisis**: service worker caches crisis resources. Network failure doesn't block access to help.
|
||||
- **No tracking**: privacy protects vulnerable users. No analytics, no cookies, no login.
|
||||
@@ -1,133 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Crisis Metrics CLI — View crisis detection health from the command line.
|
||||
|
||||
Usage:
|
||||
python3 -m crisis.metrics --summary # weekly report
|
||||
python3 -m crisis.metrics --json # raw JSON export
|
||||
python3 -m crisis.metrics --last 24h # last 24 hours
|
||||
|
||||
Ref: #136
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
METRICS_DIR = os.environ.get("CRISIS_METRICS_DIR", str(Path.home() / ".the-door" / "metrics"))
|
||||
|
||||
|
||||
def load_metrics(hours: int = 168) -> List[dict]:
|
||||
"""Load metrics entries from the last N hours."""
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(hours=hours)
|
||||
entries = []
|
||||
metrics_path = Path(METRICS_DIR)
|
||||
|
||||
if not metrics_path.exists():
|
||||
return entries
|
||||
|
||||
for f in sorted(metrics_path.glob("*.json")):
|
||||
try:
|
||||
with open(f) as fh:
|
||||
data = json.load(fh)
|
||||
if isinstance(data, list):
|
||||
entries.extend(data)
|
||||
elif isinstance(data, dict):
|
||||
entries.append(data)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Filter by timestamp
|
||||
filtered = []
|
||||
for e in entries:
|
||||
ts = e.get("timestamp", "")
|
||||
if ts:
|
||||
try:
|
||||
t = datetime.fromisoformat(ts.replace("Z", "+00:00"))
|
||||
if t >= cutoff:
|
||||
filtered.append(e)
|
||||
except Exception:
|
||||
filtered.append(e)
|
||||
|
||||
return filtered
|
||||
|
||||
|
||||
def summarize(entries: List[dict]) -> dict:
|
||||
"""Summarize metrics entries."""
|
||||
total = len(entries)
|
||||
by_level = {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "NONE": 0}
|
||||
escalated = 0
|
||||
deescalated = 0
|
||||
resources_shown = 0
|
||||
|
||||
for e in entries:
|
||||
level = e.get("level", "NONE")
|
||||
by_level[level] = by_level.get(level, 0) + 1
|
||||
if e.get("escalated"):
|
||||
escalated += 1
|
||||
if e.get("deescalation_confirmed"):
|
||||
deescalated += 1
|
||||
if e.get("resources_shown"):
|
||||
resources_shown += 1
|
||||
|
||||
return {
|
||||
"period_hours": 168,
|
||||
"total_interactions": total,
|
||||
"by_level": by_level,
|
||||
"escalated_sessions": escalated,
|
||||
"deescalated_sessions": deescalated,
|
||||
"resources_shown": resources_shown,
|
||||
"crisis_rate": round((by_level["CRITICAL"] + by_level["HIGH"]) / max(total, 1) * 100, 1),
|
||||
}
|
||||
|
||||
|
||||
def print_summary(summary: dict):
|
||||
print(f"\n{'='*50}")
|
||||
print(f" CRISIS METRICS SUMMARY")
|
||||
print(f" {datetime.now().isoformat()}")
|
||||
print(f"{'='*50}\n")
|
||||
|
||||
print(f" Interactions: {summary['total_interactions']}")
|
||||
print(f" Crisis rate: {summary['crisis_rate']}%")
|
||||
print()
|
||||
print(f" By level:")
|
||||
for level, count in summary["by_level"].items():
|
||||
bar = "█" * min(count, 40)
|
||||
print(f" {level:10} {count:5} {bar}")
|
||||
print()
|
||||
print(f" Escalated: {summary['escalated_sessions']}")
|
||||
print(f" De-escalated: {summary['deescalated_sessions']}")
|
||||
print(f" 988 shown: {summary['resources_shown']}")
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description="Crisis Metrics CLI")
|
||||
parser.add_argument("--summary", action="store_true", help="Weekly summary")
|
||||
parser.add_argument("--json", action="store_true", help="JSON export")
|
||||
parser.add_argument("--last", default="168h", help="Time window (e.g., 24h, 7d)")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Parse time window
|
||||
last = args.last
|
||||
if last.endswith("h"):
|
||||
hours = int(last[:-1])
|
||||
elif last.endswith("d"):
|
||||
hours = int(last[:-1]) * 24
|
||||
else:
|
||||
hours = 168
|
||||
|
||||
entries = load_metrics(hours)
|
||||
summary = summarize(entries)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps(summary, indent=2))
|
||||
else:
|
||||
print_summary(summary)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -680,7 +680,7 @@ html, body {
|
||||
|
||||
<!-- Footer -->
|
||||
<footer id="footer">
|
||||
<a href="/about" aria-label="About The Door">about</a>
|
||||
<a href="/about.html" aria-label="About The Door">about</a>
|
||||
<button id="safety-plan-btn" aria-label="Open My Safety Plan">my safety plan</button>
|
||||
<button id="clear-chat-btn" aria-label="Clear chat history">clear chat</button>
|
||||
</footer>
|
||||
|
||||
Reference in New Issue
Block a user