Compare commits

..

1 Commits

Author SHA1 Message Date
bf5526c610 feat: Safety plan version history with diff view (#96)
All checks were successful
Sanity Checks / sanity-test (pull_request) Successful in 10s
Smoke Test / smoke (pull_request) Successful in 16s
- Store up to 20 plan versions in localStorage
- Migrate legacy single-plan format automatically
- History button in plan modal footer
- Diff view: additions (green) / deletions (red) between versions
- Restore any previous version with one click
- No PII leaves the device
2026-04-15 03:39:12 +00:00
2 changed files with 164 additions and 86 deletions

View File

@@ -1,75 +0,0 @@
# GENOME.md — the-door
**Generated:** 2026-04-14
**Repo:** Timmy_Foundation/the-door
**Description:** Crisis Front Door — a single URL where a man at 3am can talk to Timmy. No login, no signup. 988 always visible.
---
## Project Overview
The-door is a crisis intervention web application — the most sacred surface in the Timmy Foundation. When a man at 3am reaches the end of his road, this is where he lands. No login, no signup, no barriers. 988 Suicide and Crisis Lifeline always visible. The "When a Man Is Dying" protocol active on every page.
## Architecture
```
the-door/
├── index.html # Main crisis page (PWA-capable)
├── crisis-offline.html # Offline fallback (service worker cached)
├── about.html # About page
├── testimony.html # Testimony/stories page
├── sw.js # Service worker (offline-first)
├── manifest.json # PWA manifest
├── crisis/ # Core crisis detection + response
│ ├── detect.py # Keyword/pattern detection (4 tiers)
│ ├── gateway.py # API endpoints, prompt injection
│ ├── response.py # Response generation, 988 routing
│ ├── compassion_router.py # Profile-based response routing
│ ├── profiles.py # Compassion profiles
│ └── PROTOCOL.md # The protocol (SOUL.md reference)
├── crisis_detector.py # Legacy shim → crisis/detect.py
├── crisis_responder.py # Legacy responder
├── dying_detection/ # Deprecated module
├── evolution/ # Crisis synthesizer (creative)
├── tests/ # Safety-critical tests
│ ├── test_crisis_overlay_focus_trap.py
│ ├── test_dying_detection_deprecation.py
│ └── test_false_positive_fixes.py
└── deploy/ # Deployment docs
```
## Key Abstractions
| Module | Purpose |
|---|---|
| `crisis/detect.py` | 4-tier detection: LOW/MEDIUM/HIGH/CRITICAL via regex patterns |
| `crisis/gateway.py` | HTTP API, Sovereign Heart prompt injection |
| `crisis/response.py` | Response generation, 988 integration, escalation |
| `crisis/compassion_router.py` | Profile-based routing (different crisis types) |
| `sw.js` | Service worker for offline-first PWA |
## Safety Constraints
- **The-door never auto-closes PRs** (in fleet-ops exempt list)
- **988 always visible** on every page, even offline
- **When a Man Is Dying protocol** active on every interaction
- **No login/signup** — zero barriers to crisis support
- **Offline-first** — service worker caches critical pages
## Test Coverage
| Test | Coverage |
|---|---|
| Crisis overlay focus trap | ✅ |
| Dying detection deprecation | ✅ |
| False positive fixes | ✅ |
| Crisis detection tiers | ❌ (in crisis/tests.py) |
| Response generation | ❌ |
| Offline service worker | ❌ |
## Security
- No user data stored (crisis intervention is stateless by design)
- No cookies, no tracking, no analytics
- Service worker only caches static assets
- Crisis detection runs client-side where possible

View File

@@ -739,11 +739,25 @@ html, body {
</div>
<div class="modal-footer">
<button class="btn btn-secondary" id="cancel-safety-plan">Cancel</button>
<button class="btn btn-secondary" id="show-version-history" title="View previous versions">History</button>
<button class="btn btn-primary" id="save-safety-plan">Save Plan</button>
</div>
</div>
</div>
<!-- Safety Plan Version History Modal -->
<div id="version-history-modal" class="modal-overlay" role="dialog" aria-modal="true" aria-labelledby="vh-title">
<div class="modal-content" style="max-width: 640px;">
<div class="modal-header">
<h2 id="vh-title">Safety Plan History</h2>
<button class="close-modal" id="close-version-history" aria-label="Close history">&times;</button>
</div>
<div class="modal-body" id="vh-body" style="max-height: 400px; overflow-y: auto;">
<p id="vh-empty" style="color: #8b949e;">No previous versions saved.</p>
</div>
</div>
</div>
<script>
(function() {
'use strict';
@@ -1169,17 +1183,40 @@ Sovereignty and service always.`;
});
// ===== SAFETY PLAN LOGIC =====
// Safety plan version storage key
var SP_STORAGE_KEY = 'timmy_safety_plan_versions';
function _getPlanVersions() {
try {
var raw = localStorage.getItem(SP_STORAGE_KEY);
if (raw) return JSON.parse(raw);
// Migrate legacy single-plan format
var legacy = localStorage.getItem('timmy_safety_plan');
if (legacy) {
var plan = JSON.parse(legacy);
var versions = [{ plan: plan, timestamp: new Date().toISOString(), label: 'Migrated' }];
localStorage.setItem(SP_STORAGE_KEY, JSON.stringify(versions));
localStorage.removeItem('timmy_safety_plan');
return versions;
}
} catch (e) {}
return [];
}
function _setPlanVersions(versions) {
localStorage.setItem(SP_STORAGE_KEY, JSON.stringify(versions));
}
function loadSafetyPlan() {
try {
var saved = localStorage.getItem('timmy_safety_plan');
if (saved) {
var plan = JSON.parse(saved);
document.getElementById('sp-warning-signs').value = plan.warningSigns || '';
document.getElementById('sp-coping').value = plan.coping || '';
document.getElementById('sp-distraction').value = plan.distraction || '';
document.getElementById('sp-help').value = plan.help || '';
document.getElementById('sp-environment').value = plan.environment || '';
}
var versions = _getPlanVersions();
if (versions.length === 0) return;
var plan = versions[versions.length - 1].plan;
document.getElementById('sp-warning-signs').value = plan.warningSigns || '';
document.getElementById('sp-coping').value = plan.coping || '';
document.getElementById('sp-distraction').value = plan.distraction || '';
document.getElementById('sp-help').value = plan.help || '';
document.getElementById('sp-environment').value = plan.environment || '';
} catch (e) {}
}
@@ -1202,10 +1239,13 @@ Sovereignty and service always.`;
environment: document.getElementById('sp-environment').value
};
try {
localStorage.setItem('timmy_safety_plan', JSON.stringify(plan));
var versions = _getPlanVersions();
versions.push({ plan: plan, timestamp: new Date().toISOString(), label: 'Saved' });
if (versions.length > 20) versions = versions.slice(-20);
_setPlanVersions(versions);
safetyPlanModal.classList.remove('active');
_restoreSafetyPlanFocus();
alert('Safety plan saved locally.');
alert('Safety plan saved. Version ' + versions.length + ' of 20.');
} catch (e) {
alert('Error saving plan.');
}
@@ -1299,6 +1339,119 @@ Sovereignty and service always.`;
});
}
// ===== SAFETY PLAN VERSION HISTORY =====
var versionHistoryModal = document.getElementById('version-history-modal');
var showVersionHistoryBtn = document.getElementById('show-version-history');
var closeVersionHistoryBtn = document.getElementById('close-version-history');
var vhBody = document.getElementById('vh-body');
var SP_FIELDS = [
{ key: 'warningSigns', label: 'Warning signs' },
{ key: 'coping', label: 'Coping strategies' },
{ key: 'distraction', label: 'People/Places for distraction' },
{ key: 'help', label: 'People I can ask for help' },
{ key: 'environment', label: 'Making my environment safe' }
];
function _diffPlans(oldPlan, newPlan) {
var changes = [];
for (var i = 0; i < SP_FIELDS.length; i++) {
var f = SP_FIELDS[i];
var ov = (oldPlan[f.key] || '').trim();
var nv = (newPlan[f.key] || '').trim();
if (ov !== nv) changes.push({ label: f.label, old: ov, new: nv });
}
return changes;
}
function _renderVersionHistory() {
var versions = _getPlanVersions();
vhBody.innerHTML = '';
if (versions.length === 0) {
vhBody.innerHTML = '<p style="color:#8b949e;">No previous versions saved.</p>';
return;
}
for (var i = versions.length - 1; i >= 0; i--) {
var v = versions[i];
var ts = new Date(v.timestamp).toLocaleString();
var card = document.createElement('div');
card.style.cssText = 'border:1px solid #30363d;border-radius:8px;padding:12px;margin-bottom:8px;';
var header = document.createElement('div');
header.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;';
var label = document.createElement('strong');
label.textContent = 'v' + (i + 1) + ' — ' + ts;
header.appendChild(label);
var restoreBtn = document.createElement('button');
restoreBtn.textContent = 'Restore';
restoreBtn.className = 'btn btn-secondary';
restoreBtn.style.cssText = 'padding:2px 10px;font-size:0.8rem;';
restoreBtn.setAttribute('data-version', i);
restoreBtn.addEventListener('click', function() {
var idx = parseInt(this.getAttribute('data-version'));
var v2 = _getPlanVersions()[idx];
if (!v2) return;
var fields = ['sp-warning-signs', 'sp-coping', 'sp-distraction', 'sp-help', 'sp-environment'];
var keys = ['warningSigns', 'coping', 'distraction', 'help', 'environment'];
for (var j = 0; j < fields.length; j++) {
document.getElementById(fields[j]).value = v2.plan[keys[j]] || '';
}
versionHistoryModal.classList.remove('active');
safetyPlanModal.classList.add('active');
});
header.appendChild(restoreBtn);
card.appendChild(header);
if (i > 0) {
var changes = _diffPlans(versions[i - 1].plan, v.plan);
if (changes.length === 0) {
var noChange = document.createElement('div');
noChange.style.cssText = 'color:#8b949e;font-size:0.85rem;';
noChange.textContent = 'No changes from previous version.';
card.appendChild(noChange);
} else {
for (var c = 0; c < changes.length; c++) {
var ch = changes[c];
var diffDiv = document.createElement('div');
diffDiv.style.cssText = 'margin-bottom:4px;font-size:0.85rem;';
var lbl = document.createElement('div');
lbl.style.color = '#58a6ff';
lbl.textContent = ch.label;
diffDiv.appendChild(lbl);
if (ch.old) {
var del = document.createElement('div');
del.style.cssText = 'color:#f85149;text-decoration:line-through;padding:2px 4px;';
del.textContent = '- ' + ch.old.substring(0, 100);
diffDiv.appendChild(del);
}
if (ch.new) {
var add = document.createElement('div');
add.style.cssText = 'color:#3fb950;padding:2px 4px;';
add.textContent = '+ ' + ch.new.substring(0, 100);
diffDiv.appendChild(add);
}
card.appendChild(diffDiv);
}
}
} else {
var initial = document.createElement('div');
initial.style.cssText = 'color:#8b949e;font-size:0.85rem;';
initial.textContent = 'Initial version.';
card.appendChild(initial);
}
vhBody.appendChild(card);
}
}
showVersionHistoryBtn.addEventListener('click', function() {
safetyPlanModal.classList.remove('active');
_renderVersionHistory();
versionHistoryModal.classList.add('active');
});
closeVersionHistoryBtn.addEventListener('click', function() {
versionHistoryModal.classList.remove('active');
safetyPlanModal.classList.add('active');
});
// ===== TEXTAREA AUTO-RESIZE =====
msgInput.addEventListener('input', function() {
this.style.height = 'auto';