Compare commits

..

1 Commits

Author SHA1 Message Date
Alexander Whitestone
32dff947cc feat: add GENOME.md - full codebase analysis of the-door (#673)
All checks were successful
Sanity Checks / sanity-test (pull_request) Successful in 5s
Smoke Test / smoke (pull_request) Successful in 12s
2026-04-17 02:05:39 -04:00
3 changed files with 124 additions and 115 deletions

124
GENOME.md Normal file
View 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.

View File

@@ -681,7 +681,6 @@ html, body {
<!-- Footer -->
<footer id="footer">
<a href="/about.html" aria-label="About The Door">about</a>
<button id="crisis-resources-btn" aria-label="Open crisis resources">crisis resources</button>
<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>
@@ -812,7 +811,6 @@ Sovereignty and service always.`;
var overlayCallLink = document.querySelector('.overlay-call');
var statusDot = document.querySelector('.status-dot');
var statusText = document.getElementById('status-text');
var crisisResourcesBtn = document.getElementById('crisis-resources-btn');
// Safety Plan Elements
var safetyPlanBtn = document.getElementById('safety-plan-btn');
@@ -828,9 +826,6 @@ Sovereignty and service always.`;
var isStreaming = false;
var overlayTimer = null;
var crisisPanelShown = false;
var CRISIS_OVERLAY_COOLDOWN_MS = 10 * 60 * 1000;
var CRISIS_OVERLAY_LAST_SHOWN_KEY = 'timmy_crisis_overlay_last_shown_at';
var CRISIS_OVERLAY_EVENT_LOG_KEY = 'timmy_crisis_overlay_event_log';
// ===== SERVICE WORKER =====
if ('serviceWorker' in navigator) {
@@ -858,43 +853,6 @@ Sovereignty and service always.`;
window.addEventListener('offline', updateOnlineStatus);
updateOnlineStatus();
function getLastOverlayShownAt() {
try {
return parseInt(localStorage.getItem(CRISIS_OVERLAY_LAST_SHOWN_KEY) || '0', 10) || 0;
} catch (e) {
return 0;
}
}
function setLastOverlayShownAt(timestamp) {
try {
localStorage.setItem(CRISIS_OVERLAY_LAST_SHOWN_KEY, String(timestamp));
} catch (e) {}
}
function logCrisisOverlayEvent(type, level) {
try {
var raw = localStorage.getItem(CRISIS_OVERLAY_EVENT_LOG_KEY);
var events = raw ? JSON.parse(raw) : [];
if (!Array.isArray(events)) events = [];
events.push({ type: type, level: level, at: Date.now() });
if (events.length > 20) events = events.slice(events.length - 20);
localStorage.setItem(CRISIS_OVERLAY_EVENT_LOG_KEY, JSON.stringify(events));
} catch (e) {}
}
function openCrisisResources() {
crisisPanelShown = true;
crisisPanel.classList.add('visible');
if (typeof crisisPanel.scrollIntoView === 'function') {
crisisPanel.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
var firstAction = crisisPanel.querySelector('.crisis-btn, a[href]');
if (firstAction && typeof firstAction.focus === 'function') {
firstAction.focus();
}
}
// ===== CRISIS KEYWORDS =====
// Tier 1: General crisis indicators - triggers enhanced 988 panel
var crisisKeywords = [
@@ -1063,19 +1021,6 @@ Sovereignty and service always.`;
var _preOverlayFocusElement = null;
function showOverlay() {
return showOverlayWithRateLimit(false, 2);
}
function showOverlayWithRateLimit(forceOpen, level) {
var lastShownAt = getLastOverlayShownAt();
if (!forceOpen && Date.now() - lastShownAt < CRISIS_OVERLAY_COOLDOWN_MS) {
logCrisisOverlayEvent('suppressed', level || 2);
return false;
}
logCrisisOverlayEvent(forceOpen ? 'manual-open' : 'shown', level || 2);
setLastOverlayShownAt(Date.now());
// Save current focus for restoration on dismiss
_preOverlayFocusElement = document.activeElement;
@@ -1108,7 +1053,6 @@ Sovereignty and service always.`;
// Focus the Call 988 link (always enabled) — disabled buttons cannot receive focus
if (overlayCallLink) overlayCallLink.focus();
return true;
}
// Register focus trap on document (always listening, gated by class check)
@@ -1357,12 +1301,6 @@ Sovereignty and service always.`;
});
}
if (crisisResourcesBtn) {
crisisResourcesBtn.addEventListener('click', function() {
openCrisisResources();
});
}
// ===== TEXTAREA AUTO-RESIZE =====
msgInput.addEventListener('input', function() {
this.style.height = 'auto';

View File

@@ -1,53 +0,0 @@
import pathlib
import re
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
INDEX_HTML = ROOT / 'index.html'
class TestCrisisOverlayRateLimit(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.html = INDEX_HTML.read_text()
def test_overlay_has_ten_minute_cooldown_constant(self):
self.assertRegex(
self.html,
r"CRISIS_OVERLAY_COOLDOWN_MS\s*=\s*10\s*\*\s*60\s*\*\s*1000",
'Expected a 10-minute crisis overlay cooldown constant.',
)
def test_show_overlay_suppresses_repeat_with_logging(self):
self.assertRegex(
self.html,
r"function\s+logCrisisOverlayEvent\s*\(",
'Expected a crisis overlay event logger.',
)
self.assertRegex(
self.html,
r"if\s*\(!forceOpen\s*&&\s*Date\.now\(\)\s*-\s*lastShownAt\s*<\s*CRISIS_OVERLAY_COOLDOWN_MS\)",
'Expected showOverlay to suppress repeated auto-displays inside the cooldown window.',
)
self.assertRegex(
self.html,
r"logCrisisOverlayEvent\('suppressed'",
'Expected suppressed overlay attempts to be logged.',
)
def test_manual_crisis_resources_button_exists_and_bypasses_cooldown(self):
self.assertIn('id="crisis-resources-btn"', self.html)
self.assertRegex(
self.html,
r"function\s+openCrisisResources\s*\(",
'Expected a manual crisis resources opener.',
)
self.assertRegex(
self.html,
r"crisisResourcesBtn\.addEventListener\('click',\s*function\(\)\s*\{\s*openCrisisResources\(\);",
'Expected the footer button to wire into openCrisisResources().',
)
if __name__ == '__main__':
unittest.main()