Compare commits
1 Commits
fix/136
...
feat/safet
| Author | SHA1 | Date | |
|---|---|---|---|
| cbf2d512c7 |
@@ -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()
|
||||
119
index.html
119
index.html
@@ -739,6 +739,7 @@ html, body {
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button class="btn btn-secondary" id="cancel-safety-plan">Cancel</button>
|
||||
<button class="btn btn-secondary" id="history-safety-plan" style="margin-right:auto;">History</button>
|
||||
<button class="btn btn-primary" id="save-safety-plan">Save Plan</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1202,6 +1203,7 @@ Sovereignty and service always.`;
|
||||
environment: document.getElementById('sp-environment').value
|
||||
};
|
||||
try {
|
||||
_pushPlanVersion(plan);
|
||||
localStorage.setItem('timmy_safety_plan', JSON.stringify(plan));
|
||||
safetyPlanModal.classList.remove('active');
|
||||
_restoreSafetyPlanFocus();
|
||||
@@ -1211,6 +1213,123 @@ Sovereignty and service always.`;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// ===== SAFETY PLAN VERSION HISTORY =====
|
||||
var MAX_HISTORY = 20;
|
||||
|
||||
function _getPlanHistory() {
|
||||
try {
|
||||
var raw = localStorage.getItem('timmy_safety_plan_history');
|
||||
return raw ? JSON.parse(raw) : [];
|
||||
} catch (e) { return []; }
|
||||
}
|
||||
|
||||
function _pushPlanVersion(plan) {
|
||||
var history = _getPlanHistory();
|
||||
var last = history.length > 0 ? history[history.length - 1] : null;
|
||||
// Only save if different from last version
|
||||
if (last && JSON.stringify(last.plan) === JSON.stringify(plan)) return;
|
||||
history.push({ ts: Date.now(), plan: plan });
|
||||
if (history.length > MAX_HISTORY) history = history.slice(-MAX_HISTORY);
|
||||
localStorage.setItem('timmy_safety_plan_history', JSON.stringify(history));
|
||||
}
|
||||
|
||||
function _diffPlans(oldPlan, newPlan) {
|
||||
var fields = ['warningSigns', 'coping', 'distraction', 'help', 'environment'];
|
||||
var labels = { warningSigns: 'Warning signs', coping: 'Coping strategies', distraction: 'Distractions', help: 'People who can help', environment: 'Safe environment' };
|
||||
var diffs = [];
|
||||
fields.forEach(function(f) {
|
||||
var oldVal = (oldPlan[f] || '').trim();
|
||||
var newVal = (newPlan[f] || '').trim();
|
||||
if (oldVal !== newVal) {
|
||||
diffs.push({ field: labels[f], old: oldVal, _new: newVal });
|
||||
}
|
||||
});
|
||||
return diffs;
|
||||
}
|
||||
|
||||
var historyModal = null;
|
||||
|
||||
function _showHistoryModal() {
|
||||
var history = _getPlanHistory();
|
||||
if (history.length === 0) {
|
||||
alert('No saved versions yet.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Create modal if not exists
|
||||
if (!historyModal) {
|
||||
historyModal = document.createElement('div');
|
||||
historyModal.id = 'sp-history-modal';
|
||||
historyModal.className = 'modal-overlay';
|
||||
historyModal.setAttribute('role', 'dialog');
|
||||
historyModal.setAttribute('aria-modal', 'true');
|
||||
historyModal.innerHTML = '<div class="modal-content" style="max-width:600px;max-height:80vh;overflow-y:auto;">' +
|
||||
'<div class="modal-header"><h2>Safety Plan History</h2><button class="close-modal" id="close-sp-history" aria-label="Close">×</button></div>' +
|
||||
'<div class="modal-body" id="sp-history-body"></div>' +
|
||||
'</div>';
|
||||
document.body.appendChild(historyModal);
|
||||
document.getElementById('close-sp-history').addEventListener('click', function() {
|
||||
historyModal.classList.remove('active');
|
||||
});
|
||||
historyModal.addEventListener('click', function(e) {
|
||||
if (e.target === historyModal) historyModal.classList.remove('active');
|
||||
});
|
||||
}
|
||||
|
||||
var body = document.getElementById('sp-history-body');
|
||||
var html = '';
|
||||
for (var i = history.length - 1; i >= 0; i--) {
|
||||
var entry = history[i];
|
||||
var date = new Date(entry.ts);
|
||||
var label = date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});
|
||||
var prev = i > 0 ? history[i - 1].plan : {};
|
||||
var diffs = _diffPlans(prev, entry.plan);
|
||||
|
||||
html += '<div style="border:1px solid #30363d;border-radius:8px;padding:12px;margin-bottom:10px;">';
|
||||
html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">';
|
||||
html += '<strong style="color:#c9d1d9;">v' + (i + 1) + ' — ' + label + '</strong>';
|
||||
html += '<button class="btn btn-secondary sp-restore-btn" data-idx="' + i + '" style="font-size:0.8rem;padding:4px 10px;">Restore</button>';
|
||||
html += '</div>';
|
||||
|
||||
if (diffs.length === 0 && i === 0) {
|
||||
html += '<span style="color:#8b949e;font-size:0.85rem;">Initial version</span>';
|
||||
} else if (diffs.length === 0) {
|
||||
html += '<span style="color:#8b949e;font-size:0.85rem;">No changes from previous</span>';
|
||||
} else {
|
||||
diffs.forEach(function(d) {
|
||||
html += '<div style="margin-bottom:6px;">';
|
||||
html += '<div style="color:#8b949e;font-size:0.8rem;">' + d.field + '</div>';
|
||||
if (d.old) html += '<div style="color:#f85149;font-size:0.85rem;text-decoration:line-through;">' + d.old.substring(0, 120) + '</div>';
|
||||
if (d._new) html += '<div style="color:#3fb950;font-size:0.85rem;">' + d._new.substring(0, 120) + '</div>';
|
||||
html += '</div>';
|
||||
});
|
||||
}
|
||||
html += '</div>';
|
||||
}
|
||||
body.innerHTML = html;
|
||||
|
||||
// Wire restore buttons
|
||||
body.querySelectorAll('.sp-restore-btn').forEach(function(btn) {
|
||||
btn.addEventListener('click', function() {
|
||||
var idx = parseInt(btn.dataset.idx);
|
||||
var plan = history[idx].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 || '';
|
||||
localStorage.setItem('timmy_safety_plan', JSON.stringify(plan));
|
||||
historyModal.classList.remove('active');
|
||||
alert('Restored version ' + (idx + 1) + '.');
|
||||
});
|
||||
});
|
||||
|
||||
historyModal.classList.add('active');
|
||||
}
|
||||
|
||||
document.getElementById('history-safety-plan').addEventListener('click', _showHistoryModal);
|
||||
|
||||
// ===== SAFETY PLAN FOCUS TRAP (fix #65) =====
|
||||
// Focusable elements inside the modal, in tab order
|
||||
var _spFocusableIds = [
|
||||
|
||||
Reference in New Issue
Block a user