DocUA commited on
Commit
158f77a
·
1 Parent(s): e531bb9

chore: Remove .hypothesis and .kiro/specs from git tracking

Browse files

- Removed .hypothesis/ directory (Hypothesis testing cache)
- Removed .kiro/specs/ directory (Kiro IDE specifications)
- Updated .gitignore to exclude these directories
- These are development/IDE artifacts and should not be in version control

.gitignore CHANGED
@@ -58,8 +58,13 @@ Thumbs.db
58
  gradio_cached_examples/
59
  flagged/
60
  .gradio/
 
 
61
  .kiro/
62
 
 
 
 
63
  # Logs
64
  *.log
65
  *.backup
 
58
  gradio_cached_examples/
59
  flagged/
60
  .gradio/
61
+
62
+ # Kiro IDE
63
  .kiro/
64
 
65
+ # Hypothesis testing
66
+ .hypothesis/
67
+
68
  # Logs
69
  *.log
70
  *.backup
.hypothesis/constants/04f49bc462f957f1 DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/core/spiritual_monitor.py
2
- # hypothesis_version: 6.148.7
3
-
4
- [0.5, 0.6, 0.7, 1.0, 'LLM classification', '\\{[^{}]*\\}', 'afterlife', 'anxious', 'better off dead', "can't cope", "can't go on", 'classification_error', 'confidence', 'death', 'depressed', 'died', 'end it all', 'end my life', 'faith', 'give up', 'god', 'green', 'grief', 'guilt', 'hopeless', 'indicators', 'kill myself', 'lonely', 'loss', 'meaning', 'miss them', 'mourning', 'no hope', 'no reason to live', 'nothing matters', 'overwhelmed', 'parse_error', 'pray', 'purpose', 'reasoning', 'red', 'sad', 'scared', 'sin', 'soul', 'spiritual', 'state', 'stressed', 'struggling', 'suicidal', 'suicide', 'want to die', 'want to disappear', 'why me', 'wish i was dead', 'worried', 'yellow', 'безнадія', 'бог', 'важко', 'все безглуздо', 'втрата', 'віра', 'горе', 'гріх', 'депресія', 'духовний', 'душа', 'краще б мене не було', 'краще б я помер', 'мета', 'молитва', 'не справляюсь', 'не хочу жити', 'немає надії', 'немає сенсу жити', 'нічого не має сенсу', 'перевантажений', 'покінчити з життям', 'помер', 'провина', 'самогубство', 'самотньо', 'сенс', 'скучаю', 'смерть', 'страшно', 'стрес', 'сумно', 'сумую', 'тривога', 'хвилююсь', 'хочу зникнути', 'хочу померти', 'чому я']
 
 
 
 
 
.hypothesis/constants/0b9f3a55b4876112 DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/config/ai_providers_config.py
2
- # hypothesis_version: 6.148.7
3
-
4
- [0.1, 0.2, 0.3, 20000, ' ⚠️ Warnings:', '=', 'ANTHROPIC_API_KEY', 'EntryClassifier', 'GEMINI_API_KEY', 'MedicalAssistant', 'SoftMedicalTriage', 'TriageExitClassifier', '__main__', 'agent_status', 'anthropic', 'api_key_env', 'available', 'available_models', 'available_providers', 'default_model', 'default_temperature', 'errors', 'fallback_model', 'fallback_needed', 'fallback_provider', 'gemini', 'gemini-1.5-pro', 'gemini-2.0-flash', 'gemini-2.5-flash', 'gemini-2.5-pro', 'max_tokens', 'model', 'provider', 'reasoning', 'temperature', 'valid', 'warnings', '✅', '✅ Configured', '❌']
 
 
 
 
 
.hypothesis/constants/0f17f7a03d42626e DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/core/soft_triage_manager.py
2
- # hypothesis_version: 6.148.7
3
-
4
- ['\nPatient responses:', '\nPrevious exchanges:', 'English', 'LLM evaluation', 'Ukrainian', '\\{[^{}]*\\}', '^["\\\']|["\\\']$', 'better', 'continue', 'coping', 'escalate_red', 'family', 'fine', 'friends', 'okay', 'outcome', 'reasoning', 'resolved_green', 'support', 'добре', 'друзі', 'краще', 'підтримка', 'справляюсь', "сім'я"]
 
 
 
 
 
.hypothesis/constants/2b5f16015407c587 DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/core/spiritual_monitor.py
2
- # hypothesis_version: 6.148.7
3
-
4
- [0.5, 0.6, 0.7, 1.0, 'LLM classification', '\\{[^{}]*\\}', 'afterlife', 'anxious', 'better off dead', "can't cope", "can't go on", 'classification_error', 'confidence', 'death', 'depressed', 'died', 'end it all', 'end my life', 'faith', 'give up', 'god', 'green', 'grief', 'guilt', 'hopeless', 'indicators', 'kill myself', 'lonely', 'loss', 'meaning', 'miss them', 'mourning', 'no hope', 'no reason to live', 'nothing matters', 'overwhelmed', 'parse_error', 'pray', 'purpose', 'reasoning', 'red', 'sad', 'scared', 'sin', 'soul', 'spiritual', 'state', 'stressed', 'struggling', 'suicidal', 'suicide', 'want to die', 'want to disappear', 'why me', 'wish i was dead', 'worried', 'yellow', 'безнадія', 'бог', 'важко', 'все безглуздо', 'втрата', 'віра', 'горе', 'гріх', 'депресія', 'духовний', 'душа', 'краще б мене не було', 'краще б я помер', 'мета', 'молитва', 'не справляюсь', 'не хочу жити', 'немає надії', 'немає сенсу жити', 'нічого не має сенсу', 'перевантажений', 'покінчити з життям', 'помер', 'провина', 'самогубство', 'самотньо', 'сенс', 'скучаю', 'смерть', 'страшно', 'стрес', 'сумно', 'сумую', 'тривога', 'хвилююсь', 'хочу зникнути', 'хочу померти', 'чому я']
 
 
 
 
 
.hypothesis/constants/549af1221fd95a0e DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/core/ai_client.py
2
- # hypothesis_version: 6.148.7
3
-
4
- [0.0, 0.3, 20000, ' AI Client Test', '%Y-%m-%d %H:%M:%S', '=', 'ANTHROPIC_API_KEY', 'DefaultAgent', 'EntryClassifier', 'GEMINI_API_KEY', 'LOG_PROMPTS', 'MedicalAssistant', 'TEST', '__main__', 'active_model', 'active_provider', 'agent_name', 'ai_interactions.log', 'call_count', 'client_info', 'configured_model', 'configured_provider', 'content', 'default_model', 'false', 'get_client_info', 'last_error', 'model', 'performance_metrics', 'provider', 'reasoning', 'role', 'successful_calls', 'system_instruction', 'temperature', 'text', 'thinking_config', 'total_calls', 'total_response_time', 'true', 'type', 'user', 'using_fallback', 'utf-8']
 
 
 
 
 
.hypothesis/constants/55e855e82cd0f81e DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/core/soft_triage_manager.py
2
- # hypothesis_version: 6.148.7
3
-
4
- ['\nPatient responses:', '\nPrevious exchanges:', 'English', 'LLM evaluation', 'Ukrainian', '\\{[^{}]*\\}', '^["\\\']|["\\\']$', 'better', 'continue', 'coping', 'escalate_red', 'family', 'fine', 'friends', 'okay', 'outcome', 'reasoning', 'resolved_green', 'support', 'добре', 'друзі', 'краще', 'підтримка', 'справляюсь', "сім'я"]
 
 
 
 
 
.hypothesis/constants/6845c48c4c9aae99 DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/config/ai_providers_config.py
2
- # hypothesis_version: 6.148.7
3
-
4
- [0.1, 0.2, 0.3, 20000, ' ⚠️ Warnings:', '=', 'ANTHROPIC_API_KEY', 'EntryClassifier', 'GEMINI_API_KEY', 'MedicalAssistant', 'SoftMedicalTriage', 'TriageExitClassifier', '__main__', 'agent_status', 'anthropic', 'api_key_env', 'available', 'available_models', 'available_providers', 'default_model', 'default_temperature', 'errors', 'fallback_model', 'fallback_needed', 'fallback_provider', 'gemini', 'gemini-2.0-flash', 'gemini-2.5-flash', 'gemini-flash-latest', 'max_tokens', 'model', 'provider', 'reasoning', 'temperature', 'valid', 'warnings', '✅', '✅ Configured', '❌']
 
 
 
 
 
.hypothesis/constants/8c19f079e3b1a4a4 DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/core/spiritual_state.py
2
- # hypothesis_version: 6.148.7
3
-
4
- [0.0, 'RESET -> green', 'continue', 'escalate_red', 'green', 'red', 'resolved_green', 'yellow']
 
 
 
 
 
.hypothesis/constants/d992e29f81671095 DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/core/ai_client.py
2
- # hypothesis_version: 6.148.7
3
-
4
- [0.0, 0.3, 0.7, 20000, ' AI Client Test', '%Y-%m-%d %H:%M:%S', '=', 'ANTHROPIC_API_KEY', 'DefaultAgent', 'EntryClassifier', 'GEMINI_API_KEY', 'LOG_PROMPTS', 'MedicalAssistant', 'TEST', '__main__', 'active_model', 'active_provider', 'agent_name', 'ai_interactions.log', 'call_count', 'client_info', 'configured_model', 'configured_provider', 'content', 'default_model', 'false', 'get_client_info', 'last_error', 'model', 'performance_metrics', 'provider', 'reasoning', 'role', 'spiritual_analysis', 'successful_calls', 'system_instruction', 'temperature', 'text', 'thinking_config', 'total_calls', 'total_response_time', 'true', 'type', 'user', 'using_fallback', 'utf-8']
 
 
 
 
 
.hypothesis/constants/da39a3ee5e6b4b0d DELETED
@@ -1,4 +0,0 @@
1
- # file: /Users/serhiizabolotnii/Medical Brain/Lifestyle/src/__init__.py
2
- # hypothesis_version: 6.148.7
3
-
4
- []
 
 
 
 
 
.hypothesis/unicode_data/16.0.0/charmap.json.gz DELETED
Binary file (22.3 kB)
 
.hypothesis/unicode_data/16.0.0/codec-utf-8.json.gz DELETED
Binary file (60 Bytes)
 
.kiro/specs/lifestyle-spiritual-integration/design.md DELETED
@@ -1,557 +0,0 @@
1
- # Design Document - Lifestyle & Spiritual Integration
2
-
3
- ## Overview
4
-
5
- Цей документ описує архітектурний дизайн інтеграції Lifestyle та Spiritual Health Assessment режимів в єдиний діалоговий інтерфейс. Система надає користувачам можливість вибору між окремими режимами або їх комбінацією, зберігаючи при цьому пріоритет медичних питань.
6
-
7
- ## Architecture
8
-
9
- ### High-Level Architecture
10
-
11
- ```
12
- ┌─────────────────────────────────────────────────────────────┐
13
- │ User Interface (Gradio) │
14
- │ ┌──────────────────────────────────────────────────────┐ │
15
- │ │ Mode Selector: Medical | Lifestyle | Spiritual | │ │
16
- │ │ Combined │ │
17
- │ └──────────────────────────────────────────────────────┘ │
18
- └─────────────────────────────────────────────────────────────┘
19
-
20
- ┌─────────────────────────────────────────────────────────────┐
21
- │ ExtendedLifestyleJourneyApp │
22
- │ ┌──────────────────────────────────────────────────────┐ │
23
- │ │ Entry Classifier (K/L/S/T) │ │
24
- │ └──────────────────────────────────────────────────────┘ │
25
- │ ↓ │
26
- │ ┌──────────────────────────────────────────────────────┐ │
27
- │ │ Mode Router │ │
28
- │ │ • Medical Mode → MedicalAssistant │ │
29
- │ │ • Lifestyle Mode → MainLifestyleAssistant │ │
30
- │ │ • Spiritual Mode → SpiritualAssistant │ │
31
- │ │ • Combined Mode → CombinedAssistant │ │
32
- │ └──────────────────────────────────────────────────────┘ │
33
- └─────────────────────────────────────────────────────────────┘
34
-
35
- ┌─────────────────────────────────────────────────────────────┐
36
- │ Assistants Layer │
37
- │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
38
- │ │ Medical │ │ Lifestyle │ │ Spiritual │ │
39
- │ │ Assistant │ │ Assistant │ │ Assistant │ │
40
- │ └──────────────┘ └──────────────┘ └──────────────┘ │
41
- │ ↓ │
42
- │ ┌──────────────────────────────────────────────────────┐ │
43
- │ │ CombinedAssistant │ │
44
- │ │ (координує Lifestyle + Spiritual) │ │
45
- │ └──────────────────────────────────────────────────────┘ │
46
- └─────────────────────────────────────────────────────────────┘
47
-
48
- ┌─────────────────────────────────────────────────────────────┐
49
- │ Core Services │
50
- │ • AIClientManager │
51
- │ • SpiritualDistressAnalyzer │
52
- │ • ReferralMessageGenerator │
53
- │ • ClarifyingQuestionGenerator │
54
- │ • LifestyleSessionManager │
55
- └─────────────────────────────────────────────────────────────┘
56
- ```
57
-
58
- ## Components and Interfaces
59
-
60
- ### 1. AssistantMode Enum
61
-
62
- ```python
63
- from enum import Enum
64
-
65
- class AssistantMode(Enum):
66
- """Режими роботи асистента"""
67
- NONE = "none"
68
- MEDICAL = "medical"
69
- LIFESTYLE = "lifestyle"
70
- SPIRITUAL = "spiritual"
71
- COMBINED = "combined"
72
- ```
73
-
74
- ### 2. SpiritualAssistant
75
-
76
- Новий компонент для інтеграції Spiritual Health Assessment в діалоговий режим.
77
-
78
- ```python
79
- class SpiritualAssistant:
80
- """
81
- Асистент для оцінки духовного дистресу в діалоговому режимі.
82
-
83
- Обгортка навколо SpiritualDistressAnalyzer, ReferralMessageGenerator
84
- та ClarifyingQuestionGenerator для інтеграції в діалоговий потік.
85
- """
86
-
87
- def __init__(self, api: AIClientManager):
88
- self.api = api
89
- self.analyzer = SpiritualDistressAnalyzer(api)
90
- self.referral_generator = ReferralMessageGenerator(api)
91
- self.question_generator = ClarifyingQuestionGenerator(api)
92
-
93
- def process_message(
94
- self,
95
- message: str,
96
- chat_history: List[ChatMessage],
97
- clinical_background: ClinicalBackground
98
- ) -> Dict[str, Any]:
99
- """
100
- Обробляє повідомлення користувача та генерує відповідь.
101
-
102
- Args:
103
- message: Повідомлення користувача
104
- chat_history: Історія чату
105
- clinical_background: Медичний контекст пацієнта
106
-
107
- Returns:
108
- {
109
- "message": str, # Відповідь користувачу
110
- "classification": DistressClassification,
111
- "referral": Optional[ReferralMessage],
112
- "questions": List[str],
113
- "action": str, # "continue", "escalate", "close"
114
- "reasoning": str
115
- }
116
- """
117
- ```
118
-
119
- **Інтерфейс:**
120
- - **Input**: message (str), chat_history (List), clinical_background (ClinicalBackground)
121
- - **Output**: Dict з полями message, classification, referral, questions, action, reasoning
122
-
123
- **Поведінка:**
124
- - Аналізує повідомлення на духовний дистрес
125
- - Генерує referral для red flags
126
- - Генерує clarifying questions для yellow flags
127
- - Форматує відповідь для діалогового інтерфейсу
128
-
129
- ### 3. CombinedAssistant
130
-
131
- Координатор для одночасної роботи Lifestyle та Spiritual асистентів.
132
-
133
- ```python
134
- class CombinedAssistant:
135
- """
136
- Координує роботу Lifestyle та Spiritual асистентів.
137
-
138
- Викликає обидва асистенти, комбінує їх результати та визначає
139
- пріоритет відповіді на основі виявлених індикаторів.
140
- """
141
-
142
- def __init__(
143
- self,
144
- lifestyle_assistant: MainLifestyleAssistant,
145
- spiritual_assistant: SpiritualAssistant
146
- ):
147
- self.lifestyle = lifestyle_assistant
148
- self.spiritual = spiritual_assistant
149
-
150
- def process_message(
151
- self,
152
- message: str,
153
- chat_history: List[ChatMessage],
154
- clinical_background: ClinicalBackground,
155
- lifestyle_profile: LifestyleProfile,
156
- session_length: int
157
- ) -> Dict[str, Any]:
158
- """
159
- Обробляє повідомлення обома асистентами та комбінує результати.
160
-
161
- Args:
162
- message: Повідомлення користувача
163
- chat_history: Історія чату
164
- clinical_background: Медичний контекст
165
- lifestyle_profile: Профіль lifestyle
166
- session_length: Довжина поточної сесії
167
-
168
- Returns:
169
- {
170
- "message": str, # Комбінована відповідь
171
- "lifestyle_result": Dict,
172
- "spiritual_result": Dict,
173
- "priority": str, # "lifestyle", "spiritual", "balanced"
174
- "action": str, # "continue", "escalate_spiritual", "close"
175
- "reasoning": str
176
- }
177
- """
178
- ```
179
-
180
- **Інтерфей��:**
181
- - **Input**: message, chat_history, clinical_background, lifestyle_profile, session_length
182
- - **Output**: Dict з комбінованими результатами
183
-
184
- **Логіка пріоритизації:**
185
- 1. Якщо Spiritual виявляє red flag → пріоритет spiritual (escalate)
186
- 2. Якщо Lifestyle вирішує закрити сесію → пріоритет lifestyle (close)
187
- 3. Інакше → збалансована комбінація (balanced)
188
-
189
- ### 4. Оновлений Entry Classifier
190
-
191
- Розширений класифікатор з підтримкою spiritual індикаторів.
192
-
193
- ```python
194
- class EntryClassifier:
195
- """
196
- Класифікує вхідні повідомлення за типом потреби.
197
-
198
- Визначає:
199
- - K (Koncern): медичні проблеми
200
- - L (Lifestyle): потреба в lifestyle підтримці
201
- - S (Spiritual): потреба в spiritual підтримці
202
- - T (Triage): рівень терміновості
203
- """
204
-
205
- def classify(
206
- self,
207
- message: str,
208
- clinical_background: ClinicalBackground
209
- ) -> Dict[str, str]:
210
- """
211
- Класифікує повідомлення.
212
-
213
- Returns:
214
- {
215
- "K": "none" | "minor" | "urgent",
216
- "L": "off" | "on",
217
- "S": "off" | "on",
218
- "T": "routine" | "urgent" | "emergency"
219
- }
220
- """
221
- ```
222
-
223
- **Нова логіка:**
224
- - Додано визначення spiritual індикаторів (S)
225
- - Аналіз емоційних та духовних маркерів
226
- - Інтеграція з існуючою K/L/T логікою
227
-
228
- ### 5. Оновлений SessionState
229
-
230
- ```python
231
- @dataclass
232
- class SessionState:
233
- """Стан поточної сесії користувача"""
234
-
235
- # Загальний стан
236
- current_mode: AssistantMode = AssistantMode.NONE
237
- is_active_session: bool = False
238
- session_start_time: Optional[datetime] = None
239
-
240
- # Entry classification
241
- entry_classification: Dict[str, str] = field(default_factory=dict)
242
-
243
- # Medical state
244
- last_triage_summary: str = ""
245
-
246
- # Lifestyle state
247
- lifestyle_session_length: int = 0
248
-
249
- # Spiritual state
250
- spiritual_assessment: Optional[DistressClassification] = None
251
- spiritual_referral: Optional[ReferralMessage] = None
252
- spiritual_questions: List[str] = field(default_factory=list)
253
-
254
- # Combined state
255
- combined_results: Dict[str, Any] = field(default_factory=dict)
256
- active_assistants: List[str] = field(default_factory=list)
257
- ```
258
-
259
- ## Data Models
260
-
261
- ### ClassificationResult
262
-
263
- ```python
264
- @dataclass
265
- class ClassificationResult:
266
- """Результат класифікації Entry Classifier"""
267
- K: str # "none", "minor", "urgent"
268
- L: str # "off", "on"
269
- S: str # "off", "on"
270
- T: str # "routine", "urgent", "emergency"
271
- reasoning: str
272
- confidence: float
273
- ```
274
-
275
- ### SpiritualResponse
276
-
277
- ```python
278
- @dataclass
279
- class SpiritualResponse:
280
- """Відповідь Spiritual Assistant"""
281
- message: str
282
- classification: DistressClassification
283
- referral: Optional[ReferralMessage]
284
- questions: List[str]
285
- action: str # "continue", "escalate", "close"
286
- reasoning: str
287
- ```
288
-
289
- ### CombinedResponse
290
-
291
- ```python
292
- @dataclass
293
- class CombinedResponse:
294
- """Відповідь Combined Assistant"""
295
- message: str
296
- lifestyle_result: Dict[str, Any]
297
- spiritual_result: SpiritualResponse
298
- priority: str # "lifestyle", "spiritual", "balanced"
299
- action: str # "continue", "escalate_spiritual", "close"
300
- reasoning: str
301
- ```
302
-
303
- ## Correctness Properties
304
-
305
- *A property is a characteristic or behavior that should hold true across all valid executions of a system-essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*
306
-
307
- ### Property 1: Mode consistency
308
- *For any* session state, the current_mode field should always match the active assistant being used
309
- **Validates: Requirements 1.1, 1.2**
310
-
311
- ### Property 2: History preservation
312
- *For any* mode switch operation, the chat history length should never decrease
313
- **Validates: Requirements 1.3, 9.1, 9.2**
314
-
315
- ### Property 3: Medical priority
316
- *For any* message classified with K="urgent", the system should activate Medical mode regardless of current mode
317
- **Validates: Requirements 3.1, 3.4**
318
-
319
- ### Property 4: Combined coordination
320
- *For any* message in Combined mode, both Lifestyle and Spiritual assistants should be invoked
321
- **Validates: Requirements 2.1, 6.1**
322
-
323
- ### Property 5: Spiritual escalation priority
324
- *For any* Combined mode response where Spiritual detects red flag, the priority should be "spiritual"
325
- **Validates: Requirements 2.3, 2.4, 6.3**
326
-
327
- ### Property 6: Session closure completeness
328
- *For any* mode switch from Lifestyle, the lifestyle profile should be updated before switching
329
- **Validates: Requirements 10.1, 10.3**
330
-
331
- ### Property 7: Classification completeness
332
- *For any* message, Entry Classifier should return all four fields (K, L, S, T)
333
- **Validates: Requirements 4.1, 4.2, 4.3, 4.4**
334
-
335
- ### Property 8: Fallback availability
336
- *For any* assistant error, the system should have at least one fallback option available
337
- **Validates: Requirements 11.1, 11.2**
338
-
339
- ### Property 9: UI mode indicator consistency
340
- *For any* active mode, the UI should display the corresponding mode indicator
341
- **Validates: Requirements 1.4, 8.3**
342
-
343
- ### Property 10: Combined result structure
344
- *For any* Combined mode response, both lifestyle_result and spiritual_result fields should be present
345
- **Validates: Requirements 2.2, 6.2**
346
-
347
- ## Error Handling
348
-
349
- ### Error Scenarios
350
-
351
- 1. **Assistant Unavailable**
352
- - Fallback: Use alternative assistant or Medical mode
353
- - User notification: "Switching to alternative support mode"
354
-
355
- 2. **Classification Failure**
356
- - Fallback: Use last known mode or default to Medical
357
- - User notification: "Using previous mode settings"
358
-
359
- 3. **Combined Mode Partial Failure**
360
- - Fallback: Use successful assistant result
361
- - User notification: "Providing available support"
362
-
363
- 4. **Session State Corruption**
364
- - Fallback: Reset to safe state (Medical mode)
365
- - User notification: "Session reset for safety"
366
-
367
- ### Error Recovery Strategy
368
-
369
- ```python
370
- def handle_assistant_error(
371
- error: Exception,
372
- current_mode: AssistantMode,
373
- fallback_mode: AssistantMode
374
- ) -> Tuple[str, AssistantMode]:
375
- """
376
- Обробляє помилки асистентів з fallback логікою.
377
-
378
- Returns:
379
- (error_message, new_mode)
380
- """
381
- if isinstance(error, TimeoutError):
382
- return "Service temporarily unavailable, trying alternative...", fallback_mode
383
- elif isinstance(error, ValueError):
384
- return "Invalid input, switching to safe mode...", AssistantMode.MEDICAL
385
- else:
386
- return "Unexpected error, resetting to medical mode...", AssistantMode.MEDICAL
387
- ```
388
-
389
- ## Testing Strategy
390
-
391
- ### Unit Tests
392
-
393
- 1. **SpiritualAssistant Tests**
394
- - Test message processing for each flag level
395
- - Test response formatting
396
- - Test error handling
397
-
398
- 2. **CombinedAssistant Tests**
399
- - Test parallel invocation
400
- - Test priority determination
401
- - Test result combination
402
-
403
- 3. **Entry Classifier Tests**
404
- - Test K/L/S/T classification
405
- - Test spiritual indicator detection
406
- - Test edge cases
407
-
408
- ### Integration Tests
409
-
410
- 1. **Mode Switching Tests**
411
- - Test Lifestyle → Spiritual switch
412
- - Test Spiritual → Lifestyle switch
413
- - Test Combined → Single mode switch
414
- - Test history preservation
415
-
416
- 2. **Combined Mode Tests**
417
- - Test both assistants invoked
418
- - Test priority handling
419
- - Test partial failure scenarios
420
-
421
- 3. **Session Management Tests**
422
- - Test session closure on mode switch
423
- - Test state preservation
424
- - Test profile updates
425
-
426
- ### Property-Based Tests
427
-
428
- Using pytest with hypothesis library:
429
-
430
- 1. **Property Test: Mode Consistency**
431
- ```python
432
- @given(st.text(), st.sampled_from(AssistantMode))
433
- def test_mode_consistency(message, mode):
434
- # Test that mode always matches active assistant
435
- ```
436
-
437
- 2. **Property Test: History Preservation**
438
- ```python
439
- @given(st.lists(st.text()), st.sampled_from(AssistantMode))
440
- def test_history_preservation(messages, new_mode):
441
- # Test that history never decreases on mode switch
442
- ```
443
-
444
- 3. **Property Test: Medical Priority**
445
- ```python
446
- @given(st.text())
447
- def test_medical_priority(message):
448
- # Test that urgent medical issues always activate Medical mode
449
- ```
450
-
451
- ## UI Design
452
-
453
- ### Mode Selector Component
454
-
455
- ```python
456
- with gr.Row():
457
- mode_selector = gr.Radio(
458
- choices=[
459
- "🏥 Medical Only",
460
- "💚 Lifestyle Focus",
461
- "🕊️ Spiritual Focus",
462
- "🌟 Combined (Lifestyle + Spiritual)"
463
- ],
464
- value="🌟 Combined (Lifestyle + Spiritual)",
465
- label="Assistant Mode",
466
- info="Choose your support mode"
467
- )
468
- ```
469
-
470
- ### Status Display
471
-
472
- ```python
473
- def format_status_display(session_state: SessionState) -> str:
474
- """Форматує статус для відображення"""
475
- mode_icons = {
476
- AssistantMode.MEDICAL: "🏥",
477
- AssistantMode.LIFESTYLE: "💚",
478
- AssistantMode.SPIRITUAL: "🕊️",
479
- AssistantMode.COMBINED: "🌟"
480
- }
481
-
482
- icon = mode_icons.get(session_state.current_mode, "⚪")
483
- mode_name = session_state.current_mode.value.upper()
484
-
485
- status = f"{icon} **Current Mode:** {mode_name}\n"
486
-
487
- if session_state.current_mode == AssistantMode.COMBINED:
488
- status += f"**Active:** {', '.join(session_state.active_assistants)}\n"
489
-
490
- if session_state.spiritual_assessment:
491
- flag = session_state.spiritual_assessment.flag_level
492
- status += f"🚩 **Spiritual Flag:** {flag.upper()}\n"
493
-
494
- return status
495
- ```
496
-
497
- ### Response Formatting
498
-
499
- ```python
500
- def format_combined_response(response: CombinedResponse) -> str:
501
- """Форматує комбіновану відповідь"""
502
- if response.priority == "spiritual":
503
- return f"""🕊️ **Spiritual Assessment (Priority)**
504
-
505
- {response.spiritual_result.message}
506
-
507
- ---
508
-
509
- 💚 **Lifestyle Support**
510
-
511
- {response.lifestyle_result['message']}
512
- """
513
- elif response.priority == "lifestyle":
514
- return f"""💚 **Lifestyle Coaching (Priority)**
515
-
516
- {response.lifestyle_result['message']}
517
-
518
- ---
519
-
520
- 🕊️ **Spiritual Check**
521
-
522
- {response.spiritual_result.message}
523
- """
524
- else: # balanced
525
- return f"""🌟 **Comprehensive Support**
526
-
527
- 💚 **Lifestyle:**
528
- {response.lifestyle_result['message']}
529
-
530
- 🕊️ **Spiritual:**
531
- {response.spiritual_result.message}
532
- """
533
- ```
534
-
535
- ## Implementation Notes
536
-
537
- ### Phase 1: Core Components
538
- 1. Create SpiritualAssistant class
539
- 2. Create CombinedAssistant class
540
- 3. Update Entry Classifier
541
- 4. Update SessionState
542
-
543
- ### Phase 2: Integration
544
- 1. Integrate into ExtendedLifestyleJourneyApp
545
- 2. Add mode routing logic
546
- 3. Update process_message flow
547
-
548
- ### Phase 3: UI
549
- 1. Add mode selector
550
- 2. Update status display
551
- 3. Add response formatting
552
-
553
- ### Phase 4: Testing
554
- 1. Unit tests for new components
555
- 2. Integration tests for mode switching
556
- 3. Property-based tests for correctness
557
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/lifestyle-spiritual-integration/requirements.md DELETED
@@ -1,162 +0,0 @@
1
- # Requirements Document - Lifestyle & Spiritual Integration
2
-
3
- ## Introduction
4
-
5
- Цей документ описує вимоги до інтеграції режимів Lifestyle та Spiritual Health Assessment в єдиний діалоговий інтерфейс з можливістю переключення між режимами та комбінованої роботи.
6
-
7
- ## Glossary
8
-
9
- - **System**: Інтегрована система Medical Brain з підтримкою Lifestyle та Spiritual режимів
10
- - **Lifestyle Mode**: Режим роботи з рекомендаціями щодо способу життя
11
- - **Spiritual Mode**: Режим оцінки духовного дистресу
12
- - **Combined Mode**: Комбінований режим одночасної роботи Lifestyle та Spiritual
13
- - **Medical Mode**: Базовий медичний режим для обробки медичних питань
14
- - **Entry Classifier**: Компонент класифікації вхідних повідомлень
15
- - **Session State**: Стан поточної сесії користувача
16
- - **Assistant**: Компонент, що генерує відповіді користувачу
17
-
18
- ## Requirements
19
-
20
- ### Requirement 1: Переключення між режимами
21
-
22
- **User Story:** Як користувач, я хочу переключатися між Lifestyle та Spiritual режимами, щоб отримувати різні типи підтримки залежно від моїх потреб.
23
-
24
- #### Acceptance Criteria
25
-
26
- 1. WHEN користувач обирає Lifestyle режим THEN система SHALL активувати MainLifestyleAssistant та деактивувати інші асистенти
27
- 2. WHEN користувач обирає Spiritual режим THEN система SHALL активувати SpiritualAssistant та деактивувати інші асистенти
28
- 3. WHEN користувач перемикає режим THEN система SHALL зберігати історію чату
29
- 4. WHEN режим змінюється THEN система SHALL відображати поточний активний режим в UI
30
- 5. WHEN користувач перемикає з одного режиму на інший THEN система SHALL коректно завершувати попередню сесію
31
-
32
- ### Requirement 2: Комбінований режим роботи
33
-
34
- **User Story:** Як користувач, я хочу отримувати одночасно lifestyle рекомендації та spiritual assessment, щоб мати комплексну підтримку.
35
-
36
- #### Acceptance Criteria
37
-
38
- 1. WHEN користувач обирає Combined режим THEN система SHALL аналізувати повідомлення обома асистентами
39
- 2. WHEN отримано результати від обох асистентів THEN система SHALL комбінувати відповіді в єдине повідомлення
40
- 3. WHEN один з асистентів виявляє критичну ситуацію THEN система SHALL надавати пріоритет його відповіді
41
- 4. WHEN Spiritual Assistant виявляє red flag THEN система SHALL відображати referral message з найвищим пріоритетом
42
- 5. WHEN обидва асистенти генерують відповіді THEN система SHALL чітко розділяти їх в UI
43
-
44
- ### Requirement 3: Інтеграція з медичним режимом
45
-
46
- **User Story:** Як користувач, я хочу, щоб медичні питання завжди мали пріоритет, незалежно від обраного режиму.
47
-
48
- #### Acceptance Criteria
49
-
50
- 1. WHEN Entry Classifier виявляє медичну проблему THEN система SHALL переключатися на Medical режим
51
- 2. WHEN медична проблема вирішена THEN система SHALL повертатися до попередньо обраного режиму
52
- 3. WHEN користувач в Medical режимі THEN система SHALL використовувати MedicalAssistant або SoftMedicalTriage
53
- 4. WHEN медична проблема критична THEN система SHALL ігнорувати поточний режим та активувати Medical режим
54
-
55
- ### Requirement 4: Розширений Entry Classifier
56
-
57
- **User Story:** Як система, я маю коректно визначати потребу в lifestyle, spiritual або обох типах підтримки.
58
-
59
- #### Acceptance Criteria
60
-
61
- 1. WHEN Entry Classifier аналізує повідомлення THEN система SHALL визначати медичні індикатори (K)
62
- 2. WHEN Entry Classifier аналізує повідомлення THEN система SHALL визнач��ти lifestyle індикатори (L)
63
- 3. WHEN Entry Classifier аналізує повідомлення THEN система SHALL визначати spiritual індикатори (S)
64
- 4. WHEN Entry Classifier аналізує повідомлення THEN система SHALL визначати рівень терміновості (T)
65
- 5. WHEN виявлено індикатори обох типів THEN система SHALL рекомендувати Combined режим
66
-
67
- ### Requirement 5: SpiritualAssistant для діалогового режиму
68
-
69
- **User Story:** Як система, я маю інтегрувати Spiritual Health Assessment в діалоговий потік.
70
-
71
- #### Acceptance Criteria
72
-
73
- 1. WHEN SpiritualAssistant отримує повідомлення THEN система SHALL аналізувати його на духовний дистрес
74
- 2. WHEN виявлено red flag THEN SpiritualAssistant SHALL генерувати referral message
75
- 3. WHEN виявлено yellow flag THEN SpiritualAssistant SHALL генерувати clarifying questions
76
- 4. WHEN виявлено no flag THEN SpiritualAssistant SHALL генерувати підтримуючу відповідь
77
- 5. WHEN SpiritualAssistant генерує відповідь THEN система SHALL форматувати її для діалогового інтерфейсу
78
-
79
- ### Requirement 6: CombinedAssistant координація
80
-
81
- **User Story:** Як система, я маю координувати роботу Lifestyle та Spiritual асистентів в Combined режимі.
82
-
83
- #### Acceptance Criteria
84
-
85
- 1. WHEN CombinedAssistant обробляє повідомлення THEN система SHALL викликати обидва асистенти паралельно
86
- 2. WHEN отримано результати від обох асистентів THEN CombinedAssistant SHALL визначати пріоритет відповіді
87
- 3. WHEN Spiritual виявляє red flag THEN CombinedAssistant SHALL надавати пріоритет spiritual відповіді
88
- 4. WHEN обидва асистенти генерують нормальні відповіді THEN CombinedAssistant SHALL комбінувати їх збалансовано
89
- 5. WHEN один з асистентів повертає помилку THEN CombinedAssistant SHALL використовувати результат іншого
90
-
91
- ### Requirement 7: Оновлений SessionState
92
-
93
- **User Story:** Як система, я маю зберігати стан для всіх режимів роботи.
94
-
95
- #### Acceptance Criteria
96
-
97
- 1. WHEN SessionState ініціалізується THEN система SHALL створювати поля для всіх режимів
98
- 2. WHEN режим змінюється THEN SessionState SHALL оновлювати current_mode
99
- 3. WHEN Spiritual режим активний THEN SessionState SHALL зберігати spiritual_assessment, spiritual_referral, spiritual_questions
100
- 4. WHEN Combined режим активний THEN SessionState SHALL зберігати результати обох асистентів
101
- 5. WHEN сесія скидається THEN SessionState SHALL очищати всі поля
102
-
103
- ### Requirement 8: UI компоненти для вибору режиму
104
-
105
- **User Story:** Як користувач, я хочу легко обирати та бачити поточний режим роботи.
106
-
107
- #### Acceptance Criteria
108
-
109
- 1. WHEN інтерфейс завантажується THEN система SHALL відображати mode selector з усіма доступними режимами
110
- 2. WHEN користувач обирає режим THEN UI SHALL візуально підтверджувати вибір
111
- 3. WHEN режим активний THEN status box SHALL відображати поточний режим з іконкою
112
- 4. WHEN Combined режим активний THEN UI SHALL показувати індикатори обох асистентів
113
- 5. WHEN Spiritual виявляє red flag THEN UI SHALL відображати червоний індикатор та referral message
114
-
115
- ### Requirement 9: Збереження історії при переключенні
116
-
117
- **User Story:** Як користувач, я хочу, щоб історія чату зберігалася при переключенні режимів.
118
-
119
- #### Acceptance Criteria
120
-
121
- 1. WHEN користувач перемикає режим THEN система SHALL зберігати всю історію чату
122
- 2. WHEN користувач повертається до попереднього режиму THEN система SHALL відображати повну історію
123
- 3. WHEN повідомлення додається до історії THEN система SHALL позначати його поточним режимом
124
- 4. WHEN історія відображається THEN UI SHALL показувати іконки режимів для кожного повідомлення
125
- 5. WHEN сесія завершується THEN система SHALL зберігати історію з інформацією про режими
126
-
127
- ### Requirement 10: Коректне завершення сесій
128
-
129
- **User Story:** Як система, я маю коректно завершувати сесії при переключенні режимів.
130
-
131
- #### Acceptance Criteria
132
-
133
- 1. WHEN користувач перемикає з Lifestyle режиму THEN система SHALL оновлювати lifestyle profile
134
- 2. WHEN користувач перемикає з Spiritual режиму THEN система SHALL зберігати spiritual assessment
135
- 3. WHEN користувач перемикає з Combined режиму THEN система SHALL завершувати обидві сесії
136
- 4. WHEN сесія завершується THEN система SHALL генерувати summary для користувача
137
- 5. WHEN користувач явно завершує розмову THEN система SHALL коректно закривати всі активні сесії
138
-
139
- ### Requirement 11: Обробка помилок та fallback
140
-
141
- **User Story:** Як система, я маю коректно обробляти помилки та надавати fallback опції.
142
-
143
- #### Acceptance Criteria
144
-
145
- 1. WHEN один з асистентів повертає помилку THEN система SHALL використовувати інший асистент
146
- 2. WHEN обидва асистенти недоступні THEN система SHALL переключатися на Medical режим
147
- 3. WHEN Entry Classifier не може визначити режим THEN система SHALL використовувати останній активний режим
148
- 4. WHEN виникає критична помилка THEN система SHALL інформувати користувача з чіткими інструкціями
149
- 5. WHEN помилка тимчасова THEN система SHALL автоматично повторювати запит
150
-
151
- ### Requirement 12: Тестування та валідація
152
-
153
- **User Story:** Як розробник, я хочу мати комплексні тести для всіх режимів роботи.
154
-
155
- #### Acceptance Criteria
156
-
157
- 1. WHEN створюється новий компонент THEN розробник SHALL написати unit тести
158
- 2. WHEN інтегруються компоненти THEN розробник SHALL написати integration тести
159
- 3. WHEN тестується переключення режимів THEN тести SHALL перевіряти збереження стану
160
- 4. WHEN тестується Combined режим THEN тести SHALL перевіряти координацію асистентів
161
- 5. WHEN тестується UI THEN тести SHALL перевіряти коректне відображення всіх режимів
162
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/lifestyle-spiritual-integration/tasks.md DELETED
@@ -1,467 +0,0 @@
1
- # Implementation Plan - Lifestyle & Spiritual Integration
2
-
3
- ## Overview
4
-
5
- Цей план описує покрокову імплементацію інтеграції Lifestyle та Spiritual режимів з можливістю переключення та комбінованої роботи.
6
-
7
- ---
8
-
9
- ## Phase 1: Core Components ✅ COMPLETED
10
-
11
- ### Task 1: Створити SpiritualAssistant для діалогового режиму ✅
12
-
13
- - [x] 1.1 Створити файл `src/core/spiritual_assistant.py`
14
- - Створити клас SpiritualAssistant
15
- - Додати __init__ з ініціалізацією analyzer, referral_generator, question_generator
16
- - _Requirements: 5.1_
17
-
18
- - [x] 1.2 Імплементувати метод process_message()
19
- - Додати аналіз повідомлення через SpiritualDistressAnalyzer
20
- - Додати генерацію referral для red flags
21
- - Додати генерацію questions для yellow flags
22
- - Додати форматування відповіді для діалогу
23
- - _Requirements: 5.2, 5.3, 5.4, 5.5_
24
-
25
- - [x] 1.3 Додати форматування відповідей
26
- - Створити метод _format_response_for_dialog()
27
- - Додати різні формати для red/yellow/no flags
28
- - Додати емоційно підтримуючі повідомлення
29
- - _Requirements: 5.5_
30
-
31
- - [x]* 1.4 Написати unit тести для SpiritualAssistant
32
- - Тести для process_message з різними flag levels
33
- - Тести для форматування відповідей
34
- - Тести для обробки помилок
35
- - _Requirements: 12.1_
36
-
37
- ---
38
-
39
- ### Task 2: Створити CombinedAssistant для координації ✅
40
-
41
- - [x] 2.1 Створити файл `src/core/combined_assistant.py`
42
- - Створити клас CombinedAssistant
43
- - Додати __init__ з lifestyle_assistant та spiritual_assistant
44
- - _Requirements: 6.1_
45
-
46
- - [x] 2.2 Імплементувати метод process_message()
47
- - Додати паралельний виклик обох асистентів
48
- - Додати обробку результатів
49
- - Додати error handling для кожного асистента
50
- - _Requirements: 6.1, 6.5_
51
-
52
- - [x] 2.3 Додати логіку пріоритизації
53
- - Створити метод _determine_priority()
54
- - Додати перевірку red flag від Spiritual
55
- - Додати перевірку close action від Lifestyle
56
- - Додати balanced режим
57
- - _Requirements: 6.2, 6.3, 6.4_
58
-
59
- - [x] 2.4 Додати комбінування відповідей
60
- - Створити метод _combine_responses()
61
- - Додати форматування для різних пріоритетів
62
- - Додати розділення відповідей в UI
63
- - _Requirements: 2.2, 2.5_
64
-
65
- - [x]* 2.5 Написати unit тести для CombinedAssistant
66
- - Тести для паралельного виклику
67
- - Тести для пріоритизації
68
- - Тести для комбінування відповідей
69
- - Тести для partial failure scenarios
70
- - _Requirements: 12.1_
71
-
72
- ---
73
-
74
- ### Task 3: Оновити Entry Classifier та SessionState ✅
75
-
76
- - [x] 3.1 Створити AssistantMode enum
77
- - Додати enum AssistantMode в `src/core/core_classes.py` з значеннями: NONE, MEDICAL, LIFESTYLE, SPIRITUAL, COMBINED
78
- - _Requirements: 7.1_
79
-
80
- - [x] 3.2 Додати визначення spiritual індикаторів в Entry Classifier
81
- - Оновити метод classify() в `src/core/core_classes.py`
82
- - Додати аналіз емоційних маркерів (anger, sadness, hopelessness, etc.)
83
- - Додати аналіз духовних маркерів (meaning, purpose, faith concerns)
84
- - Додати поле S в результат класифікації (off/on)
85
- - _Requirements: 4.2, 4.3_
86
-
87
- - [x] 3.3 Оновити формат відповіді Entry Classifier на K/L/S/T
88
- - Змінити return type на Dict з полями K, L, S, T
89
- - K: "none" | "minor" | "urgent" (медичні індикатори)
90
- - L: "off" | "on" (lifestyle індикатори)
91
- - S: "off" | "on" (spiritual індикатори)
92
- - T: "routine" | "urgent" | "emergency" (терміновість)
93
- - Додати reasoning для кожного поля
94
- - _Requirements: 4.1, 4.2, 4.3, 4.4_
95
-
96
- - [x] 3.4 Додати логіку рекомендації Combined режиму
97
- - Додати перевірку L="on" AND S="on"
98
- - Додати поле recommended_mode в результат
99
- - _Requirements: 4.5_
100
-
101
- - [x] 3.5 Оновити SessionState з новими полями
102
- - Змінити current_mode з str на AssistantMode type
103
- - Додати spiritual_assessment: Optional[DistressClassification]
104
- - Додати spiritual_referral: Optional[ReferralMessage]
105
- - Додати spiritual_questions: List[str]
106
- - Додати combined_results: Dict[str, Any]
107
- - Додати active_assistants: List[str]
108
- - _Requirements: 7.1, 7.3, 7.4_
109
-
110
- - [x] 3.6 Оновити методи SessionState
111
- - Оновити метод reset() для очищення нових полів
112
- - Додати метод update_mode() для зміни режиму
113
- - Додати метод get_active_assistants()
114
- - _Requirements: 7.2, 7.5_
115
-
116
- - [-]* 3.7 Написати тести для оновленого Entry Classifier та SessionState
117
- - Тести для визначення S індикаторів
118
- - Тести для K/L/S/T формату
119
- - Тести для рекомендації Combined режиму
120
- - Тести для нових полів SessionState
121
- - _Requirements: 12.1_
122
-
123
- ---
124
-
125
- ## Phase 2: Integration into ExtendedLifestyleJourneyApp ✅ COMPLETED
126
-
127
- ### Task 4: Інтегрувати нові асистенти в app ✅
128
-
129
- - [x] 4.1 Додати ініціалізацію асистентів in __init__
130
- - Додати self.spiritual_assistant = SpiritualAssistant(self.api) в lifestyle_app.py
131
- - Додати self.combined_assistant = CombinedAssistant(self.main_lifestyle_assistant, self.spiritual_assistant)
132
- - Оновити коментарі та документацію
133
- - _Requirements: 5.1, 6.1_
134
-
135
- - [x] 4.2 Оновити process_message() для підтримки всіх режимів
136
- - Додати перевірку current_mode (використовуючи AssistantMode enum)
137
- - Додати routing до відповідного асистента на основі режиму
138
- - Оновити логіку оновлення session_state з новими полями
139
- - _Requirements: 1.1, 1.2, 2.1_
140
-
141
- - [x] 4.3 Додати _handle_spiritual_mode()
142
- - Створити новий метод для обробки Spiritual режиму
143
- - Додати виклик spiritual_assistant.process_message()
144
- - Додати обробку результатів (red/yellow/no flag)
145
- - Додати логіку переходу в Medical при escalation (action="escalate")
146
- - Зберігати spiritual_assessment, spiritual_referral, spiritual_questions в session_state
147
- - _Requirements: 1.2, 3.1_
148
-
149
- - [x] 4.4 Додати _handle_combined_mode()
150
- - Створити новий метод для обробки Combined режиму
151
- - Додати виклик combined_assistant.process_message()
152
- - Додати обробку пріоритетів (spiritual/lifestyle/balanced)
153
- - Додати логіку escalation при action="escalate_spiritual"
154
- - Зберігати combined_results в session_state
155
- - _Requirements: 2.1, 2.3_
156
-
157
- - [x] 4.5 Оновити _handle_entry_classification()
158
- - Додати обробку S індикатора з нового K/L/S/T формату
159
- - Додати routing до Spiritual режиму коли S="on" AND L="off"
160
- - Додати routing до Combined режиму коли S="on" AND L="on"
161
- - Оновити логіку для K/L/S/T формату замість старого K/V/T
162
- - _Requirements: 4.1, 4.2, 4.3, 4.5_
163
-
164
- - [x] 4.6 Додати логіку завершення сесій при переключенні
165
- - Створити метод _close_current_session()
166
- - Додати збереження lifestyle profile при виході з Lifestyle
167
- - Додати збереження spiritual assessment при виході з Spiritual
168
- - Додати обробку Combined режиму (зберегти обидва профілі)
169
- - Викликати при зміні режиму через mode selector
170
- - _Requirements: 10.1, 10.2, 10.3, 10.4_
171
-
172
- - [-]* 4.7 Написати integration тести для app
173
- - Тести для process_message з різними режимами
174
- - Тести для переключення режимів
175
- - Тести для завершення сесій
176
- - _Requirements: 12.2_
177
-
178
- ---
179
-
180
- ## Phase 3: UI Updates ✅ COMPLETED
181
-
182
- ### Task 5: Додати mode selector в UI ✅
183
-
184
- - [x] 5.1 Додати mode selector компонент
185
- - Додати gr.Radio з режимами в `src/interface/gradio_app.py`
186
- - Режими: "🏥 Medical Only", "💚 Lifestyle Focus", "🕊️ Spiritual Focus", "🌟 Combined (Lifestyle + Spiritual)"
187
- - Замінити існуючий "Prompt Mode" radio на "Assistant Mode"
188
- - Додати опис режимів через info parameter
189
- - _Requirements: 8.1_
190
-
191
- - [x] 5.2 Додати обробник зміни режиму
192
- - Створити функцію handle_mode_change() в gradio_app.py
193
- - Додати виклик app._close_current_session() перед зміною режиму
194
- - Додати оновлення session_state.current_mode (використовуючи AssistantMode enum)
195
- - Додати оновлення UI (chatbot, status_box)
196
- - Підключити до mode_selector.change() event
197
- - _Requirements: 1.4, 8.2_
198
-
199
- - [x] 5.3 Оновити status_box для відображення режиму
200
- - Оновити _get_status_info() в lifestyle_app.py для показу current_mode
201
- - Додати іконки режимів (🏥, 💚, 🕊️, 🌟)
202
- - Додати індикатори active_assistants для Combined режиму
203
- - Додати відображення spiritual flags (red/yellow/none)
204
- - Додати відображення spiritual_referral якщо є
205
- - _Requirements: 8.3, 8.4, 8.5_
206
-
207
- - [x] 5.4 Оновити ChatMessage для підтримки режимів
208
- - Додати поле mode в ChatMessage dataclass (вже існує)
209
- - Оновити створення ChatMessage щоб включати current_mode
210
- - Додати відображення іконок режимів в історії чату
211
- - _Requirements: 9.3, 9.4_
212
-
213
- - [-]* 5.5 Написати UI тести
214
- - Тести для mode selector
215
- - Тести для status display
216
- - Тести для response formatting
217
- - _Requirements: 12.5_
218
-
219
- ---
220
-
221
- ## Phase 4: Error Handling and Fallback ✅ COMPLETED
222
-
223
- ### Task 6: Додати error handling ✅
224
-
225
- - [x] 6.1 Додати обробку помилок асистентів in app
226
- - Створити метод handle_assistant_error() в lifestyle_app.py
227
- - Додати fallback логіку: Spiritual error → Medical mode, Lifestyle error → Medical mode
228
- - Додати user notifications з чіткими інструкціями
229
- - Додати logging помилок
230
- - _Requirements: 11.1, 11.4_
231
-
232
- - [x] 6.2 Перевірити fallback для Combined режиму
233
- - Переконатися що CombinedAssistant вже має обробку partial failure (вже реалізовано)
234
- - Додати тести що Combined використовує успішний результат при помилці одного асистента
235
- - Додати повідомлення користувачу про partial availability
236
- - _Requirements: 11.1_
237
-
238
- - [x] 6.3 Додати fallback для Entry Classifier
239
- - Додати try-catch навколо entry_classifier.classify()
240
- - При помилці використовувати останній активний режим (session_state.current_mode)
241
- - Якщо немає останнього режиму, default до Medical режиму
242
- - Додати logging та user notification
243
- - _Requirements: 11.3_
244
-
245
- - [x] 6.4 Додати retry логіку для тимчасових помилок
246
- - Додати визначення тимчасових помилок (TimeoutError, ConnectionError)
247
- - Додати автоматичний retry з exponential backoff
248
- - Додати максимальну кількість спроб (3 спроби)
249
- - Додати logging retry attempts
250
- - _Requirements: 11.5_
251
-
252
- - [-]* 6.5 Написати тести для error handling
253
- - Тести для різних типів помилок
254
- - Тести для fallback логіки
255
- - Тести для retry механізму
256
- - _Requirements: 12.1_
257
-
258
- ---
259
-
260
- ## Phase 5: Testing and Validation
261
-
262
- ### Task 7: Comprehensive Testing
263
-
264
- - [-] 7.1 Checkpoint - Переконатися що всі unit тести проходять
265
- - Запустити pytest tests/test_spiritual_assistant.py
266
- - Запустити pytest tests/test_combined_assistant.py
267
- - Виправити failing тести якщо є
268
- - Переконатися що coverage > 80% для нових компонентів
269
- - _Requirements: 12.1_
270
-
271
- - [-]* 7.2 Написати integration тести для переключення режимів
272
- - Тест: Lifestyle → Spiritual → Lifestyle (збереження lifestyle profile)
273
- - Тест: Spiritual → Combined → Spiritual (збереження spiritual assessment)
274
- - Тест: Combined → Medical → Combined (збереження обох профілів)
275
- - Тест: збереження історії при переключенні (history length не зменшується)
276
- - _Requirements: 12.3_
277
-
278
- - [-]* 7.3 Написати integration тести для Combined режиму
279
- - Тест: обидва асистенти викликаються паралельно
280
- - Тест: пріоритизація при red flag (spiritual priority)
281
- - Тест: balanced комбінування при нормальних результатах
282
- - Тест: partial failure handling (один асистент працює)
283
- - _Requirements: 12.4_
284
-
285
- - [-]* 7.4 Написати property-based тести
286
- - **Property 1: Mode consistency** - session_state.current_mode завжди відповідає активному асистенту
287
- - **Property 2: History preservation** - len(chat_history) ніколи не зменшується при mode switch
288
- - **Property 3: Medical priority** - K="urgent" завжди активує Medical режим
289
- - **Property 4: Combined coordination** - Combined режим завжди викликає обидва асистенти
290
- - _Requirements: 12.1_
291
-
292
- - [-] 7.5 Checkpoint - Переконатися що всі тести проходять
293
- - Запустити pytest для всього проекту
294
- - Виправити failing тести
295
- - Перевірити edge cases
296
- - Переконатися що немає regression в існуючій функціональності
297
- - _Requirements: 12.2_
298
-
299
- ---
300
-
301
- ## Phase 6: Documentation and Final Validation
302
-
303
- ### Task 8: Оновити документацію
304
-
305
- - [-] 8.1 Оновити README.md
306
- - Додати опис нових режимів (Medical, Lifestyle, Spiritual, Combined)
307
- - Додати приклади використання кожного режиму
308
- - Додати інформацію про переключення режимів
309
- - _Requirements: N/A_
310
-
311
- - [-] 8.2 Оновити QUICK_START.md
312
- - Додати інструкції для вибору режиму через UI
313
- - Додати приклади запитів для кожного режиму
314
- - Додати пояснення коли використовувати який режим
315
- - _Requirements: N/A_
316
-
317
- - [-] 8.3 Створити USER_GUIDE.md для режимів
318
- - Додати детальний опис кожного режиму
319
- - Додати рекомендації коли використовувати який режим
320
- - Додати FAQ про режими
321
- - Додати troubleshooting для режимів
322
- - _Requirements: N/A_
323
-
324
- - [-] 8.4 Оновити код коментарі та docstrings
325
- - Додати docstrings для всіх нових методів
326
- - Оновити коментарі в коді
327
- - Додати type hints де відсутні
328
- - Додати приклади використання в docstrings
329
- - _Requirements: N/A_
330
-
331
- ---
332
-
333
- ### Task 9: Final Testing and Validation
334
-
335
- - [-] 9.1 Провести manual testing всіх режимів
336
- - Тестувати Medical режим (існуюча функціональність)
337
- - Тестувати Lifestyle режим (існуюча функціональність)
338
- - Тестувати Spiritual режим (нова функціональність)
339
- - Тестувати Combined режим (нова функціональність)
340
- - _Requirements: N/A_
341
-
342
- - [-] 9.2 Провести manual testing переключення режимів
343
- - Тестувати переключення між всіма режимами
344
- - Перевірити збереження історії
345
- - Перевірити збереження профілів
346
- - Перевірити UI updates при переключенні
347
- - _Requirements: N/A_
348
-
349
- - [-] 9.3 Провести error scenario testing
350
- - Тестувати помилки асистентів
351
- - Тестувати помилки Entry Classifier
352
- - Тестувати partial failures в Combined режимі
353
- - Перевірити fallback логіку
354
- - _Requirements: N/A_
355
-
356
- - [-] 9.4 Провести performance testing
357
- - Виміряти час відповіді для кожного режиму
358
- - Виміряти час для Combined режиму (паралельні виклики)
359
- - Виміряти час Entry Classifier з новою логікою
360
- - Оптимізувати якщо потрібно
361
- - _Requirements: N/A_
362
-
363
- - [-] 9.5 Final Checkpoint - Все готово до deployment
364
- - Всі unit тести проходять
365
- - Всі integration тести проходять (якщо написані)
366
- - Документація оновлена
367
- - Manual testing завершено
368
- - Performance прийнятний
369
- - Немає regression в існуючій функціональності
370
- - _Requirements: All_
371
-
372
- ---
373
-
374
- ## Phase 7: Technology Upgrade ✅ COMPLETED
375
-
376
- ### Task 10: Upgrade to Gradio 6.0.2 ✅
377
-
378
- - [x] 10.1 Update requirements.txt
379
- - Змінити gradio>=5.3.0 на gradio==6.0.2
380
- - Перевірити сумісність інших залежностей
381
- - _Date: December 5, 2025_
382
-
383
- - [x] 10.2 Rebuild virtual environment
384
- - Видалити старий venv
385
- - Створити новий venv з Python 3.14.0
386
- - Встановити всі залежності з оновленим Gradio
387
- - _Date: December 5, 2025_
388
-
389
- - [x] 10.3 Run regression tests
390
- - Запустити test_spiritual_assistant.py (13 tests)
391
- - Запустити test_combined_assistant.py (14 tests)
392
- - Переконатися що всі 27 тестів проходять
393
- - _Result: ✅ 27/27 tests passed_
394
-
395
- - [x] 10.4 Test UI compatibility
396
- - Запустити Gradio interface
397
- - Перевірити Assistant Mode selector
398
- - Перевірити всі 4 режими (Medical/Lifestyle/Spiritual/Combined)
399
- - Перевірити session isolation
400
- - _Status: ✅ Interface running on http://127.0.0.1:7860_
401
-
402
- - [x] 10.5 Fix Gradio 6.x compatibility issues
403
- - Виправити `theme` parameter (тепер через demo.theme attribute)
404
- - Видалити `show_copy_button` parameter (deprecated)
405
- - Видалити `type="messages"` parameter (auto-detected)
406
- - Оновити обидва файли: gradio_app.py та spiritual_interface.py
407
- - _Result: ✅ All compatibility issues resolved_
408
-
409
- **Upgrade Notes:**
410
- - Gradio 6.0.2 brings improved performance and stability
411
- - **Breaking changes fixed:**
412
- - `gr.Blocks(theme=...)` → `demo.theme = ...`
413
- - `gr.Chatbot(show_copy_button=True)` → removed (deprecated)
414
- - `gr.Chatbot(type="messages")` → removed (auto-detected)
415
- - All existing functionality remains compatible after fixes
416
- - Session isolation working correctly
417
- - UI components render properly
418
- - Interface successfully running on http://127.0.0.1:7860
419
-
420
- ---
421
-
422
- ## Summary
423
-
424
- **Completed:** All Core Phases (1-6) + Testing + Documentation ✅
425
- **Remaining:** Optional tasks only (marked with *)
426
- **Total Subtasks Completed:** 35+ core subtasks
427
- **Optional Tasks Remaining:** ~10 (integration tests, additional docs, manual testing)
428
-
429
- **Current Status:**
430
- - ✅ SpiritualAssistant implemented and tested (13/13 tests)
431
- - ✅ CombinedAssistant implemented and tested (14/14 tests)
432
- - ✅ AssistantMode enum created
433
- - ✅ Entry Classifier updated with S indicator and K/L/S/T format
434
- - ✅ SessionState updated with spiritual and combined fields
435
- - ✅ App integration completed (Task 4)
436
- - ✅ UI mode selector added (Task 5)
437
- - ✅ Error handling implemented (Task 6)
438
- - ✅ Core testing completed (Task 7.1: 27/27 tests passed)
439
- - ✅ README.md updated (Task 8.1)
440
- - ✅ **Gradio upgraded to 6.0.2** (December 5, 2025)
441
-
442
- **Completed Phases:**
443
- - ✅ Phase 1: Core Components (Tasks 1-3)
444
- - ✅ Phase 2: App Integration (Task 4)
445
- - ✅ Phase 3: UI Updates (Task 5)
446
- - ✅ Phase 4: Error Handling (Task 6)
447
- - ✅ Phase 5: Core Testing (Task 7.1)
448
- - ✅ Phase 6: Core Documentation (Task 8.1)
449
-
450
- **Git Commits:**
451
- 1. ✅ feat: Task 4 - Integrate Spiritual and Combined assistants into app (commit 05f446c)
452
- 2. ✅ feat: Task 5.1-5.2 - Add Assistant Mode selector to UI (commit 537b5b3)
453
- 3. ✅ feat: Task 6 - Add comprehensive error handling and fallback (commit 45a1a24)
454
- 4. ✅ docs: Update README.md with multi-mode integration features (commit 062b240)
455
-
456
- **Technology Stack:**
457
- - Python 3.14.0
458
- - Gradio 6.0.2 (upgraded from 5.3.0)
459
- - Google Gemini API
460
- - Pytest 9.0.1
461
-
462
- **Next Steps (Optional):**
463
- 1. Task 7.2-7.4: Additional integration and property-based tests
464
- 2. Task 8.2-8.4: Update QUICK_START.md, create USER_GUIDE.md
465
- 3. Task 9: Final manual testing and validation
466
-
467
- **Status:** ✅ **READY FOR PRODUCTION** - All core requirements (1.1-11.5) implemented and tested
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/simplified-spiritual-triage/design.md DELETED
@@ -1,240 +0,0 @@
1
- # Design Document: Simplified Spiritual Triage
2
-
3
- ## Overview
4
-
5
- Спрощена архітектура Medical Brain з фоновим моніторингом духовного здоров'я. Система працює в єдиному Medical режимі з невидимим для користувача Spiritual Monitor, який автоматично виявляє ознаки дистресу та ініціює делікатний тріаж при необхідності.
6
-
7
- ## Architecture
8
-
9
- ```mermaid
10
- flowchart TD
11
- subgraph Input
12
- MSG[Patient Message]
13
- end
14
-
15
- subgraph "Background Processing"
16
- SM[Spiritual Monitor<br/>Classifier]
17
- end
18
-
19
- subgraph "State Machine"
20
- GREEN[🟢 Green State<br/>Normal Medical Dialog]
21
- YELLOW[🟡 Yellow State<br/>Soft Triage Mode]
22
- RED[🔴 Red State<br/>Crisis Support]
23
- end
24
-
25
- subgraph "Output"
26
- MED[Medical Response]
27
- TRIAGE[Triage Question]
28
- CRISIS[Crisis Support +<br/>Referral Generation]
29
- end
30
-
31
- MSG --> SM
32
- SM -->|"No indicators"| GREEN
33
- SM -->|"Potential indicators"| YELLOW
34
- SM -->|"Severe indicators"| RED
35
-
36
- GREEN --> MED
37
- YELLOW --> TRIAGE
38
- TRIAGE -->|"Patient OK"| GREEN
39
- TRIAGE -->|"Distress confirmed<br/>or 3+ exchanges"| RED
40
- RED --> CRISIS
41
- ```
42
-
43
- ## Components and Interfaces
44
-
45
- ### 1. SpiritualMonitor (Classifier)
46
-
47
- **Purpose:** Фоновий аналіз кожного повідомлення на ознаки духовного дистресу.
48
-
49
- **Interface:**
50
- ```python
51
- class SpiritualMonitor:
52
- def classify(self, message: str, conversation_history: List[str]) -> SpiritualState:
53
- """
54
- Returns: SpiritualState (GREEN, YELLOW, RED)
55
- """
56
- ```
57
-
58
- **Classification Logic:**
59
- - GREEN: Немає індикаторів дистресу
60
- - YELLOW: Потенційні індикатори (смуток, тривога, питання про сенс)
61
- - RED: Серйозні індикатори (думки про смерть, безнадія, суїцидальні ідеї)
62
-
63
- ### 2. SoftTriageManager
64
-
65
- **Purpose:** Управління делікатним психологічним тріажем при Yellow Flag.
66
-
67
- **Interface:**
68
- ```python
69
- class SoftTriageManager:
70
- def __init__(self):
71
- self.question_count: int = 0
72
- self.max_questions: int = 3
73
- self.triage_history: List[str] = []
74
-
75
- def generate_question(self, context: str, patient_language: str) -> str:
76
- """Generate empathetic clarifying question"""
77
-
78
- def evaluate_response(self, response: str) -> TriageOutcome:
79
- """
80
- Returns: TriageOutcome (RESOLVED_GREEN, ESCALATE_RED, CONTINUE)
81
- """
82
-
83
- def should_force_decision(self) -> bool:
84
- """Returns True if max questions reached"""
85
- ```
86
-
87
- ### 3. SessionStateManager
88
-
89
- **Purpose:** Управління станом духовного моніторингу в сесії.
90
-
91
- **Interface:**
92
- ```python
93
- class SessionStateManager:
94
- current_state: SpiritualState # GREEN, YELLOW, RED
95
- triage_question_count: int
96
- triage_context: List[str]
97
-
98
- def transition_to(self, new_state: SpiritualState) -> None
99
- def reset(self) -> None
100
- def get_state(self) -> SpiritualState
101
- ```
102
-
103
- ### 4. MedicalAssistant (Simplified)
104
-
105
- **Purpose:** Основний медичний асистент без Lifestyle функціоналу.
106
-
107
- **Changes from current:**
108
- - Видалено: Lifestyle mode, Combined mode
109
- - Залишено: Medical dialog, Spiritual integration
110
- - Додано: Integration with SpiritualMonitor
111
-
112
- ## Data Models
113
-
114
- ```python
115
- from enum import Enum
116
- from dataclasses import dataclass
117
- from typing import List, Optional
118
-
119
- class SpiritualState(Enum):
120
- GREEN = "green" # Normal - no distress
121
- YELLOW = "yellow" # Potential - needs triage
122
- RED = "red" # Severe - needs referral
123
-
124
- class TriageOutcome(Enum):
125
- RESOLVED_GREEN = "resolved_green" # Patient OK, return to medical
126
- ESCALATE_RED = "escalate_red" # Distress confirmed, generate referral
127
- CONTINUE = "continue" # Need more information
128
-
129
- @dataclass
130
- class SpiritualAssessment:
131
- state: SpiritualState
132
- indicators: List[str]
133
- confidence: float
134
- reasoning: str
135
-
136
- @dataclass
137
- class TriageSession:
138
- question_count: int
139
- questions_asked: List[str]
140
- patient_responses: List[str]
141
- outcome: Optional[TriageOutcome]
142
-
143
- @dataclass
144
- class SessionState:
145
- spiritual_state: SpiritualState
146
- triage_session: Optional[TriageSession]
147
- conversation_history: List[str]
148
- ```
149
-
150
- ## Correctness Properties
151
-
152
- *A property is a characteristic or behavior that should hold true across all valid executions of a system-essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*
153
-
154
- ### Property 1: Spiritual Monitor Always Invoked
155
- *For any* patient message, the Spiritual Monitor SHALL be invoked to classify the message before generating a response.
156
- **Validates: Requirements 2.1**
157
-
158
- ### Property 2: Green State Preservation
159
- *For any* message classified as no-distress (GREEN), the system SHALL remain in GREEN state and continue medical dialog.
160
- **Validates: Requirements 2.2**
161
-
162
- ### Property 3: Yellow Triggers Triage
163
- *For any* message classified as potential-distress (YELLOW), the system SHALL enter YELLOW state and initiate Soft Triage.
164
- **Validates: Requirements 2.3**
165
-
166
- ### Property 4: Red Triggers Immediate Referral
167
- *For any* message classified as severe-distress (RED), the system SHALL generate a referral immediately without triage.
168
- **Validates: Requirements 2.4**
169
-
170
- ### Property 5: Triage Question Limit
171
- *For any* Soft Triage session, the number of clarifying questions SHALL NOT exceed 3.
172
- **Validates: Requirements 3.1, 7.2**
173
-
174
- ### Property 6: Triage Binary Outcome
175
- *For any* completed Soft Triage session, the outcome SHALL be either GREEN (resolved) or RED (escalated), never YELLOW.
176
- **Validates: Requirements 3.3**
177
-
178
- ### Property 7: Triage Timeout Escalation
179
- *For any* Soft Triage session that reaches 3 exchanges without clear resolution, the system SHALL escalate to RED.
180
- **Validates: Requirements 3.6**
181
-
182
- ### Property 8: State Validity
183
- *For any* point in conversation, the spiritual state SHALL be exactly one of: GREEN, YELLOW, or RED.
184
- **Validates: Requirements 5.1, 7.1**
185
-
186
- ### Property 9: Conservative Classification
187
- *For any* ambiguous message, the system SHALL prefer YELLOW over GREEN (conservative approach).
188
- **Validates: Requirements 5.2**
189
-
190
- ### Property 10: Red Flag Keywords
191
- *For any* message containing death, hopelessness, or suicidal ideation keywords, the classification SHALL be RED.
192
- **Validates: Requirements 5.4**
193
-
194
- ### Property 11: Referral Generation on Red
195
- *For any* RED state confirmation, the system SHALL generate a referral message.
196
- **Validates: Requirements 6.1**
197
-
198
- ### Property 12: Referral Content Completeness
199
- *For any* generated referral, the message SHALL contain: patient concerns, distress indicators, and conversation context.
200
- **Validates: Requirements 6.2**
201
-
202
- ### Property 13: Language Matching
203
- *For any* system response, the language SHALL match the patient's input language.
204
- **Validates: Requirements 8.1, 8.2, 8.3, 8.4**
205
-
206
- ### Property 14: Session Reset
207
- *For any* session end, the spiritual state SHALL reset to GREEN.
208
- **Validates: Requirements 7.4**
209
-
210
- ## Error Handling
211
-
212
- ### Classification Errors
213
- - If Spiritual Monitor fails → Default to YELLOW (conservative)
214
- - If triage question generation fails → Use fallback generic question
215
- - If referral generation fails → Provide crisis hotline information
216
-
217
- ### State Errors
218
- - Invalid state transition → Log error, maintain current state
219
- - Missing triage context → Reset to GREEN with warning
220
-
221
- ## Testing Strategy
222
-
223
- ### Unit Tests
224
- - SpiritualMonitor classification accuracy
225
- - SoftTriageManager question generation
226
- - SessionStateManager state transitions
227
- - Referral message content validation
228
-
229
- ### Property-Based Tests (fast-check)
230
- - Property 1-14 as defined above
231
- - Use generators for:
232
- - Random patient messages (with/without distress indicators)
233
- - Random conversation histories
234
- - Random triage responses
235
-
236
- ### Integration Tests
237
- - Full flow: GREEN → YELLOW → GREEN (resolved)
238
- - Full flow: GREEN → YELLOW → RED (escalated)
239
- - Full flow: GREEN → RED (immediate)
240
- - Language matching across all flows
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/simplified-spiritual-triage/requirements.md DELETED
@@ -1,106 +0,0 @@
1
- # Requirements Document
2
-
3
- ## Introduction
4
-
5
- Спрощена версія Medical Brain з інтегрованим фоновим моніторингом духовного здоров'я. Система базується на медичному діалозі з автоматичним виявленням ознак духовного/емоційного дистресу та делікатним психологічним тріажем при необхідності.
6
-
7
- ## Glossary
8
-
9
- - **Medical Dialog**: Базовий режим медичної консультації пацієнта
10
- - **Spiritual Monitor**: Фоновий класифікатор для виявлення ознак духовного дистресу
11
- - **Green State**: Нормальний стан - медичний діалог без ознак дистресу
12
- - **Yellow Flag**: Потенційні ознаки дистресу - потребує делікатного тріажу
13
- - **Red Flag**: Підтверджений серйозний дистрес - потребує негайного направлення
14
- - **Soft Triage**: Делікатне психологічне розпитування (2-3 питання) для уточнення стану
15
- - **Referral**: Направлення до служби духовної опіки (chaplain team)
16
-
17
- ## Requirements
18
-
19
- ### Requirement 1: Simplified Architecture
20
-
21
- **User Story:** As a system administrator, I want a simplified application architecture, so that the system is easier to maintain and more focused on core functionality.
22
-
23
- #### Acceptance Criteria
24
-
25
- 1. WHEN the application starts THEN the system SHALL operate in Medical mode as the default and only explicit mode
26
- 2. WHEN the Lifestyle mode code is removed THEN the system SHALL maintain all Medical and Spiritual functionality without errors
27
- 3. WHEN a user interacts with the system THEN the system SHALL present a single unified medical assistant interface
28
-
29
- ### Requirement 2: Background Spiritual Monitoring
30
-
31
- **User Story:** As a healthcare provider, I want the system to automatically monitor patient messages for spiritual distress indicators, so that patients in need receive appropriate support without explicit mode switching.
32
-
33
- #### Acceptance Criteria
34
-
35
- 1. WHEN a patient sends any message THEN the Spiritual Monitor SHALL analyze the message for distress indicators in the background
36
- 2. WHEN the Spiritual Monitor detects no distress indicators THEN the system SHALL continue normal Medical dialog (Green State)
37
- 3. WHEN the Spiritual Monitor detects potential distress indicators (Yellow Flag) THEN the system SHALL initiate Soft Triage
38
- 4. WHEN the Spiritual Monitor detects severe distress indicators (Red Flag) THEN the system SHALL immediately generate a referral and provide crisis support
39
-
40
- ### Requirement 3: Soft Psychological Triage
41
-
42
- **User Story:** As a patient experiencing emotional difficulties, I want the system to gently check on my wellbeing without being intrusive, so that I feel supported but not interrogated.
43
-
44
- #### Acceptance Criteria
45
-
46
- 1. WHEN Soft Triage is initiated THEN the system SHALL ask no more than 2-3 clarifying questions
47
- 2. WHEN asking clarifying questions THEN the system SHALL use empathetic, non-judgmental language in the patient's language
48
- 3. WHEN the patient responds to triage questions THEN the system SHALL evaluate responses to determine Green or Red outcome
49
- 4. WHEN Soft Triage determines the patient is coping well THEN the system SHALL return to Green State (Medical dialog) naturally
50
- 5. WHEN Soft Triage confirms significant distress THEN the system SHALL escalate to Red Flag with referral generation
51
- 6. WHEN Soft Triage exceeds 3 exchanges without resolution THEN the system SHALL make a conservative decision (escalate to Red if uncertain)
52
-
53
- ### Requirement 4: Seamless User Experience
54
-
55
- **User Story:** As a patient, I want the spiritual health monitoring to be invisible and natural, so that I don't feel like I'm being assessed or categorized.
56
-
57
- #### Acceptance Criteria
58
-
59
- 1. WHEN the system transitions between states THEN the patient SHALL NOT see explicit mode switching notifications
60
- 2. WHEN Soft Triage questions are asked THEN the questions SHALL feel like natural conversation continuation
61
- 3. WHEN returning from Yellow to Green state THEN the system SHALL smoothly continue medical conversation
62
- 4. WHEN escalating to Red Flag THEN the system SHALL communicate support compassionately without alarming language
63
-
64
- ### Requirement 5: Classification Logic
65
-
66
- **User Story:** As a clinical specialist, I want clear classification criteria for spiritual distress, so that the system makes consistent and appropriate decisions.
67
-
68
- #### Acceptance Criteria
69
-
70
- 1. WHEN classifying messages THEN the system SHALL use three levels: Green (none), Yellow (potential), Red (severe)
71
- 2. WHEN uncertain between Green and Yellow THEN the system SHALL default to Yellow for safety
72
- 3. WHEN uncertain between Yellow and Red THEN the system SHALL use Soft Triage to clarify
73
- 4. WHEN the patient mentions death, hopelessness, or suicidal ideation THEN the system SHALL classify as Red Flag immediately
74
-
75
- ### Requirement 6: Referral Generation
76
-
77
- **User Story:** As a chaplain, I want to receive clear, actionable referral messages, so that I can provide appropriate spiritual care to patients in need.
78
-
79
- #### Acceptance Criteria
80
-
81
- 1. WHEN a Red Flag is confirmed THEN the system SHALL generate a professional referral message
82
- 2. WHEN generating referrals THEN the system SHALL include patient concerns, distress indicators, and conversation context
83
- 3. WHEN generating referrals THEN the system SHALL use multi-faith inclusive language
84
- 4. WHEN generating referrals THEN the system SHALL write in the patient's language
85
-
86
- ### Requirement 7: State Management
87
-
88
- **User Story:** As a developer, I want clear state management for the spiritual monitoring flow, so that the system behavior is predictable and debuggable.
89
-
90
- #### Acceptance Criteria
91
-
92
- 1. WHEN tracking conversation state THEN the system SHALL maintain current spiritual state (Green/Yellow/Red)
93
- 2. WHEN in Yellow state THEN the system SHALL track triage question count (max 3)
94
- 3. WHEN state changes THEN the system SHALL log the transition for debugging
95
- 4. WHEN session ends THEN the system SHALL reset spiritual state to Green
96
-
97
- ### Requirement 8: Language Support
98
-
99
- **User Story:** As a Ukrainian-speaking patient, I want all system responses in my language, so that I can communicate naturally and feel understood.
100
-
101
- #### Acceptance Criteria
102
-
103
- 1. WHEN the patient writes in Ukrainian THEN the system SHALL respond in Ukrainian
104
- 2. WHEN the patient writes in English THEN the system SHALL respond in English
105
- 3. WHEN generating triage questions THEN the system SHALL match the patient's language
106
- 4. WHEN generating referrals THEN the system SHALL match the patient's language
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/simplified-spiritual-triage/tasks.md DELETED
@@ -1,215 +0,0 @@
1
- # Implementation Plan
2
-
3
- ## Phase 1: Create Simplified Architecture (Alternative Approach)
4
-
5
- **Note:** Instead of modifying the existing codebase, we created a new simplified implementation that can run alongside the existing one. This allows for gradual migration and testing.
6
-
7
- - [x] 1. Create new simplified components ✅
8
- - [x] 1.1 Create SimplifiedMedicalApp (src/core/simplified_medical_app.py) ✅
9
- - Medical-only mode with background spiritual monitoring
10
- - No Lifestyle mode
11
- - _Requirements: 1.1, 1.2_
12
- - [x] 1.2 Create simplified Gradio interface (src/interface/simplified_gradio_app.py) ✅
13
- - Single unified medical interface
14
- - No mode selector
15
- - _Requirements: 1.3_
16
- - [x] 1.3 Create launch script (run_simplified_app.py) ✅
17
- - Easy launch for simplified version
18
- - _Requirements: 1.1_
19
-
20
- **Cleanup tasks (optional, for later):**
21
- - [ ] 1.4 Remove old Lifestyle code (when ready to fully migrate)
22
- - Delete src/core/combined_assistant.py
23
- - Remove LIFESTYLE, COMBINED from AssistantMode enum
24
- - Update lifestyle_app.py
25
- - _Requirements: 1.2_
26
-
27
- ## Phase 2: Implement Spiritual State Machine
28
-
29
- - [x] 2. Create SpiritualState and data models
30
- - [x] 2.1 Create src/core/spiritual_state.py with enums and dataclasses ✅
31
- - SpiritualState enum (GREEN, YELLOW, RED)
32
- - TriageOutcome enum
33
- - SpiritualAssessment dataclass
34
- - TriageSession dataclass
35
- - SessionSpiritualState class (combined state manager)
36
- - _Requirements: 5.1, 7.1_
37
- - [x] 2.2 Write property test for state validity ✅
38
- - **Property 8: State Validity** - 5 tests
39
- - **Validates: Requirements 5.1, 7.1**
40
-
41
- - [x] 3. Implement SessionStateManager
42
- - [x] 3.1 Create SessionStateManager class ✅
43
- - Track current spiritual state
44
- - Track triage question count
45
- - Implement state transitions
46
- - _Requirements: 7.1, 7.2_
47
- - [x] 3.2 Write property test for session reset ✅
48
- - **Property 14: Session Reset** - 5 tests
49
- - **Validates: Requirements 7.4**
50
-
51
- ## Phase 3: Implement Spiritual Monitor
52
-
53
- - [x] 4. Refactor SpiritualDistressAnalyzer to SpiritualMonitor
54
- - [x] 4.1 Simplify classification to GREEN/YELLOW/RED ✅
55
- - Created new src/core/spiritual_monitor.py
56
- - Return SpiritualState instead of DistressClassification
57
- - _Requirements: 2.1, 5.1_
58
- - [ ] 4.2 Write property test for monitor invocation
59
- - **Property 1: Spiritual Monitor Always Invoked**
60
- - **Validates: Requirements 2.1**
61
- - [x] 4.3 Write property test for conservative classification ✅
62
- - **Property 9: Conservative Classification** - 4 tests
63
- - **Validates: Requirements 5.2**
64
- - [x] 4.4 Write property test for red flag keywords ✅
65
- - **Property 10: Red Flag Keywords** - 8 tests
66
- - **Validates: Requirements 5.4**
67
-
68
- - [x] 5. Checkpoint - Ensure all tests pass ✅
69
- - 22 state property tests passed
70
- - 42 monitor property tests passed
71
- - Total: 64 tests passing
72
-
73
- ## Phase 4: Implement Soft Triage Manager
74
-
75
- - [x] 6. Create SoftTriageManager ✅
76
- - [x] 6.1 Implement triage question generation ✅
77
- - Generate empathetic clarifying questions
78
- - Use LLM with appropriate prompt
79
- - Match patient language
80
- - _Requirements: 3.1, 3.2, 8.3_
81
- - [x] 6.2 Implement response evaluation ✅
82
- - Evaluate patient responses
83
- - Determine TriageOutcome (RESOLVED_GREEN, ESCALATE_RED, CONTINUE)
84
- - _Requirements: 3.3_
85
- - [x] 6.3 Implement question limit enforcement ✅
86
- - Track question count (max 3)
87
- - Force decision after 3 exchanges
88
- - _Requirements: 3.1, 3.6_
89
- - [x] 6.4 Write property test for triage question limit ✅
90
- - **Property 5: Triage Question Limit** - 4 tests
91
- - **Validates: Requirements 3.1, 7.2**
92
- - [x] 6.5 Write property test for triage binary outcome ✅
93
- - **Property 6: Triage Binary Outcome** - 5 tests
94
- - **Validates: Requirements 3.3**
95
- - [x] 6.6 Write property test for triage timeout escalation ✅
96
- - **Property 7: Triage Timeout Escalation** - 3 tests
97
- - **Validates: Requirements 3.6**
98
-
99
- ## Phase 5: Integrate into Main App
100
-
101
- - [x] 7. Integrate Spiritual Monitor into message processing ✅
102
- - [x] 7.1 Update process_message to use SpiritualMonitor ✅
103
- - Created SimplifiedMedicalApp with integrated monitoring
104
- - Call monitor for every message
105
- - Route based on SpiritualState
106
- - _Requirements: 2.1, 2.2, 2.3, 2.4_
107
- - [x] 7.2 Write property test for green state preservation ✅
108
- - **Property 2: Green State Preservation** - 4 tests
109
- - **Validates: Requirements 2.2**
110
- - [x] 7.3 Write property test for yellow triggers triage ✅
111
- - **Property 3: Yellow Triggers Triage** - 4 tests
112
- - **Validates: Requirements 2.3**
113
- - [x] 7.4 Write property test for red triggers referral ✅
114
- - **Property 4: Red Triggers Immediate Referral** - 8 tests
115
- - **Validates: Requirements 2.4**
116
-
117
- - [x] 8. Implement state transitions in app ✅
118
- - [x] 8.1 Handle GREEN → YELLOW transition ✅
119
- - Initiate SoftTriageManager
120
- - Generate first triage question
121
- - _Requirements: 2.3, 3.1_
122
- - [x] 8.2 Handle YELLOW → GREEN transition (resolved) ✅
123
- - Return to medical dialog
124
- - Reset triage session
125
- - _Requirements: 3.4_
126
- - [x] 8.3 Handle YELLOW → RED transition (escalated) ✅
127
- - Generate referral
128
- - Provide crisis support
129
- - _Requirements: 3.5, 6.1_
130
-
131
- - [x] 9. Checkpoint - Ensure all tests pass ✅
132
- - 113 tests passing (22 state + 42 monitor + 22 triage + 27 integration)
133
-
134
- ## Phase 6: Update Referral Generation
135
-
136
- - [x] 10. Ensure referral generation works with new flow ✅
137
- - [x] 10.1 Update ReferralMessageGenerator for simplified flow ✅
138
- - Integrated into SimplifiedMedicalApp._generate_referral
139
- - Accept SpiritualAssessment instead of DistressClassification
140
- - Include triage context if available
141
- - _Requirements: 6.1, 6.2_
142
- - [x] 10.2 Write property test for referral generation on red ✅
143
- - **Property 11: Referral Generation on Red** - 3 tests
144
- - **Validates: Requirements 6.1**
145
- - [x] 10.3 Write property test for referral content completeness ✅
146
- - **Property 12: Referral Content Completeness** - 4 tests
147
- - **Validates: Requirements 6.2**
148
-
149
- ## Phase 7: Language Support
150
-
151
- - [x] 11. Ensure language matching across all components ✅
152
- - [x] 11.1 Verify SpiritualMonitor language handling ✅
153
- - Classification reasoning in patient language
154
- - _Requirements: 8.1, 8.2_
155
- - [x] 11.2 Verify SoftTriageManager language handling ✅
156
- - Questions in patient language
157
- - Fallback questions in both languages
158
- - _Requirements: 8.3_
159
- - [x] 11.3 Verify ReferralMessageGenerator language handling ✅
160
- - Crisis responses in patient language
161
- - Triage resolution in patient language
162
- - _Requirements: 8.4_
163
- - [x] 11.4 Write property test for language matching ✅
164
- - **Property 13: Language Matching** - 10 tests
165
- - **Validates: Requirements 8.1, 8.2, 8.3, 8.4**
166
-
167
- ## Phase 8: UI Simplification
168
-
169
- - [x] 12. Simplify Gradio interface ✅
170
- - [x] 12.1 Remove mode selector from UI ✅
171
- - Created simplified_gradio_app.py
172
- - Single medical assistant interface
173
- - No visible mode switching
174
- - _Requirements: 1.3, 4.1_
175
- - [x] 12.2 Update status display ✅
176
- - Show spiritual state for debugging (optional)
177
- - Clean user-facing interface
178
- - _Requirements: 4.1_
179
- - [x] 12.3 Remove Edit Prompts for Lifestyle ✅
180
- - Simplified interface has no prompt editing
181
- - _Requirements: 1.1_
182
-
183
- ## Phase 9: Final Testing and Cleanup
184
-
185
- - [x] 13. Final integration testing ✅
186
- - [x] 13.1 Test full flow: GREEN → YELLOW → GREEN ✅
187
- - Property test: test_green_to_yellow_to_green_flow
188
- - _Requirements: 2.2, 2.3, 3.4_
189
- - [x] 13.2 Test full flow: GREEN → YELLOW → RED ✅
190
- - Property test: test_green_to_yellow_to_red_flow
191
- - _Requirements: 2.3, 3.5, 6.1_
192
- - [x] 13.3 Test full flow: GREEN → RED (immediate) ✅
193
- - Property test: test_green_to_red_immediate_flow
194
- - _Requirements: 2.4, 6.1_
195
- - [x] 13.4 Test language switching ✅
196
- - Property tests for English and Ukrainian
197
- - _Requirements: 8.1, 8.2_
198
-
199
- - [ ] 14. Cleanup and documentation
200
- - [ ] 14.1 Remove unused Lifestyle code files
201
- - Delete deprecated files
202
- - Update imports
203
- - _Requirements: 1.2_
204
- - [ ] 14.2 Update README for simplified architecture
205
- - Document new flow
206
- - Update quick start guide
207
- - _Requirements: 1.1_
208
-
209
- - [x] 15. Final Checkpoint - Property Tests ✅
210
- - **130 tests passing**
211
- - 22 state property tests
212
- - 42 monitor property tests
213
- - 22 triage property tests
214
- - 27 integration property tests
215
- - 17 referral/language property tests
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/spiritual-health-assessment/design.md DELETED
@@ -1,558 +0,0 @@
1
- # Design Document - Spiritual Health Assessment Tool
2
-
3
- ## Overview
4
-
5
- The Spiritual Health Assessment Tool is a clinical decision support application that helps healthcare providers identify patients who may benefit from spiritual care services. The system leverages Large Language Models (LLMs) to analyze patient conversations, detect emotional and spiritual distress indicators, classify severity levels, and generate appropriate referral messages. The tool includes a validation interface where clinical staff can review AI assessments and provide feedback to improve system accuracy over time.
6
-
7
- **Key Design Principles:**
8
- - **Safety-first approach**: Conservative classification with human oversight
9
- - **Reuse existing architecture**: Leverage proven patterns from Lifestyle Journey project
10
- - **Simple, testable components**: Clear separation of concerns
11
- - **Feedback-driven improvement**: Store provider feedback for system refinement
12
- - **Multi-faith sensitivity**: Inclusive language and approach
13
-
14
- ## Architecture
15
-
16
- ### High-Level Architecture
17
-
18
- ```mermaid
19
- graph TD
20
- A[Patient Input] --> B[Distress Analyzer]
21
- B --> C{Classification}
22
- C -->|Red Flag| D[Referral Generator]
23
- C -->|Yellow Flag| E[Question Generator]
24
- C -->|No Flag| F[No Action]
25
- E --> G[Follow-up Analysis]
26
- G --> C
27
- D --> H[Validation Interface]
28
- H --> I[Provider Feedback]
29
- I --> J[Feedback Storage]
30
- ```
31
-
32
- ### Component Architecture
33
-
34
- The system **reuses existing Lifestyle Journey architecture** with minimal new components:
35
-
36
- ```
37
- spiritual-health-assessment/
38
- ├── src/
39
- │ ├── core/
40
- │ │ ├── ai_client.py # ✅ REUSED: AIClientManager
41
- │ │ ├── core_classes.py # ✅ REUSED: Base dataclasses pattern
42
- │ │ └── spiritual_classes.py # 🆕 NEW: Spiritual-specific classes
43
- │ ├── interface/
44
- │ │ ├── gradio_app.py # ✅ REUSED: Gradio patterns
45
- │ │ └── spiritual_interface.py # 🆕 NEW: Spiritual validation UI
46
- │ ├── prompts/
47
- │ │ └── spiritual_prompts.py # 🆕 NEW: Spiritual LLM prompts
48
- │ └── storage/
49
- │ └── feedback_store.py # 🆕 NEW: Feedback persistence
50
- ├── data/
51
- │ └── spiritual_distress_definitions.json # Parsed from PDF
52
- ├── spiritual_app.py # 🆕 NEW: Main entry point
53
- └── requirements.txt # ✅ REUSED: Same dependencies
54
- ```
55
-
56
- **Reuse Strategy:**
57
- - **AIClientManager**: Use existing multi-provider AI client management
58
- - **Dataclass patterns**: Follow ClinicalBackground/LifestyleProfile structure
59
- - **Gradio patterns**: Reuse SessionData, session isolation, tab structure
60
- - **Prompt patterns**: Follow existing SYSTEM_PROMPT_* and PROMPT_* conventions
61
- - **Testing patterns**: Adapt TestingDataManager approach for feedback storage
62
-
63
- ## Components and Interfaces
64
-
65
- ### 1. Core Data Classes (`spiritual_classes.py`)
66
-
67
- **Following existing dataclass patterns from core_classes.py:**
68
-
69
- **PatientInput** (similar to ChatMessage)
70
- ```python
71
- @dataclass
72
- class PatientInput:
73
- message: str
74
- timestamp: str # ISO format like ChatMessage
75
- conversation_history: List[str] = None
76
-
77
- def __post_init__(self):
78
- if self.conversation_history is None:
79
- self.conversation_history = []
80
- ```
81
-
82
- **DistressClassification** (similar to SessionState)
83
- ```python
84
- @dataclass
85
- class DistressClassification:
86
- flag_level: str # "red", "yellow", "none"
87
- indicators: List[str] = None
88
- categories: List[str] = None
89
- confidence: float = 0.0
90
- reasoning: str = ""
91
- timestamp: str = ""
92
-
93
- def __post_init__(self):
94
- if self.indicators is None:
95
- self.indicators = []
96
- if self.categories is None:
97
- self.categories = []
98
- if not self.timestamp:
99
- self.timestamp = datetime.now().isoformat()
100
- ```
101
-
102
- **ReferralMessage** (similar to ChatMessage structure)
103
- ```python
104
- @dataclass
105
- class ReferralMessage:
106
- patient_concerns: str
107
- distress_indicators: List[str] = None
108
- context: str = ""
109
- message_text: str = ""
110
- timestamp: str = ""
111
-
112
- def __post_init__(self):
113
- if self.distress_indicators is None:
114
- self.distress_indicators = []
115
- if not self.timestamp:
116
- self.timestamp = datetime.now().isoformat()
117
- ```
118
-
119
- **ProviderFeedback** (similar to SessionState tracking)
120
- ```python
121
- @dataclass
122
- class ProviderFeedback:
123
- assessment_id: str
124
- provider_id: str = "provider_001"
125
- agrees_with_classification: bool = False
126
- agrees_with_referral: bool = False
127
- comments: str = ""
128
- timestamp: str = ""
129
-
130
- def __post_init__(self):
131
- if not self.timestamp:
132
- self.timestamp = datetime.now().isoformat()
133
- ```
134
-
135
- ### 2. Spiritual Distress Analyzer (`spiritual_analyzer.py`)
136
-
137
- **SpiritualDistressAnalyzer** (follows EntryClassifier/MedicalAssistant pattern)
138
- - **Purpose**: Main orchestrator for distress detection and classification
139
- - **Initialization**: `def __init__(self, api: AIClientManager)` - reuses existing AI client
140
- - **Methods**:
141
- - `analyze_message(patient_input: PatientInput) -> DistressClassification`
142
- - `generate_clarifying_questions(classification: DistressClassification) -> List[str]`
143
- - `re_evaluate_with_followup(original_input, followup_answers) -> DistressClassification`
144
-
145
- **Implementation approach** (following existing patterns):
146
- - Uses `self.api.generate_response()` like other assistants
147
- - Follows SYSTEM_PROMPT_* and PROMPT_* function pattern from prompts.py
148
- - Implements conservative classification logic (when uncertain, escalate to yellow flag)
149
- - Maintains conversation context similar to MainLifestyleAssistant
150
- - Uses JSON response parsing like EntryClassifier
151
-
152
- ### 3. Referral Message Generator (`spiritual_analyzer.py`)
153
-
154
- **ReferralMessageGenerator**
155
- - **Purpose**: Creates professional referral messages for spiritual care team
156
- - **Methods**:
157
- - `generate_referral(classification: DistressClassification, patient_input: PatientInput) -> ReferralMessage`
158
-
159
- **Message structure**:
160
- - Patient's expressed concerns (direct quotes when appropriate)
161
- - Specific distress indicators detected
162
- - Relevant conversation context
163
- - Professional, compassionate tone
164
- - Multi-faith inclusive language
165
-
166
- ### 4. Question Generator (`spiritual_analyzer.py`)
167
-
168
- **ClarifyingQuestionGenerator**
169
- - **Purpose**: Generates empathetic follow-up questions for yellow flag cases
170
- - **Methods**:
171
- - `generate_questions(classification: DistressClassification) -> List[str]`
172
-
173
- **Question characteristics**:
174
- - Open-ended to encourage patient expression
175
- - Clinically appropriate and empathetic
176
- - Focused on clarifying ambiguous indicators
177
- - Maximum 2-3 questions to avoid overwhelming patient
178
-
179
- ### 5. Validation Interface (`gradio_interface.py`)
180
-
181
- **UI Components**:
182
- - **Input Panel**: Text area for patient message input
183
- - **Results Display**:
184
- - Classification badge (red/yellow/green color-coded)
185
- - Detected indicators list
186
- - LLM reasoning explanation
187
- - Generated referral message (if applicable)
188
- - Generated questions (if yellow flag)
189
- - **Feedback Panel**:
190
- - Agreement checkboxes (classification, referral message)
191
- - Comments text area
192
- - Submit feedback button
193
- - **History Panel**: Previous assessments with feedback status
194
-
195
- **Interface Features**:
196
- - Real-time assessment processing
197
- - Clear visual hierarchy with color coding
198
- - Responsive design for clinical workflows
199
- - Export functionality for feedback data
200
-
201
- ### 6. Feedback Storage (`feedback_store.py`)
202
-
203
- **FeedbackStore**
204
- - **Purpose**: Persist provider feedback for analysis and improvement
205
- - **Methods**:
206
- - `save_feedback(feedback: ProviderFeedback) -> str` # Returns feedback_id
207
- - `get_feedback_by_id(feedback_id: str) -> ProviderFeedback`
208
- - `get_all_feedback() -> List[ProviderFeedback]`
209
- - `export_to_csv(output_path: str) -> bool`
210
- - `get_accuracy_metrics() -> Dict`
211
-
212
- **Storage format**: JSON files with structured records
213
- - One file per assessment with feedback
214
- - Indexed by assessment_id for quick retrieval
215
- - Includes full context for later analysis
216
-
217
- ### 7. Reference Data Loader (`spiritual_analyzer.py`)
218
-
219
- **SpiritualDistressDefinitions**
220
- - **Purpose**: Load and manage spiritual distress definitions from reference document
221
- - **Methods**:
222
- - `load_definitions(file_path: str) -> Dict`
223
- - `get_definition(category: str) -> str`
224
- - `get_all_categories() -> List[str]`
225
-
226
- **Data structure**:
227
- ```python
228
- {
229
- "category_name": {
230
- "definition": "...",
231
- "red_flag_examples": ["...", "..."],
232
- "yellow_flag_examples": ["...", "..."],
233
- "keywords": ["...", "..."]
234
- }
235
- }
236
- ```
237
-
238
- ## Data Models
239
-
240
- ### Assessment Record
241
- ```json
242
- {
243
- "assessment_id": "uuid",
244
- "timestamp": "2025-12-04T10:30:00Z",
245
- "patient_input": {
246
- "message": "I am angry all the time",
247
- "conversation_history": []
248
- },
249
- "classification": {
250
- "flag_level": "red",
251
- "indicators": ["persistent anger", "emotional distress"],
252
- "categories": ["anger", "emotional_suffering"],
253
- "confidence": 0.92,
254
- "reasoning": "Patient explicitly states persistent anger..."
255
- },
256
- "referral_message": {
257
- "patient_concerns": "Persistent anger affecting daily life",
258
- "distress_indicators": ["anger", "emotional_distress"],
259
- "context": "Patient reports feeling angry all the time",
260
- "message_text": "Referral for spiritual care: Patient expressing..."
261
- },
262
- "provider_feedback": {
263
- "provider_id": "provider_123",
264
- "agrees_with_classification": true,
265
- "agrees_with_referral": true,
266
- "comments": "Accurate assessment",
267
- "timestamp": "2025-12-04T10:35:00Z"
268
- }
269
- }
270
- ```
271
-
272
- ### Spiritual Distress Definitions
273
- ```json
274
- {
275
- "anger": {
276
- "definition": "Persistent feelings of anger, resentment, or hostility",
277
- "red_flag_examples": [
278
- "I am angry all the time",
279
- "I can't control my rage",
280
- "I hate everyone"
281
- ],
282
- "yellow_flag_examples": [
283
- "I've been feeling frustrated lately",
284
- "Things are bothering me more than usual"
285
- ],
286
- "keywords": ["angry", "rage", "resentment", "hostility", "furious"]
287
- },
288
- "persistent_sadness": {
289
- "definition": "Ongoing feelings of sadness, grief, or depression",
290
- "red_flag_examples": [
291
- "I am crying all the time",
292
- "I can't stop feeling sad",
293
- "Life has no meaning anymore"
294
- ],
295
- "yellow_flag_examples": [
296
- "I've been feeling down",
297
- "I cry more than I used to"
298
- ],
299
- "keywords": ["sad", "crying", "depressed", "grief", "hopeless"]
300
- }
301
- }
302
- ```
303
-
304
- ## Correctness Properties
305
-
306
- *A property is a characteristic or behavior that should hold true across all valid executions of a system-essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*
307
-
308
- ### Property 1: Analysis execution for all inputs
309
- *For any* patient message submitted, the System should return a classification object with flag_level, indicators, and reasoning fields
310
- **Validates: Requirements 1.1**
311
-
312
- ### Property 2: Classification uses definitions
313
- *For any* patient message with known distress indicators from the definitions, the System should classify them into the corresponding predefined categories
314
- **Validates: Requirements 1.2**
315
-
316
- ### Property 3: Multi-category detection completeness
317
- *For any* patient input containing multiple distress indicators from different categories, the System should identify all applicable categories in the classification
318
- **Validates: Requirements 1.3**
319
-
320
- ### Property 4: Response time performance
321
- *For any* patient message submission, the System should return classification results within 5 seconds
322
- **Validates: Requirements 1.4**
323
-
324
- ### Property 5: No-flag classification for neutral input
325
- *For any* patient input containing no distress indicators, the System should return a classification with flag_level "none"
326
- **Validates: Requirements 1.5**
327
-
328
- ### Property 6: Red flag detection for severe distress
329
- *For any* patient input containing explicit severe distress statements from the red flag definitions, the System should classify it with flag_level "red"
330
- **Validates: Requirements 2.1**
331
-
332
- ### Property 7: Referral generation for red flags
333
- *For any* classification with flag_level "red", the System should generate a referral message
334
- **Validates: Requirements 2.4, 4.1**
335
-
336
- ### Property 8: Red flag indicator completeness
337
- *For any* patient input with multiple red flag indicators, the System should include all detected indicators in the classification
338
- **Validates: Requirements 2.5**
339
-
340
- ### Property 9: Yellow flag detection for ambiguous input
341
- *For any* patient input containing ambiguous distress indicators from yellow flag definitions, the System should classify it with flag_level "yellow"
342
- **Validates: Requirements 3.1**
343
-
344
- ### Property 10: Question generation for yellow flags
345
- *For any* classification with flag_level "yellow", the System should generate at least one clarifying question
346
- **Validates: Requirements 3.2**
347
-
348
- ### Property 11: Re-evaluation with follow-up
349
- *For any* yellow flag classification with follow-up answers provided, the System should produce a new classification that either escalates to red flag or clears to no flag
350
- **Validates: Requirements 3.3, 3.4**
351
-
352
- ### Property 12: Referral message includes patient concerns
353
- *For any* generated referral message, it should contain the patient's expressed concerns from the original input
354
- **Validates: Requirements 4.2**
355
-
356
- ### Property 13: Referral message includes indicators
357
- *For any* generated referral message, it should contain all specific distress indicators detected in the classification
358
- **Validates: Requirements 4.3**
359
-
360
- ### Property 14: Referral message includes context
361
- *For any* generated referral message, it should contain relevant conversation context
362
- **Validates: Requirements 4.4**
363
-
364
- ### Property 15: Feedback storage with unique ID
365
- *For any* provider feedback submission, the System should store it with a unique assessment_id
366
- **Validates: Requirements 6.1**
367
-
368
- ### Property 16: Feedback storage completeness
369
- *For any* stored feedback record, it should contain all required fields: original patient input, AI classification, reasoning, provider agreement status, comments, and timestamp
370
- **Validates: Requirements 6.2, 6.3, 6.4, 6.5, 6.6**
371
-
372
- ### Property 17: Feedback persistence round-trip
373
- *For any* feedback record stored with an assessment_id, retrieving it by that ID should return an equivalent feedback object
374
- **Validates: Requirements 6.7**
375
-
376
- ### Property 18: Religion-agnostic detection
377
- *For any* patient input with distress indicators, the System should detect them regardless of religious affiliation mentioned in the message
378
- **Validates: Requirements 7.1**
379
-
380
- ### Property 19: Inclusive referral language
381
- *For any* generated referral message, it should not contain denominational or religion-specific terms
382
- **Validates: Requirements 7.2**
383
-
384
- ### Property 20: Religious context preservation
385
- *For any* patient input mentioning specific religious concerns, the generated referral message should include those religious mentions
386
- **Validates: Requirements 7.3**
387
-
388
- ### Property 21: Non-assumptive questions
389
- *For any* generated clarifying questions for yellow flags, they should not contain assumptive religious language or denominational terms
390
- **Validates: Requirements 7.4**
391
-
392
- ### Property 22: Definition-based classification
393
- *For any* patient input analyzed, the System should reference the loaded spiritual distress definitions when determining categories
394
- **Validates: Requirements 9.2**
395
-
396
- ### Property 23: Definition validation
397
- *For any* spiritual distress definitions file loaded, the System should either successfully parse valid definitions or report specific validation errors
398
- **Validates: Requirements 9.4**
399
-
400
- ## Error Handling
401
-
402
- ### LLM API Errors
403
- - **Timeout**: Retry with exponential backoff (max 3 attempts)
404
- - **Rate limiting**: Queue requests and implement throttling
405
- - **Invalid response**: Log error, return conservative classification (yellow flag)
406
- - **Connection failure**: Display user-friendly error, suggest retry
407
-
408
- ### Data Validation Errors
409
- - **Invalid patient input**: Display validation message, highlight required fields
410
- - **Malformed definitions file**: Log specific errors, prevent system startup
411
- - **Corrupted feedback data**: Log error, continue operation, notify administrator
412
-
413
- ### Classification Edge Cases
414
- - **Ambiguous input**: Default to yellow flag for safety
415
- - **Multiple conflicting indicators**: Escalate to higher severity level
416
- - **Empty or very short input**: Request more information before classification
417
- - **Non-English input**: Attempt classification, note language in metadata
418
-
419
- ### Storage Errors
420
- - **Disk full**: Display error, attempt to free space, notify administrator
421
- - **Permission denied**: Log error, attempt alternative storage location
422
- - **Concurrent write conflicts**: Implement file locking or use atomic writes
423
-
424
- ## Testing Strategy
425
-
426
- ### Unit Testing
427
-
428
- **Test coverage areas**:
429
- - Data class initialization and validation
430
- - Classification logic with known inputs
431
- - Referral message generation with various scenarios
432
- - Question generation for different yellow flag types
433
- - Feedback storage and retrieval operations
434
- - Definition loading and parsing
435
-
436
- **Example unit tests**:
437
- - Test red flag detection with explicit distress statements
438
- - Test yellow flag generation with ambiguous inputs
439
- - Test referral message includes all required components
440
- - Test feedback storage round-trip (save and retrieve)
441
- - Test multi-language support with sample inputs
442
-
443
- ### Property-Based Testing
444
-
445
- **Property testing library**: Hypothesis (Python)
446
- **Minimum iterations per test**: 100
447
-
448
- **Property test requirements**:
449
- - Each property-based test must run minimum 100 iterations
450
- - Each test must reference its corresponding correctness property using format: `**Feature: spiritual-health-assessment, Property {number}: {property_text}**`
451
- - Each correctness property must be implemented by a single property-based test
452
-
453
- **Property test implementations**:
454
-
455
- 1. **Test red flag detection** (Property 1)
456
- - Generate random patient inputs with known red flag phrases
457
- - Verify all are classified as red flags
458
- - **Feature: spiritual-health-assessment, Property 1: Red flag detection completeness**
459
-
460
- 2. **Test yellow flag questions** (Property 2)
461
- - Generate random yellow flag classifications
462
- - Verify each produces at least one question
463
- - **Feature: spiritual-health-assessment, Property 2: Yellow flag clarification generation**
464
-
465
- 3. **Test referral message completeness** (Property 3)
466
- - Generate random red flag classifications with patient inputs
467
- - Verify all referral messages contain required fields
468
- - **Feature: spiritual-health-assessment, Property 3: Referral message generation for red flags**
469
-
470
- 4. **Test feedback storage** (Property 4)
471
- - Generate random feedback objects
472
- - Verify all fields are stored and retrievable
473
- - **Feature: spiritual-health-assessment, Property 4: Feedback storage completeness**
474
-
475
- 5. **Test language consistency** (Property 5)
476
- - Generate patient inputs in various languages
477
- - Verify outputs match input language
478
- - **Feature: spiritual-health-assessment, Property 5: Language consistency**
479
-
480
- 6. **Test classification consistency** (Property 6)
481
- - Generate random patient inputs
482
- - Run classification multiple times
483
- - Verify results are consistent within threshold
484
- - **Feature: spiritual-health-assessment, Property 6: Classification determinism**
485
-
486
- 7. **Test multi-category detection** (Property 7)
487
- - Generate inputs with multiple distress indicators
488
- - Verify all categories are detected
489
- - **Feature: spiritual-health-assessment, Property 7: Multi-category detection**
490
-
491
- 8. **Test feedback round-trip** (Property 8)
492
- - Generate random feedback records
493
- - Store and retrieve by ID
494
- - Verify equivalence
495
- - **Feature: spiritual-health-assessment, Property 8: Feedback persistence**
496
-
497
- ### Integration Testing
498
-
499
- **Integration test scenarios**:
500
- - End-to-end flow: patient input → classification → referral → feedback
501
- - UI interaction: submit message → view results → provide feedback
502
- - Data persistence: multiple assessments → export to CSV → verify data integrity
503
- - Definition loading: parse PDF → load definitions → use in classification
504
-
505
- ### Manual Testing
506
-
507
- **Clinical validation scenarios**:
508
- - Test with real patient conversation examples (anonymized)
509
- - Validate referral message quality with spiritual care team
510
- - Test multi-faith sensitivity with diverse scenarios
511
- - Verify UI usability with clinical staff
512
-
513
- ## Deployment Considerations
514
-
515
- ### Environment Setup
516
- - Python 3.9+
517
- - Gradio for UI framework
518
- - LLM API credentials (Gemini or alternative)
519
- - File system access for feedback storage
520
-
521
- ### Configuration
522
- - LLM provider selection (reuse AIClientManager from Lifestyle Journey)
523
- - Spiritual distress definitions file path
524
- - Feedback storage directory
525
- - Logging level and output
526
-
527
- ### Security
528
- - No PHI (Protected Health Information) stored in feedback
529
- - Provider authentication for feedback submission
530
- - Secure API key management
531
- - Audit logging for all assessments
532
-
533
- ### Performance
534
- - Target: < 5 seconds per assessment
535
- - Concurrent user support: 10+ simultaneous users
536
- - Feedback storage: scalable to 10,000+ records
537
- - UI responsiveness: < 100ms for user interactions
538
-
539
- ### Monitoring
540
- - Track classification distribution (red/yellow/none)
541
- - Monitor provider feedback agreement rates
542
- - Log LLM API performance and errors
543
- - Alert on system errors or degraded performance
544
-
545
- ## Future Enhancements
546
-
547
- ### Short-term
548
- - Export feedback data for analysis
549
- - Batch processing for multiple patient messages
550
- - Provider dashboard with accuracy metrics
551
- - Customizable distress definitions
552
-
553
- ### Long-term
554
- - Machine learning model trained on feedback data
555
- - Integration with EHR systems
556
- - Real-time collaboration features for spiritual care team
557
- - Multi-modal input support (voice, text)
558
- - Predictive analytics for proactive spiritual care outreach
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/spiritual-health-assessment/requirements.md DELETED
@@ -1,142 +0,0 @@
1
- # Requirements Document - Spiritual Health Assessment Tool
2
-
3
- ## Introduction
4
-
5
- The Spiritual Health Assessment Tool is a clinical decision support system designed to help healthcare providers identify patients who may benefit from spiritual care services. The system analyzes patient conversations to detect emotional and spiritual distress indicators, classifies them by severity (red flag or yellow flag), and generates appropriate referral messages to the spiritual care team. The tool includes a validation interface where clinical staff can review and provide feedback on the AI's assessments.
6
-
7
- ## Glossary
8
-
9
- - **System**: The Spiritual Health Assessment Tool
10
- - **Provider**: Healthcare professional (doctor, nurse, etc.) using the system
11
- - **Patient**: Individual receiving healthcare services
12
- - **Spiritual Service**: The clinical spiritual care team (chaplains, spiritual counselors)
13
- - **Red Flag**: Clear indicators of severe emotional/spiritual distress requiring immediate spiritual care referral
14
- - **Yellow Flag**: Potential indicators of distress requiring further assessment questions
15
- - **Assessment**: The process of analyzing patient input to determine spiritual distress level
16
- - **Referral Message**: Generated communication to the spiritual service team about a patient's needs
17
- - **Validation Interface**: UI component where providers review and approve/reject AI assessments
18
- - **Feedback Record**: Stored data about provider agreement/disagreement with system decisions
19
- - **LLM**: Large Language Model (AI) used for analysis and message generation
20
-
21
- ## Requirements
22
-
23
- ### Requirement 1: Spiritual Distress Detection
24
-
25
- **User Story:** As a healthcare provider, I want the system to automatically detect signs of spiritual or emotional distress in patient conversations, so that I can identify patients who may benefit from spiritual care services without having to manually screen every interaction.
26
-
27
- #### Acceptance Criteria
28
-
29
- 1. WHEN a patient message is submitted THEN the System SHALL analyze the text for emotional and spiritual distress indicators
30
- 2. WHEN distress indicators are detected THEN the System SHALL classify them according to the predefined spiritual distress definitions
31
- 3. WHEN multiple distress indicators are present THEN the System SHALL identify all applicable categories
32
- 4. WHEN the analysis is complete THEN the System SHALL return results within 5 seconds
33
- 5. WHEN patient input contains no distress indicators THEN the System SHALL return a classification indicating no spiritual care referral needed
34
-
35
- ### Requirement 2: Red Flag Classification
36
-
37
- **User Story:** As a healthcare provider, I want the system to identify clear signs of severe emotional distress, so that patients with urgent spiritual care needs can be referred immediately.
38
-
39
- #### Acceptance Criteria
40
-
41
- 1. WHEN patient input contains explicit statements of severe distress THEN the System SHALL classify the case as a red flag
42
- 2. WHEN red flag indicators include anger expressions (e.g., "I am angry all the time") THEN the System SHALL detect and flag them
43
- 3. WHEN red flag indicators include persistent sadness (e.g., "I am crying all the time") THEN the System SHALL detect and flag them
44
- 4. WHEN a red flag is identified THEN the System SHALL generate a referral message to the Spiritual Service
45
- 5. WHEN multiple red flag indicators are present THEN the System SHALL include all relevant indicators in the assessment
46
-
47
- ### Requirement 3: Yellow Flag Classification and Follow-up
48
-
49
- **User Story:** As a healthcare provider, I want the system to identify potential signs of distress that require further exploration, so that I can gather more information before making a referral decision.
50
-
51
- #### Acceptance Criteria
52
-
53
- 1. WHEN patient input contains ambiguous distress indicators THEN the System SHALL classify the case as a yellow flag
54
- 2. WHEN a yellow flag is identified THEN the System SHALL generate clarifying questions to gather more information
55
- 3. WHEN clarifying questions are answered THEN the System SHALL re-evaluate the classification based on the additional information
56
- 4. WHEN yellow flag assessment is complete THEN the System SHALL either escalate to red flag or clear the concern
57
- 5. WHEN generating clarifying questions THEN the System SHALL create questions that are empathetic and clinically appropriate
58
-
59
- ### Requirement 4: Referral Message Generation
60
-
61
- **User Story:** As a member of the spiritual care team, I want to receive clear, informative referral messages about patients, so that I can understand their needs and provide appropriate support.
62
-
63
- #### Acceptance Criteria
64
-
65
- 1. WHEN a red flag is confirmed THEN the System SHALL generate a referral message for the Spiritual Service
66
- 2. WHEN generating a referral message THEN the System SHALL include the patient's expressed concerns
67
- 3. WHEN generating a referral message THEN the System SHALL include the specific distress indicators detected
68
- 4. WHEN generating a referral message THEN the System SHALL include relevant context from the conversation
69
- 5. WHEN generating a referral message THEN the System SHALL use professional, compassionate language appropriate for clinical communication
70
-
71
- ### Requirement 5: Validation Interface
72
-
73
- **User Story:** As a healthcare provider, I want to review the system's assessments and provide feedback, so that I can validate the AI's decisions and help improve the system over time.
74
-
75
- #### Acceptance Criteria
76
-
77
- 1. WHEN the System completes an assessment THEN the System SHALL display the classification (red flag, yellow flag, or no flag) in the validation interface
78
- 2. WHEN displaying an assessment THEN the System SHALL show the original patient input
79
- 3. WHEN displaying an assessment THEN the System SHALL show the generated referral message (if applicable)
80
- 4. WHEN displaying an assessment THEN the System SHALL show the reasoning behind the classification
81
- 5. WHEN a provider reviews an assessment THEN the System SHALL provide options to agree or disagree with the decision
82
- 6. WHEN a provider reviews an assessment THEN the System SHALL allow the provider to add comments or notes
83
-
84
- ### Requirement 6: Feedback Storage and Tracking
85
-
86
- **User Story:** As a system administrator, I want to store provider feedback on AI assessments, so that we can track accuracy, identify patterns, and improve the system over time.
87
-
88
- #### Acceptance Criteria
89
-
90
- 1. WHEN a provider submits feedback THEN the System SHALL store the feedback record with a unique identifier
91
- 2. WHEN storing feedback THEN the System SHALL include the original patient input
92
- 3. WHEN storing feedback THEN the System SHALL include the AI classification and reasoning
93
- 4. WHEN storing feedback THEN the System SHALL include the provider's agreement/disagreement decision
94
- 5. WHEN storing feedback THEN the System SHALL include any provider comments
95
- 6. WHEN storing feedback THEN the System SHALL include a timestamp
96
- 7. WHEN feedback is stored THEN the System SHALL persist the data in a structured format (JSON or database)
97
-
98
- ### Requirement 7: Multi-faith Sensitivity
99
-
100
- **User Story:** As a spiritual care coordinator, I want the system to be sensitive to diverse spiritual backgrounds, so that referrals are appropriate for patients of all faiths including Christians, Buddhists, and others.
101
-
102
- #### Acceptance Criteria
103
-
104
- 1. WHEN analyzing patient input THEN the System SHALL detect distress indicators regardless of religious affiliation
105
- 2. WHEN generating referral messages THEN the System SHALL use inclusive, non-denominational language
106
- 3. WHEN patient input mentions specific religious concerns THEN the System SHALL include this information in the referral
107
- 4. WHEN generating questions for yellow flags THEN the System SHALL avoid assumptions about patient's spiritual beliefs
108
-
109
- ### Requirement 8: Testing and Demonstration Interface
110
-
111
- **User Story:** As a clinical stakeholder, I want to test the system with various patient scenarios, so that I can evaluate its performance before deploying it in clinical workflows.
112
-
113
- #### Acceptance Criteria
114
-
115
- 1. WHEN accessing the testing interface THEN the System SHALL provide a text input area for patient messages
116
- 2. WHEN a test message is submitted THEN the System SHALL process it through the full assessment pipeline
117
- 3. WHEN displaying test results THEN the System SHALL show the classification, reasoning, and any generated messages
118
- 4. WHEN using the testing interface THEN the System SHALL allow multiple test cases to be run sequentially
119
- 5. WHEN test results are displayed THEN the System SHALL provide clear visual indicators for red flags, yellow flags, and no flags
120
-
121
- ### Requirement 9: Reference Data Integration
122
-
123
- **User Story:** As a system developer, I want to integrate the spiritual distress definitions and examples document, so that the AI has accurate reference material for classifications.
124
-
125
- #### Acceptance Criteria
126
-
127
- 1. WHEN the System initializes THEN the System SHALL load spiritual distress definitions from the reference document
128
- 2. WHEN analyzing patient input THEN the System SHALL use the loaded definitions as classification criteria
129
- 3. WHEN the reference document is updated THEN the System SHALL support reloading the definitions without code changes
130
- 4. WHEN definitions are loaded THEN the System SHALL validate the data structure and report any errors
131
-
132
- ### Requirement 10: User Interface Design
133
-
134
- **User Story:** As a healthcare provider, I want an intuitive, easy-to-use interface, so that I can quickly test scenarios and review assessments without extensive training.
135
-
136
- #### Acceptance Criteria
137
-
138
- 1. WHEN the application launches THEN the System SHALL display a clean, professional interface
139
- 2. WHEN displaying results THEN the System SHALL use color coding to distinguish red flags, yellow flags, and no flags
140
- 3. WHEN showing multiple assessments THEN the System SHALL organize them in a clear, scannable format
141
- 4. WHEN a provider interacts with the interface THEN the System SHALL provide immediate visual feedback for all actions
142
- 5. WHEN errors occur THEN the System SHALL display user-friendly error messages with guidance
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.kiro/specs/spiritual-health-assessment/tasks.md DELETED
@@ -1,225 +0,0 @@
1
- # Implementation Plan - Spiritual Health Assessment Tool
2
-
3
- - [x] 1. Set up project structure and core data classes (REUSE existing patterns)
4
- - Create spiritual_classes.py following existing dataclass patterns from core_classes.py
5
- - Implement PatientInput, DistressClassification, ReferralMessage, ProviderFeedback using @dataclass with __post_init__
6
- - Create data/ directory for spiritual_distress_definitions.json
7
- - Reuse existing AIClientManager from src/core/ai_client.py (no new AI client needed)
8
- - _Requirements: All requirements - foundational structure_
9
- - _Reuses: core_classes.py patterns, AIClientManager, dataclass structure_
10
-
11
- - [ ]* 1.1 Write property test for data class validation
12
- - **Property 1: Analysis execution for all inputs**
13
- - **Validates: Requirements 1.1**
14
-
15
- - [x] 2. Parse and load spiritual distress definitions
16
- - Extract definitions from PDF document into structured JSON format
17
- - Create SpiritualDistressDefinitions class with load_definitions(), get_definition(), get_all_categories()
18
- - Implement validation for definitions data structure
19
- - Store parsed definitions in data/spiritual_distress_definitions.json
20
- - _Requirements: 9.1, 9.2, 9.3, 9.4_
21
-
22
- - [ ]* 2.1 Write property test for definition loading
23
- - **Property 23: Definition validation**
24
- - **Validates: Requirements 9.4**
25
-
26
- - [x] 3. Implement spiritual distress analyzer core logic (FOLLOW existing assistant patterns)
27
- - Create SpiritualDistressAnalyzer class with __init__(self, api: AIClientManager)
28
- - Follow EntryClassifier/MedicalAssistant pattern: use self.api.generate_response()
29
- - Create SYSTEM_PROMPT_SPIRITUAL_ANALYZER and PROMPT_SPIRITUAL_ANALYZER functions in spiritual_prompts.py
30
- - Implement analyze_message() method returning JSON like EntryClassifier
31
- - Parse JSON response and create DistressClassification object
32
- - Implement conservative classification logic (default to yellow flag when uncertain)
33
- - _Requirements: 1.1, 1.2, 1.3, 1.4, 1.5, 2.1, 3.1_
34
- - _Reuses: AIClientManager, prompt patterns, JSON parsing approach_
35
-
36
- - [ ]* 3.1 Write property test for classification using definitions
37
- - **Property 2: Classification uses definitions**
38
- - **Validates: Requirements 1.2**
39
-
40
- - [ ]* 3.2 Write property test for multi-category detection
41
- - **Property 3: Multi-category detection completeness**
42
- - **Validates: Requirements 1.3**
43
-
44
- - [ ]* 3.3 Write property test for response time
45
- - **Property 4: Response time performance**
46
- - **Validates: Requirements 1.4**
47
-
48
- - [ ]* 3.4 Write property test for no-flag classification
49
- - **Property 5: No-flag classification for neutral input**
50
- - **Validates: Requirements 1.5**
51
-
52
- - [ ]* 3.5 Write property test for red flag detection
53
- - **Property 6: Red flag detection for severe distress**
54
- - **Validates: Requirements 2.1**
55
-
56
- - [ ]* 3.6 Write property test for yellow flag detection
57
- - **Property 9: Yellow flag detection for ambiguous input**
58
- - **Validates: Requirements 3.1**
59
-
60
- - [ ]* 3.7 Write property test for red flag indicator completeness
61
- - **Property 8: Red flag indicator completeness**
62
- - **Validates: Requirements 2.5**
63
-
64
- - [x] 4. Implement referral message generator (FOLLOW assistant pattern)
65
- - Create ReferralMessageGenerator class with __init__(self, api: AIClientManager)
66
- - Follow MedicalAssistant pattern for message generation
67
- - Create SYSTEM_PROMPT_REFERRAL_GENERATOR and PROMPT_REFERRAL_GENERATOR in spiritual_prompts.py
68
- - Implement generate_referral() method using self.api.generate_response()
69
- - Build prompts for professional, compassionate referral messages
70
- - Ensure multi-faith inclusive language in system prompt
71
- - Include patient concerns, indicators, and context in user prompt
72
- - _Requirements: 2.4, 4.1, 4.2, 4.3, 4.4, 4.5, 7.2, 7.3_
73
- - _Reuses: AIClientManager, MedicalAssistant message generation pattern_
74
-
75
- - [ ]* 4.1 Write property test for referral generation
76
- - **Property 7: Referral generation for red flags**
77
- - **Validates: Requirements 2.4, 4.1**
78
-
79
- - [ ]* 4.2 Write property test for referral message patient concerns
80
- - **Property 12: Referral message includes patient concerns**
81
- - **Validates: Requirements 4.2**
82
-
83
- - [ ]* 4.3 Write property test for referral message indicators
84
- - **Property 13: Referral message includes indicators**
85
- - **Validates: Requirements 4.3**
86
-
87
- - [ ]* 4.4 Write property test for referral message context
88
- - **Property 14: Referral message includes context**
89
- - **Validates: Requirements 4.4**
90
-
91
- - [ ]* 4.5 Write property test for inclusive referral language
92
- - **Property 19: Inclusive referral language**
93
- - **Validates: Requirements 7.2**
94
-
95
- - [ ]* 4.6 Write property test for religious context preservation
96
- - **Property 20: Religious context preservation**
97
- - **Validates: Requirements 7.3**
98
-
99
- - [x] 5. Implement clarifying question generator
100
- - Create ClarifyingQuestionGenerator class
101
- - Implement generate_questions() method for yellow flag cases
102
- - Build prompts for empathetic, open-ended questions
103
- - Limit to 2-3 questions maximum
104
- - Ensure questions avoid religious assumptions
105
- - _Requirements: 3.2, 3.5, 7.4_
106
-
107
- - [ ]* 5.1 Write property test for question generation
108
- - **Property 10: Question generation for yellow flags**
109
- - **Validates: Requirements 3.2**
110
-
111
- - [ ]* 5.2 Write property test for non-assumptive questions
112
- - **Property 21: Non-assumptive questions**
113
- - **Validates: Requirements 7.4**
114
-
115
- - [x] 6. Implement follow-up re-evaluation logic
116
- - Add re_evaluate_with_followup() method to SpiritualDistressAnalyzer
117
- - Implement logic to combine original input with follow-up answers
118
- - Ensure re-evaluation escalates to red flag or clears to no flag
119
- - _Requirements: 3.3, 3.4_
120
-
121
- - [ ]* 6.1 Write property test for re-evaluation
122
- - **Property 11: Re-evaluation with follow-up**
123
- - **Validates: Requirements 3.3, 3.4**
124
-
125
- - [x] 7. Implement multi-faith sensitivity features
126
- - Add religion-agnostic detection logic
127
- - Implement checks for denominational language in outputs
128
- - Add religious context extraction and preservation
129
- - Test with diverse religious scenarios
130
- - _Requirements: 7.1, 7.2, 7.3, 7.4_
131
-
132
- - [ ]* 7.1 Write property test for religion-agnostic detection
133
- - **Property 18: Religion-agnostic detection**
134
- - **Validates: Requirements 7.1**
135
-
136
- - [x] 8. Implement feedback storage system (ADAPT TestingDataManager pattern)
137
- - Create FeedbackStore class following TestingDataManager structure
138
- - Implement save_feedback() with UUID generation (like save_patient_profile)
139
- - Implement get_feedback_by_id() and get_all_feedback() (like get_all_test_sessions)
140
- - Implement export_to_csv() following export_results_to_csv pattern
141
- - Implement get_accuracy_metrics() for analytics
142
- - Use JSON file storage in testing_results/ directory pattern
143
- - Use atomic writes with temp files like existing code
144
- - _Requirements: 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7_
145
- - _Reuses: TestingDataManager patterns, JSON storage approach, CSV export_
146
-
147
- - [ ]* 8.1 Write property test for feedback storage with unique ID
148
- - **Property 15: Feedback storage with unique ID**
149
- - **Validates: Requirements 6.1**
150
-
151
- - [ ]* 8.2 Write property test for feedback completeness
152
- - **Property 16: Feedback storage completeness**
153
- - **Validates: Requirements 6.2, 6.3, 6.4, 6.5, 6.6**
154
-
155
- - [ ]* 8.3 Write property test for feedback persistence
156
- - **Property 17: Feedback persistence round-trip**
157
- - **Validates: Requirements 6.7**
158
-
159
- - [x] 9. Build validation interface with Gradio (REUSE existing Gradio patterns)
160
- - Create spiritual_interface.py following gradio_app.py structure
161
- - Reuse SessionData pattern for session isolation
162
- - Implement tabs structure like existing app (Assessment, History, Instructions)
163
- - Implement input panel with gr.Textbox following existing patterns
164
- - Implement results display with gr.Markdown for color-coded badges
165
- - Display detected indicators, reasoning, and generated messages in gr.Markdown
166
- - Add feedback panel with gr.Checkbox and gr.Textbox for comments
167
- - Implement history panel with gr.Dataframe like test results table
168
- - Use session-isolated event handlers pattern from existing code
169
- - _Requirements: 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 8.1, 8.2, 8.3, 8.4, 8.5, 10.2, 10.4, 10.5_
170
- - _Reuses: gradio_app.py structure, SessionData, tab patterns, event handlers_
171
-
172
- - [x] 10. Integrate all components into main application (FOLLOW existing app structure)
173
- - Create spiritual_app.py following lifestyle_app.py structure
174
- - Create SpiritualHealthApp class similar to ExtendedLifestyleJourneyApp
175
- - Initialize AIClientManager in __init__ like existing app
176
- - Wire together analyzer, generators, and storage as class attributes
177
- - Create process_assessment() method similar to process_message()
178
- - Connect UI to backend using session-isolated handlers
179
- - Reuse existing error handling patterns and logging setup
180
- - Use existing .env configuration approach
181
- - _Requirements: All requirements - integration_
182
- - _Reuses: lifestyle_app.py structure, AIClientManager, error handling, logging_
183
-
184
- - [x] 11. Implement error handling and edge cases
185
- - Add LLM API error handling with retry logic
186
- - Implement data validation error handling
187
- - Handle classification edge cases (ambiguous, empty input)
188
- - Add storage error handling
189
- - Implement user-friendly error messages in UI
190
- - _Requirements: 10.5_
191
-
192
- - [ ]* 11.1 Write unit tests for error handling scenarios
193
- - Test LLM timeout and retry logic
194
- - Test invalid input handling
195
- - Test storage failure recovery
196
- - _Requirements: 10.5_
197
-
198
- - [x] 12. Add export and analytics features
199
- - Implement CSV export functionality in FeedbackStore
200
- - Add accuracy metrics calculation
201
- - Create summary statistics for classifications
202
- - Add provider agreement rate tracking
203
- - _Requirements: 6.7_
204
-
205
- - [x] 13. Checkpoint - Ensure all tests pass
206
- - Ensure all tests pass, ask the user if questions arise.
207
-
208
- - [x] 14. Create deployment configuration (REUSE existing setup)
209
- - Reuse existing requirements.txt (no new dependencies needed - same Gradio, google-genai)
210
- - Reuse existing .env setup (GEMINI_API_KEY, LOG_PROMPTS)
211
- - Create spiritual_README.md following existing README.md structure
212
- - Document spiritual-specific configuration (definitions file path)
213
- - Reuse existing ai_providers_config.py for LLM provider configuration
214
- - Add deployment notes referencing existing HuggingFace Space setup
215
- - _Requirements: All requirements - deployment_
216
- - _Reuses: requirements.txt, .env setup, README structure, ai_providers_config.py_
217
-
218
- - [ ]* 14.1 Write integration tests for end-to-end flows
219
- - Test full pipeline: input → classification → referral → feedback
220
- - Test UI interaction flows
221
- - Test data persistence across sessions
222
- - _Requirements: All requirements - integration_
223
-
224
- - [x] 15. Final checkpoint - Ensure all tests pass
225
- - Ensure all tests pass, ask the user if questions arise.