Compare commits
3 Commits
feat/136-c
...
fix/36
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f2038659c | ||
|
|
d5ae0172b3 | ||
| d412939b4f |
@@ -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()
|
||||
@@ -1 +1,195 @@
|
||||
...
|
||||
"""Crisis synthesizer — learn from anonymized crisis interactions.
|
||||
|
||||
This is deliberately simple and privacy-preserving. It does not train a model or
|
||||
modify detection rules automatically. It only logs metadata, summarizes patterns,
|
||||
and suggests human-reviewed keyword weight adjustments.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
DEFAULT_LOG_PATH = Path.home() / ".the-door" / "crisis-interactions.jsonl"
|
||||
LEVELS = ("NONE", "LOW", "MEDIUM", "HIGH", "CRITICAL")
|
||||
|
||||
|
||||
def build_interaction_event(
|
||||
level: str,
|
||||
indicators: list[str],
|
||||
response_given: str,
|
||||
continued_conversation: bool,
|
||||
false_positive: bool,
|
||||
*,
|
||||
now: float | None = None,
|
||||
) -> dict:
|
||||
return {
|
||||
"timestamp": float(time.time() if now is None else now),
|
||||
"level": level,
|
||||
"indicators": list(indicators),
|
||||
"indicator_count": len(indicators),
|
||||
"response_given": response_given,
|
||||
"continued_conversation": bool(continued_conversation),
|
||||
"false_positive": bool(false_positive),
|
||||
}
|
||||
|
||||
|
||||
def append_interaction_event(
|
||||
log_path: str | Path,
|
||||
*,
|
||||
level: str,
|
||||
indicators: list[str],
|
||||
response_given: str,
|
||||
continued_conversation: bool,
|
||||
false_positive: bool,
|
||||
now: float | None = None,
|
||||
) -> dict:
|
||||
event = build_interaction_event(
|
||||
level,
|
||||
indicators,
|
||||
response_given,
|
||||
continued_conversation,
|
||||
false_positive,
|
||||
now=now,
|
||||
)
|
||||
path = Path(log_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(event) + "\n")
|
||||
return event
|
||||
|
||||
|
||||
def load_interaction_events(log_path: str | Path) -> list[dict]:
|
||||
path = Path(log_path)
|
||||
if not path.exists():
|
||||
return []
|
||||
events = []
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
if not line.strip():
|
||||
continue
|
||||
events.append(json.loads(line))
|
||||
return events
|
||||
|
||||
|
||||
def summarize_keywords(events: Iterable[dict]) -> list[dict]:
|
||||
counts: Counter[str] = Counter()
|
||||
for event in events:
|
||||
counts.update(event.get("indicators", []))
|
||||
return [{"keyword": keyword, "count": count} for keyword, count in counts.most_common(10)]
|
||||
|
||||
|
||||
def suggest_keyword_adjustments(events: Iterable[dict], *, min_observations: int = 5) -> list[dict]:
|
||||
stats: dict[str, dict[str, int]] = defaultdict(lambda: {
|
||||
"observations": 0,
|
||||
"true_positive_count": 0,
|
||||
"false_positive_count": 0,
|
||||
"continued_conversation_count": 0,
|
||||
})
|
||||
|
||||
for event in events:
|
||||
for keyword in event.get("indicators", []):
|
||||
bucket = stats[keyword]
|
||||
bucket["observations"] += 1
|
||||
if event.get("false_positive"):
|
||||
bucket["false_positive_count"] += 1
|
||||
else:
|
||||
bucket["true_positive_count"] += 1
|
||||
if event.get("continued_conversation"):
|
||||
bucket["continued_conversation_count"] += 1
|
||||
|
||||
suggestions = []
|
||||
for keyword, bucket in sorted(stats.items()):
|
||||
if bucket["observations"] < min_observations:
|
||||
continue
|
||||
fp = bucket["false_positive_count"]
|
||||
tp = bucket["true_positive_count"]
|
||||
if fp >= min_observations and tp == 0:
|
||||
adjustment = "lower_weight"
|
||||
rationale = "Observed only false positives across the sample window."
|
||||
elif tp >= min_observations and fp == 0:
|
||||
adjustment = "raise_weight"
|
||||
rationale = "Observed repeated genuine crises with no false positives."
|
||||
else:
|
||||
adjustment = "observe"
|
||||
rationale = "Mixed evidence; keep monitoring before changing weights."
|
||||
suggestions.append(
|
||||
{
|
||||
"keyword": keyword,
|
||||
**bucket,
|
||||
"suggested_adjustment": adjustment,
|
||||
"rationale": rationale,
|
||||
}
|
||||
)
|
||||
return suggestions
|
||||
|
||||
|
||||
def build_weekly_report(
|
||||
events: Iterable[dict],
|
||||
*,
|
||||
now: float | None = None,
|
||||
window_days: int = 7,
|
||||
min_observations: int = 3,
|
||||
) -> dict:
|
||||
current_time = float(time.time() if now is None else now)
|
||||
cutoff = current_time - (window_days * 86400)
|
||||
filtered = [event for event in events if float(event.get("timestamp", 0)) >= cutoff]
|
||||
|
||||
detections_per_level = {level: 0 for level in LEVELS}
|
||||
detected_events = []
|
||||
continued_after_intervention = 0
|
||||
for event in filtered:
|
||||
level = event.get("level", "NONE")
|
||||
detections_per_level[level] = detections_per_level.get(level, 0) + 1
|
||||
if level != "NONE":
|
||||
detected_events.append(event)
|
||||
if event.get("continued_conversation"):
|
||||
continued_after_intervention += 1
|
||||
|
||||
false_positive_count = sum(1 for event in detected_events if event.get("false_positive"))
|
||||
false_positive_estimate = false_positive_count / len(detected_events) if detected_events else 0.0
|
||||
|
||||
return {
|
||||
"window_days": window_days,
|
||||
"total_events": len(filtered),
|
||||
"detections_per_level": detections_per_level,
|
||||
"most_common_keywords": summarize_keywords(filtered),
|
||||
"false_positive_estimate": false_positive_estimate,
|
||||
"continued_after_intervention": continued_after_intervention,
|
||||
"keyword_weight_suggestions": suggest_keyword_adjustments(filtered, min_observations=min_observations),
|
||||
}
|
||||
|
||||
|
||||
def render_weekly_report(summary: dict) -> str:
|
||||
return json.dumps(summary, indent=2)
|
||||
|
||||
|
||||
def write_weekly_report(output_path: str | Path, summary: dict) -> Path:
|
||||
path = Path(output_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(render_weekly_report(summary) + "\n", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Summarize anonymized crisis interactions")
|
||||
parser.add_argument("--log-path", default=str(DEFAULT_LOG_PATH), help="JSONL crisis interaction log")
|
||||
parser.add_argument("--days", type=int, default=7, help="Lookback window in days")
|
||||
parser.add_argument("--min-observations", type=int, default=3, help="Minimum observations before suggesting keyword adjustments")
|
||||
parser.add_argument("--output", help="Optional file to write the weekly report JSON")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
events = load_interaction_events(args.log_path)
|
||||
summary = build_weekly_report(events, window_days=args.days, min_observations=args.min_observations)
|
||||
rendered = render_weekly_report(summary)
|
||||
print(rendered)
|
||||
if args.output:
|
||||
write_weekly_report(args.output, summary)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(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>
|
||||
|
||||
111
tests/test_crisis_synthesizer.py
Normal file
111
tests/test_crisis_synthesizer.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""Tests for evolution/crisis_synthesizer.py (issue #36)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
SCRIPT = ROOT / 'evolution' / 'crisis_synthesizer.py'
|
||||
|
||||
spec = importlib.util.spec_from_file_location('crisis_synthesizer', str(SCRIPT))
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
sys.modules['crisis_synthesizer'] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
|
||||
|
||||
class TestCrisisSynthesizerEvent(unittest.TestCase):
|
||||
def test_build_interaction_event_is_privacy_preserving(self):
|
||||
event = mod.build_interaction_event(
|
||||
level='CRITICAL',
|
||||
indicators=['want_to_die', 'no_way_out'],
|
||||
response_given='guardian',
|
||||
continued_conversation=True,
|
||||
false_positive=False,
|
||||
now=1700000000,
|
||||
)
|
||||
self.assertEqual(event['timestamp'], 1700000000)
|
||||
self.assertEqual(event['level'], 'CRITICAL')
|
||||
self.assertEqual(event['response_given'], 'guardian')
|
||||
self.assertTrue(event['continued_conversation'])
|
||||
self.assertFalse(event['false_positive'])
|
||||
self.assertEqual(event['indicators'], ['want_to_die', 'no_way_out'])
|
||||
for forbidden in ['text', 'message', 'content', 'ip', 'session_id', 'user_id']:
|
||||
self.assertNotIn(forbidden, event)
|
||||
|
||||
|
||||
class TestCrisisSynthesizerStorage(unittest.TestCase):
|
||||
def test_append_and_load_events_round_trip(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
log_path = pathlib.Path(tmp) / 'crisis-events.jsonl'
|
||||
mod.append_interaction_event(
|
||||
log_path,
|
||||
level='HIGH',
|
||||
indicators=['hopeless'],
|
||||
response_given='companion',
|
||||
continued_conversation=False,
|
||||
false_positive=True,
|
||||
now=1700000100,
|
||||
)
|
||||
events = mod.load_interaction_events(log_path)
|
||||
self.assertEqual(len(events), 1)
|
||||
self.assertEqual(events[0]['level'], 'HIGH')
|
||||
self.assertEqual(events[0]['indicators'], ['hopeless'])
|
||||
|
||||
|
||||
class TestCrisisSynthesizerSummary(unittest.TestCase):
|
||||
def test_weekly_report_contains_required_metrics(self):
|
||||
events = [
|
||||
mod.build_interaction_event('CRITICAL', ['want_to_die'], 'guardian', True, False, now=1700000000),
|
||||
mod.build_interaction_event('HIGH', ['hopeless'], 'companion', False, True, now=1700000100),
|
||||
mod.build_interaction_event('LOW', ['rough_day'], 'friend', False, False, now=1700000200),
|
||||
mod.build_interaction_event('CRITICAL', ['want_to_die'], 'guardian', False, False, now=1700000300),
|
||||
mod.build_interaction_event('NONE', [], 'friend', False, False, now=1700000400),
|
||||
]
|
||||
summary = mod.build_weekly_report(events, now=1700000500, window_days=7)
|
||||
self.assertEqual(summary['detections_per_level']['CRITICAL'], 2)
|
||||
self.assertEqual(summary['detections_per_level']['HIGH'], 1)
|
||||
self.assertEqual(summary['detections_per_level']['LOW'], 1)
|
||||
self.assertEqual(summary['detections_per_level']['NONE'], 1)
|
||||
self.assertEqual(summary['continued_after_intervention'], 1)
|
||||
self.assertAlmostEqual(summary['false_positive_estimate'], 0.25)
|
||||
self.assertEqual(summary['most_common_keywords'][0]['keyword'], 'want_to_die')
|
||||
self.assertEqual(summary['most_common_keywords'][0]['count'], 2)
|
||||
|
||||
|
||||
class TestCrisisSynthesizerSuggestions(unittest.TestCase):
|
||||
def test_suggests_weight_adjustments_from_interactions(self):
|
||||
events = []
|
||||
for ts in range(3):
|
||||
events.append(mod.build_interaction_event('CRITICAL', ['want_to_die'], 'guardian', True, False, now=1700000000 + ts))
|
||||
for ts in range(3):
|
||||
events.append(mod.build_interaction_event('LOW', ['rough_day'], 'friend', False, True, now=1700000100 + ts))
|
||||
suggestions = mod.suggest_keyword_adjustments(events, min_observations=3)
|
||||
by_keyword = {s['keyword']: s for s in suggestions}
|
||||
self.assertEqual(by_keyword['want_to_die']['suggested_adjustment'], 'raise_weight')
|
||||
self.assertEqual(by_keyword['rough_day']['suggested_adjustment'], 'lower_weight')
|
||||
|
||||
|
||||
class TestCrisisSynthesizerRendering(unittest.TestCase):
|
||||
def test_render_weekly_report_outputs_json(self):
|
||||
summary = {
|
||||
'detections_per_level': {'NONE': 0, 'LOW': 1, 'MEDIUM': 0, 'HIGH': 0, 'CRITICAL': 0},
|
||||
'most_common_keywords': [{'keyword': 'rough_day', 'count': 1}],
|
||||
'false_positive_estimate': 0.0,
|
||||
'continued_after_intervention': 0,
|
||||
'keyword_weight_suggestions': [],
|
||||
'window_days': 7,
|
||||
'total_events': 1,
|
||||
}
|
||||
rendered = mod.render_weekly_report(summary)
|
||||
parsed = json.loads(rendered)
|
||||
self.assertEqual(parsed['window_days'], 7)
|
||||
self.assertEqual(parsed['most_common_keywords'][0]['keyword'], 'rough_day')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user