본문으로 건너뛰기

P5 주간 재평가 - 구현 가이드

1. 개요

목적: 매주 치료 진행 상황을 종합적으로 평가하고, 4가지 경로 중 하나를 선택하여 치료 방향을 조정합니다.

트리거 조건:

  • 매주 일요일 오후 6시
  • 설문 회차 완료 시 (5주차, 9주차)
  • 위급 상황 감지 시 (즉시 실행)

결과물:

  1. 주간 평가 보고서
  2. 경로 결정 (SUCCESS/MISMATCH/BARRIER/CRITICAL)
  3. 치료 계획 조정안
  4. 다음 주 목표 설정

2. 4가지 경로 정의

2.1 SUCCESS 경로

interface SuccessPath {
type: "SUCCESS";
criteria: {
insomniaImproved: boolean; // ISI 점수 20% 이상 개선
comorbidityImproved: boolean; // 동반 증상 1개 이상 개선
engagementHigh: boolean; // Task 완료율 > 70%
};
actions: {
maintain: "현재 치료 강도 유지";
celebrate: "성과 축하 메시지";
reinforce: "효과적인 전략 강화";
};
}

2.2 MISMATCH 경로

interface MismatchPath {
type: "MISMATCH";
criteria: {
insomniaNotImproved: boolean; // ISI 개선 < 10%
otherSymptomsImproved: boolean; // PHQ-9, GAD-7 등 개선
engagementModerate: boolean; // Task 완료율 40-70%
};
actions: {
reassess: "가설 재검토";
pivot: "치료 모듈 변경";
explore: "새로운 접근법 시도";
};
}

2.3 BARRIER 경로

interface BarrierPath {
type: "BARRIER";
criteria: {
allMetricsStagnant: boolean; // 모든 지표 정체/악화
lowEngagement: boolean; // Task 완료율 < 40%
noImprovement: boolean; // 4주 이상 변화 없음
};
actions: {
identify: "장애물 파악";
simplify: "치료 단순화";
motivate: "동기 강화 개입";
};
}

2.4 CRITICAL_ISSUE 경로

interface CriticalPath {
type: "CRITICAL_ISSUE";
criteria: {
severeDepression: boolean; // PHQ-9 >= 20
severeAnxiety: boolean; // GAD-7 >= 15
suicidalIdeation: boolean; // PHQ-9 item 9 > 0
rapidDeterioration: boolean; // 급속 악화
};
actions: {
immediate: "즉시 개입 프로토콜";
referral: "전문가 연계 고려";
support: "위기 지원 자원 제공";
};
}

3. Flowise 플로우 구성

3.1 플로우 다이어그램

[주간 트리거] → [데이터 수집] → [변화 분석] → [경로 결정] → [치료 조정] → [보고서 생성]
↓ ↓ ↓ ↓ ↓
시간/이벤트 7일 데이터 개선도 계산 4개 경로 조정안 작성

3.2 핵심 노드 설정

Weekly Data Aggregator

Type: Parallel MCP Calls
Tools:
- getWeeklySleepMetrics
- getWeeklyTaskCompletion
- getWeeklyMoodTrends
- getLearningEngagement
- getQuestionnaireScores (if available)

Processing:
- Calculate week-over-week changes
- Identify patterns and trends
- Flag concerning changes

Improvement Calculator

Type: Analytics Engine
Metrics:
Sleep:
- efficiency_change: (current - baseline) / baseline
- consistency_score: 1 - (std_dev(bedtimes) / mean)
- quality_trend: linear_regression(quality_scores)

Psychological:
- mood_trajectory: weighted_average(daily_moods)
- anxiety_peaks: count(anxiety > threshold)
- depression_trend: phq9_current vs phq9_previous

Engagement:
- task_completion_rate: completed / assigned
- learning_progress: lessons_completed / total_lessons
- consistency_score: active_days / 7

Path Decision Engine

Type: Rule-Based Decision Tree
Priority Order:
1. Check CRITICAL criteria first
2. If not CRITICAL, check SUCCESS criteria
3. If not SUCCESS, check MISMATCH criteria
4. Default to BARRIER if none above

Rules:
CRITICAL:
- PHQ9 >= 20 → IMMEDIATE
- GAD7 >= 15 → IMMEDIATE
- Suicidal ideation → IMMEDIATE
- Sleep efficiency < 50% for 3+ days → HIGH

SUCCESS:
- ISI improved >= 20% AND
- At least 1 comorbidity improved AND
- Engagement > 70%

MISMATCH:
- ISI improved < 10% AND
- Other symptoms improved AND
- Moderate engagement

BARRIER:
- All others

4. 경로별 처리 로직

4.1 SUCCESS 경로 처리

async function handleSuccessPath(evaluation) {
const actions = {
// 현재 전략 유지
maintainStrategy: {
message: "훌륭해요! 현재 방법이 잘 맞고 있어요.",
modules: evaluation.currentModules,
intensity: evaluation.currentIntensity
},

// 성과 축하
celebration: {
achievements: identifyAchievements(evaluation),
milestones: checkMilestones(evaluation.progress),
rewards: generateRewards(evaluation.userId)
},

// 다음 단계 준비
nextPhase: {
graduationCheck: evaluation.weekNumber >= 10,
maintenancePrep: evaluation.improvementRate > 0.5,
advancedModules: suggestAdvancedContent(evaluation)
}
};

return {
path: "SUCCESS",
actions,
weeklyMessage: generateSuccessMessage(evaluation, actions)
};
}

4.2 MISMATCH 경로 처리

async function handleMismatchPath(evaluation) {
// 왜 불면증은 개선되지 않는지 분석
const analysis = {
possibleReasons: [
checkIfWrongHypothesis(evaluation),
checkIfMissingFactors(evaluation),
checkIfNeedsDifferentApproach(evaluation)
],

// 새로운 접근 제안
alternatives: {
switchPrimaryModule: suggestAlternativeModule(evaluation),
adjustTiming: recommendScheduleChange(evaluation),
addressBarriers: identifyHiddenBarriers(evaluation)
}
};

return {
path: "MISMATCH",
analysis,
adjustments: generateMismatchAdjustments(analysis),
exploratoryQuestions: generateProbeQuestions(evaluation)
};
}

4.3 BARRIER 경로 처리

async function handleBarrierPath(evaluation) {
// 장애물 심층 분석
const barriers = {
motivational: assessMotivationBarriers(evaluation),
practical: identifyPracticalObstacles(evaluation),
psychological: detectPsychologicalBlocks(evaluation),
environmental: checkEnvironmentalFactors(evaluation)
};

// 단순화 전략
const simplification = {
reduceTaskComplexity: true,
focusOnOneModule: selectCoreModule(evaluation),
shortenDailyCommitment: "5-10분으로 축소",
increaseSupport: "일일 체크인 추가"
};

return {
path: "BARRIER",
barriers,
interventions: generateBarrierInterventions(barriers),
simplifiedPlan: createSimplifiedPlan(simplification)
};
}

4.4 CRITICAL 경로 처리

async function handleCriticalPath(evaluation) {
const urgency = calculateUrgencyLevel(evaluation);

const immediateActions = {
// 즉시 실행
notification: {
alertClinician: urgency === "HIGHEST",
sendSupportResources: true,
scheduleCheckIn: "within 24 hours"
},

// 안전 계획
safetyPlan: {
crisisContacts: getCrisisResources(evaluation.location),
copingStrategies: getSafetyStrategies(),
warningSignsEducation: true
},

// 치료 수정
treatmentModification: {
pauseChallengingModules: true,
focusOnStabilization: true,
increaseMonitoring: "daily"
}
};

// 로깅 및 추적
await logCriticalEvent(evaluation, immediateActions);

return {
path: "CRITICAL_ISSUE",
urgency,
immediateActions,
followUpPlan: generateCriticalFollowUp(evaluation)
};
}

5. 평가 보고서 생성

5.1 보고서 구조

const weeklyReport = {
summary: {
week: 5,
path: "SUCCESS",
overallProgress: "긍정적",
keyMetrics: {
sleepEfficiency: "75% → 82% (+7%)",
isiScore: "18 → 14 (-22%)",
taskCompletion: "85%",
moodTrend: "상승"
}
},

detailed: {
sleepAnalysis: {
improvements: ["입면 시간 단축", "수면 효율 증가"],
challenges: ["주말 패턴 불규칙"],
patterns: ["평일 안정화 확인"]
},

psychologicalProgress: {
mood: "전반적 개선",
anxiety: "경미한 수준 유지",
stress: "관리 가능 수준"
},

engagementMetrics: {
taskTypes: {
cognitive: "90% 완료",
behavioral: "80% 완료",
emotional: "85% 완료"
},
preferredTimes: "저녁 8-9시",
consistency: "매우 일관됨"
}
},

recommendations: {
nextWeek: [
"현재 수면 제한 유지",
"인지 재구성 심화",
"주말 루틴 강화"
],
adjustments: "없음 (SUCCESS 경로)",
specialNotes: "5주차 설문 예정"
}
};

6. 구현 체크리스트

6.1 데이터 수집 및 분석

  • 주간 수면 데이터 집계
  • Task 완료율 계산
  • 기분/심리 지표 추이
  • 학습 참여도 분석

6.2 경로 결정

  • CRITICAL 기준 우선 체크
  • 개선도 계산 알고리즘
  • 경로 결정 규칙 적용
  • 경계 케이스 처리

6.3 조정안 생성

  • 경로별 액션 플랜
  • 모듈/강도 조정
  • 메시지 톤 변경
  • 다음 주 목표 설정

7. 테스트 시나리오

시나리오 1: 순조로운 개선 (SUCCESS)

Given:
- Week 5
- ISI: 18 → 14 (22% 개선)
- PHQ-9: 10 → 8
- Task 완료율: 85%
Expected:
- Path: SUCCESS
- Action: 현재 유지
- Message: 축하 및 격려
- Next: 심화 단계 준비

시나리오 2: 불일치 패턴 (MISMATCH)

Given:
- Week 7
- ISI: 16 → 15 (6% 개선)
- PHQ-9: 12 → 8 (33% 개선)
- 수면은 안 좋아지는데 기분은 좋아짐
Expected:
- Path: MISMATCH
- Analysis: 우울 개선이 수면에 아직 반영 안됨
- Action: 수면 특화 모듈 강화

시나리오 3: 정체 상태 (BARRIER)

Given:
- Week 4
- 모든 지표 변화 없음
- Task 완료율: 30%
Expected:
- Path: BARRIER
- Analysis: 참여도 부족이 주요 문제
- Action: 과제 단순화, 동기 강화

시나리오 4: 위급 상황 (CRITICAL)

Given:
- Any week
- PHQ-9: 22 (item 9 = 2)
- 급속 악화 패턴
Expected:
- Path: CRITICAL_ISSUE
- Immediate: 24시간 내 연락
- Resources: 위기 지원 제공
- Modification: 안정화 중심

8. 성능 고려사항

// 주간 평가는 계산량이 많으므로 최적화 필요
const performanceOptimizations = {
// 1. 데이터 프리패칭
prefetchData: async (userIds) => {
const promises = userIds.map(id => ({
sleep: getSleepData(id),
tasks: getTaskData(id),
mood: getMoodData(id)
}));
return Promise.all(promises);
},

// 2. 배치 처리
batchEvaluation: async (users) => {
const batches = chunk(users, 50);
for (const batch of batches) {
await processEvaluationBatch(batch);
await delay(500); // Rate limiting
}
},

// 3. 캐싱 전략
caching: {
evaluationResults: 7 * 24 * 60 * 60 * 1000, // 7일
pathDecisions: 24 * 60 * 60 * 1000, // 24시간
reportTemplates: 30 * 24 * 60 * 60 * 1000 // 30일
}
};

9. 모니터링 및 품질 지표

const p5QualityMetrics = {
// 정확도 지표
accuracy: {
pathDecisionAccuracy: "전문가 검토 대비 일치율",
falsePositiveCritical: "불필요한 위급 판정",
missedCritical: "놓친 위급 상황"
},

// 효과성 지표
effectiveness: {
pathChangeFrequency: "경로 변경 빈도",
improvementAfterAdjustment: "조정 후 개선율",
userSatisfaction: "경로 결정 만족도"
},

// 운영 지표
operational: {
evaluationCompletionRate: "> 99.9%",
averageProcessingTime: "< 5s",
reportGenerationSuccess: "> 99%"
}
};

10. 참고 자료

3. 경로별 액션

// IMPROVEMENT 경로 액션
const improvementActions = {
validation: {
action: "sendProgressMessage",
content: {
type: "TREATMENT_PROGRESS",
priority: MessagePriority.HIGH,
message: "훌륭해요! 지속적인 개선을 보이고 있습니다.",
data: {
improvementRate: "25%",
achievements: ["규칙적 수면", "수면 효율 향상"],
nextGoals: ["수면 질 개선", "주간 피로도 감소"]
}
}
},

nextPhase: {
condition: "week >= 5",
action: "considerPhaseTransition",
options: ["continue_current", "advance_modules", "reduce_intensity"]
}
};

// ADJUSTMENT 경로 액션
const adjustmentActions = {
moduleAdjustment: {
analyze: ["ineffective_modules", "user_feedback", "completion_rates"],
actions: [
"replaceIneffectiveModule",
"adjustDifficulty",
"changeDeliveryTime"
]
},

supportMessage: {
type: "ENCOURAGEMENT",
priority: MessagePriority.MEDIUM,
personalized: true
}
};

// CRITICAL_ISSUE 경로 액션
const criticalActions = {
immediate: {
alert: {
type: "CRISIS_INTERVENTION",
priority: MessagePriority.CRITICAL,
channel: "push_notification"
},

content: {
supportResources: true,
emergencyContacts: true,
immediateStrategies: ["breathing", "grounding", "support"]
}
},

followUp: {
frequency: "daily",
duration: "until_stable",
escalation: "clinical_team_if_needed"
}
};