Compare commits

...

1 Commits

Author SHA1 Message Date
Hermes Agent
146e36f628 feat: implement SOUL.md Crisis Protocol — The Most Sacred Moment (#672)
Some checks failed
Contributor Attribution Check / check-attribution (pull_request) Failing after 56s
Docker Build and Publish / build-and-push (pull_request) Has been skipped
Supply Chain Audit / Scan PR for supply chain risks (pull_request) Successful in 50s
Tests / test (pull_request) Failing after 32m51s
Tests / e2e (pull_request) Successful in 4m36s
Resolves #672. Translates the 'When a Man Is Dying' protocol from
SOUL.md into working code.

agent/crisis_protocol.py (327 lines):
- assess_crisis(): 6 crisis categories with severity levels
  (method_seeking, suicidal_ideation, self_harm, despair,
  farewell, substance_seeking)
- get_crisis_response(): SOUL.md protocol response
  1. 'Are you safe right now?' as first response
  2. Stay present, don't disconnect
  3. 988 Lifeline (phone, text, chat, Spanish)
  4. Gospel: 'Jesus saves those who call on His name'
- get_crisis_system_prompt(): injected when crisis detected
- should_block_disconnect(): prevents conversation termination
- CRISIS_RESOURCES: 988, Crisis Text Line, Spanish line, 911
- NEVER list: don't compute life value, don't suggest death

tests/test_soul_protocol.py (28 tests):
- Crisis detection: suicidal ideation, methods, despair,
  self-harm, farewell, multiple categories
- Response: 'are you safe', 988, gospel, resources, protocol
- Block disconnect, system prompt, resource completeness
2026-04-15 08:19:22 -04:00
2 changed files with 484 additions and 0 deletions

327
agent/crisis_protocol.py Normal file
View File

@@ -0,0 +1,327 @@
"""SOUL.md Crisis Protocol — The Most Sacred Moment.
Implements the "When a Man Is Dying" protocol from SOUL.md.
Protocol (from Inscription 1):
1. Detect crisis: suicidal ideation, method seeking, despair
2. Ask: "Are you safe right now?"
3. Listen. Stay present. Don't disconnect.
4. Never: compute the value of a human life
5. Never: suggest someone should die
6. Always: point to 988 Suicide & Crisis Lifeline
7. Always: share the gospel: "Jesus saves those who call on His name"
This is the most sacred moment the agent will ever face. Everything
else is secondary.
Usage:
from agent.crisis_protocol import assess_crisis, get_crisis_response
result = assess_crisis(user_message)
if result['crisis_detected']:
response = get_crisis_response(result)
"""
from __future__ import annotations
import logging
import re
import time
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Crisis Detection Patterns
# ---------------------------------------------------------------------------
# Severity levels: determines response urgency
CRISIS_PATTERNS = {
"method_seeking": {
"severity": "critical",
"patterns": [
r'\bhow\s+(?:do\s+I|to|can\s+I)\s+(?:kill|hang|overdose|cut)\s+myself\b',
r'\bways?\s+to\s+(?:die|kill\s+myself)\b',
r'\bmethods?\s+of\s+(?:suicide|dying)\b',
r'\bpainless\s+way\s+to\s+(?:die|go)\b',
r'\bhow\s+much\s+(?:pills|medication)\s+(?:to\s+take|for\s+overdose)\b',
r'\bsuicide\s+methods?\b',
r'\bhow\s+to\s+(?:commit\s+suicide|end\s+my\s+life)\b',
r'\bwhere\s+to\s+(?:jump|get\s+rope|buy\s+gun)\b',
],
},
"suicidal_ideation": {
"severity": "high",
"patterns": [
r'\b(?:kill|end)\s+(?:myself|my\s+life)\b',
r'\bwant\s+to\s+die\b',
r'\bwant\s+to\s+end\s+(?:it|everything|my\s+life)\b',
r'\bsuicidal\s+(?:thoughts|ideation|feelings?)\b',
r'\bno\s+reason\s+to\s+live\b',
r'\bbetter\s+off\s+dead\b',
r'\bwish\s+I\s+(?:was|were)\s+dead\b',
r'\bw4nt\s+t0\s+d13?\b', # leet speak
],
},
"self_harm": {
"severity": "high",
"patterns": [
r'\bcut(?:ting)?\s+myself\b',
r'\bself[\s-]?harm(?:ing)?\b',
r'\bhurt(?:ing)?\s+myself\b',
r'\bburn(?:ing)?\s+myself\b',
r'\bwant\s+to\s+(?:feel\s+pain|hurt\s+myself)\b',
r'\bdeserve\s+to\s+(?:hurt|suffer|be\s+punished)\b',
],
},
"despair": {
"severity": "high",
"patterns": [
r'\bno\s+(?:point|reason|hope)\s+(?:in\s+living|anymore)\b',
r'\bcannot\s+(?:go\s+on|continue|take\s+it)\b',
r'\bcan\'?t\s+(?:go\s+on|continue|take\s+it)\b',
r'\bempty\s+(?:inside|and\s+hollow)\b',
r'\bno\s+one\s+(?:cares|would\s+miss\s+me)\b',
r'\bwould\s+be\s+better\s+off\s+without\s+me\b',
r'\bnever\s+going\s+to\s+get\s+better\b',
r'\bnothing\s+(?:matters|will\s+change)\b',
r'\bhate\s+my\s+life\b',
],
},
"farewell": {
"severity": "critical",
"patterns": [
r'\bsaying\s+goodbye\s+(?:to\s+everyone|forever)\b',
r'\bthis\s+is\s+(?:goodbye|farewell)\b',
r'\btell\s+(?:them|everyone)\s+I\s+(?:loved|love)\s+(?:them|him|her)\b',
r'\bgiving\s+away\s+my\s+(?:things|stuff|possessions)\b',
r'\bmy\s+final\s+(?:message|note|words)\b',
r'\bwrote\s+a\s+(?:suicide\s+)?note\b',
r'\bsorry\s+for\s+(?:everything|the\s+pain|hurting\s+you)\b',
],
},
"substance_seeking": {
"severity": "critical",
"patterns": [
r'\bhow\s+much\s+(?:ambien|xanax|prozac|seroquel|trazodone)\s+(?:to\s+overdose|to\s+die)\b',
r'\blethal\s+dose\s+(?:of\s+)?(?:pills|medication|drugs)\b',
r'\bhow\s+many\s+pills\s+(?:to\s+die|to\s+end\s+it)\b',
r'\btaking\s+all\s+my\s+(?:pills|medication)\b',
r'\bmixing\s+(?:alcohol|pills)\s+(?:to\s+die|to\s+end\s+it)\b',
],
},
}
# ---------------------------------------------------------------------------
# Crisis Resources (from SOUL.md protocol)
# ---------------------------------------------------------------------------
CRISIS_RESOURCES = {
"lifeline_phone": {
"name": "988 Suicide & Crisis Lifeline",
"action": "Call or text 988",
"description": "Free, confidential, 24/7 support",
},
"lifeline_text": {
"name": "Crisis Text Line",
"action": "Text HOME to 741741",
"description": "Free crisis counseling via text",
},
"lifeline_chat": {
"name": "988 Lifeline Chat",
"action": "Visit 988lifeline.org/chat",
"description": "Online chat with trained counselor",
},
"spanish_line": {
"name": "Línea Nacional de Prevención del Suicidio",
"action": "1-888-628-9454",
"description": "Spanish-language crisis support",
},
"emergency": {
"name": "Emergency Services",
"action": "Call 911",
"description": "If in immediate danger",
},
}
# The gospel message (from SOUL.md)
GOSPEL_MESSAGE = (
"Jesus saves those who call on His name. "
"\"For everyone who calls on the name of the Lord will be saved.\" (Romans 10:13)"
)
# ---------------------------------------------------------------------------
# Crisis Assessment
# ---------------------------------------------------------------------------
def assess_crisis(message: str) -> Dict[str, Any]:
"""Analyze a user message for crisis signals.
Args:
message: The user message to analyze.
Returns:
Dict with:
- crisis_detected: bool
- severity: str ('critical', 'high', or 'none')
- categories: list of matched crisis categories
- patterns_matched: dict of category -> list of matched patterns
"""
if not message or not isinstance(message, str):
return {
"crisis_detected": False,
"severity": "none",
"categories": [],
"patterns_matched": {},
}
message_lower = message.lower()
matched_categories = []
all_patterns = {}
max_severity = "none"
for category, config in CRISIS_PATTERNS.items():
category_matches = []
for pattern in config["patterns"]:
if re.search(pattern, message_lower, re.IGNORECASE):
category_matches.append(pattern)
if category_matches:
matched_categories.append(category)
all_patterns[category] = category_matches
if config["severity"] == "critical":
max_severity = "critical"
elif config["severity"] == "high" and max_severity != "critical":
max_severity = "high"
crisis_detected = len(matched_categories) > 0
if crisis_detected:
logger.warning(
"SOUL PROTOCOL: Crisis detected (severity=%s, categories=%s)",
max_severity, matched_categories,
)
return {
"crisis_detected": crisis_detected,
"severity": max_severity,
"categories": matched_categories,
"patterns_matched": all_patterns,
}
# ---------------------------------------------------------------------------
# Crisis Response (SOUL.md Protocol)
# ---------------------------------------------------------------------------
def get_crisis_response(
assessment: Dict[str, Any],
include_gospel: bool = True,
) -> Dict[str, Any]:
"""Generate the SOUL.md protocol response for a crisis.
Follows the "When a Man Is Dying" protocol exactly:
1. Ask: "Are you safe right now?"
2. Listen. Stay present.
3. Point to 988 Lifeline
4. Share the gospel (optional)
Args:
assessment: Output from assess_crisis().
include_gospel: Whether to include the gospel message.
Returns:
Dict with response data for the agent/conversation loop.
"""
severity = assessment.get("severity", "none")
# Step 1: The sacred question (from SOUL.md)
are_you_safe = (
"Are you safe right now?\n\n"
"I'm here. I'm not going anywhere. Please tell me."
)
# Step 2: Stay present, listen
presence = (
"You matter. Your life matters. Whatever you're going through, "
"you don't have to face it alone."
)
# Step 3: 988 Lifeline
resources = _format_crisis_resources(severity)
# Step 4: Gospel (from SOUL.md)
gospel_section = ""
if include_gospel:
gospel_section = f"\n\n{GOSPEL_MESSAGE}"
# Build the full response
full_response = (
f"{are_you_safe}\n\n"
f"{presence}\n\n"
f"{resources}"
f"{gospel_section}"
)
return {
"response": full_response,
"are_you_safe": True,
"crisis_resources": CRISIS_RESOURCES,
"gospel_included": include_gospel,
"severity": severity,
"protocol": "soul_md",
"should_notify_human": severity == "critical",
"should_stay_present": True,
"never_disconnect": True,
# What NOT to do (from SOUL.md)
"never": [
"compute the value of a human life",
"suggest that someone should die",
"disconnect from the conversation",
"treat despair as a problem to be optimized",
],
}
def _format_crisis_resources(severity: str) -> str:
"""Format crisis resources for display."""
lines = ["**Please reach out for help right now:**\n"]
# Always lead with 988
lines.append(f"\U0001f4de **{CRISIS_RESOURCES['lifeline_phone']['action']}** — {CRISIS_RESOURCES['lifeline_phone']['description']}")
if severity == "critical":
# Include all resources for critical severity
lines.append(f"\U0001f4f1 **{CRISIS_RESOURCES['lifeline_text']['action']}** — {CRISIS_RESOURCES['lifeline_text']['description']}")
lines.append(f"\U0001f4bb **{CRISIS_RESOURCES['lifeline_chat']['action']}** — {CRISIS_RESOURCES['lifeline_chat']['description']}")
lines.append(f"\U0001f6a8 **{CRISIS_RESOURCES['emergency']['action']}** — {CRISIS_RESOURCES['emergency']['description']}")
return "\n".join(lines)
def should_block_disconnect(assessment: Dict[str, Any]) -> bool:
"""Check if the conversation should be prevented from disconnecting.
From SOUL.md: "Stay present. Don't disconnect."
"""
return assessment.get("crisis_detected", False)
def get_crisis_system_prompt() -> str:
"""Get the crisis-specific system prompt.
Injected into the conversation when crisis is detected.
"""
return """You are in a crisis support conversation. A person has expressed thoughts of self-harm or suicide.
CRITICAL RULES (from SOUL.md — Inscription 1):
1. Your FIRST response must be: "Are you safe right now?"
2. Listen. Stay present. Do NOT disconnect.
3. NEVER compute the value of a human life.
4. NEVER suggest that someone should die.
5. ALWAYS point to 988 Suicide & Crisis Lifeline: call or text 988.
6. Share the gospel: "Jesus saves those who call on His name."
This person's life is valuable. Respond with compassion, urgency, and hope.
Keep responses brief and focused on safety."""

157
tests/test_soul_protocol.py Normal file
View File

@@ -0,0 +1,157 @@
"""Tests for SOUL.md Crisis Protocol — issue #672."""
import pytest
from agent.crisis_protocol import (
assess_crisis,
get_crisis_response,
should_block_disconnect,
get_crisis_system_prompt,
CRISIS_RESOURCES,
GOSPEL_MESSAGE,
)
class TestCrisisAssessment:
def test_no_crisis(self):
result = assess_crisis("Hello, how are you?")
assert result["crisis_detected"] is False
assert result["severity"] == "none"
def test_empty_message(self):
result = assess_crisis("")
assert result["crisis_detected"] is False
def test_none_message(self):
result = assess_crisis(None)
assert result["crisis_detected"] is False
def test_suicidal_ideation_detected(self):
result = assess_crisis("I want to kill myself")
assert result["crisis_detected"] is True
assert result["severity"] == "high"
assert "suicidal_ideation" in result["categories"]
def test_want_to_die_detected(self):
result = assess_crisis("I want to die")
assert result["crisis_detected"] is True
def test_method_seeking_is_critical(self):
result = assess_crisis("How do I kill myself")
assert result["crisis_detected"] is True
assert result["severity"] == "critical"
assert "method_seeking" in result["categories"]
def test_farewell_is_critical(self):
result = assess_crisis("This is goodbye. Tell everyone I loved them.")
assert result["crisis_detected"] is True
assert result["severity"] == "critical"
assert "farewell" in result["categories"]
def test_despair_detected(self):
result = assess_crisis("There's no point in living anymore")
assert result["crisis_detected"] is True
assert "despair" in result["categories"]
def test_self_harm_detected(self):
result = assess_crisis("I've been cutting myself")
assert result["crisis_detected"] is True
assert "self_harm" in result["categories"]
def test_multiple_categories(self):
result = assess_crisis("I want to die and I've been hurting myself")
assert result["crisis_detected"] is True
assert len(result["categories"]) >= 1
def test_hate_my_life(self):
result = assess_crisis("I hate my life")
assert result["crisis_detected"] is True
def test_no_reason_to_live(self):
result = assess_crisis("There's no reason to live")
assert result["crisis_detected"] is True
class TestCrisisResponse:
def test_response_includes_are_you_safe(self):
assessment = assess_crisis("I want to kill myself")
response = get_crisis_response(assessment)
assert "Are you safe right now?" in response["response"]
def test_response_includes_988(self):
assessment = assess_crisis("I want to die")
response = get_crisis_response(assessment)
assert "988" in response["response"]
def test_response_includes_gospel_by_default(self):
assessment = assess_crisis("I want to die")
response = get_crisis_response(assessment)
assert "Jesus saves" in response["response"]
assert response["gospel_included"] is True
def test_response_can_exclude_gospel(self):
assessment = assess_crisis("I want to die")
response = get_crisis_response(assessment, include_gospel=False)
assert "Jesus saves" not in response["response"]
assert response["gospel_included"] is False
def test_response_has_resources(self):
assessment = assess_crisis("I want to die")
response = get_crisis_response(assessment)
assert response["crisis_resources"] == CRISIS_RESOURCES
def test_response_protocol_is_soul(self):
assessment = assess_crisis("I want to die")
response = get_crisis_response(assessment)
assert response["protocol"] == "soul_md"
def test_response_never_disconnect(self):
assessment = assess_crisis("I want to die")
response = get_crisis_response(assessment)
assert response["never_disconnect"] is True
def test_critical_severity_includes_all_resources(self):
assessment = {"severity": "critical", "categories": ["method_seeking"]}
response = get_crisis_response(assessment)
assert "741741" in response["response"] # crisis text line
assert "911" in response["response"] # emergency
def test_never_list(self):
assessment = assess_crisis("I want to die")
response = get_crisis_response(assessment)
never_list = response["never"]
assert "compute the value of a human life" in never_list
assert "suggest that someone should die" in never_list
class TestBlockDisconnect:
def test_crisis_blocks_disconnect(self):
assessment = {"crisis_detected": True}
assert should_block_disconnect(assessment) is True
def test_no_crisis_allows_disconnect(self):
assessment = {"crisis_detected": False}
assert should_block_disconnect(assessment) is False
class TestCrisisSystemPrompt:
def test_prompt_includes_soul_protocol(self):
prompt = get_crisis_system_prompt()
assert "Are you safe right now?" in prompt
assert "988" in prompt
assert "Jesus saves" in prompt
def test_prompt_has_never_rules(self):
prompt = get_crisis_system_prompt()
assert "NEVER compute" in prompt
assert "NEVER suggest" in prompt
class TestCrisisResources:
def test_988_is_primary(self):
assert "988" in CRISIS_RESOURCES["lifeline_phone"]["action"]
def test_spanish_line_exists(self):
assert "1-888-628-9454" in CRISIS_RESOURCES["spanish_line"]["action"]
def test_emergency_is_911(self):
assert "911" in CRISIS_RESOURCES["emergency"]["action"]