Now, for the existing 10 responses that are already saved without the `deep_analysis_pass` field, I can detect them by matching the question text to the known pass prompts. Let me update the `load_deep_analysis` API to also match by question text as a fallback:


Edit

        case 'load_deep_analysis':
            $threadId = $_GET['thread_id'] ?? '';
            if (!$threadId) jsonError('thread_id required');
            $threadId = resolveThreadId($threadId);

            $mongo = \EmailIntelligence\MongoDatabase::getInstance();

            // Find all responses with deep_analysis_pass field for this thread
            $responses = $mongo->findAll('ai_query_responses', [
                'thread_ids' => $threadId,
                'deep_analysis_pass' => ['$exists' => true]
            ], [
                'sort' => ['deep_analysis_pass' => 1, 'created_at' => -1]
            ]);

            // Group by pass
            $passes = [];
            foreach ($responses as $r) {
                $passNum = $r['deep_analysis_pass'] ?? 0;
                if (!isset($passes[$passNum])) {
                    $passes[$passNum] = [
                        'pass' => $passNum,
                        'name' => $r['deep_analysis_name'] ?? 'Pass ' . $passNum,
                        'agent' => $r['agent'] ?? 'general',
                        'responses' => []
                    ];
                }
                $passes[$passNum]['responses'][] = [
                    '_id' => (string)$r['_id'],
                    'provider' => $r['provider'] ?? '',
                    'model' => $r['model'] ?? '',
                    'response' => $r['response']['response'] ?? '',
                    'cost' => $r['response']['cost'] ?? 0,
                    'request_time' => $r['response']['request_time'] ?? 0,
                    'created_at' => $r['created_at'] ?? ''
                ];
            }

            // Re-index to sequential array
            ksort($passes);
            $passes = array_values($passes);

            jsonResponse([
                'success' => true,
                'passes' => $passes,
                'total_responses' => count($responses)
            ]);
            break;

        case 'load_deep_analysis':
            $threadId = $_GET['thread_id'] ?? '';
            if (!$threadId) jsonError('thread_id required');
            $threadId = resolveThreadId($threadId);

            $mongo = \EmailIntelligence\MongoDatabase::getInstance();

            // Find all responses with deep_analysis_pass field for this thread
            $responses = $mongo->findAll('ai_query_responses', [
                'thread_ids' => $threadId,
                'deep_analysis_pass' => ['$exists' => true]
            ], [
                'sort' => ['deep_analysis_pass' => 1, 'created_at' => -1]
            ]);

            // Fallback: if no tagged responses, detect by matching question text patterns
            if (empty($responses)) {
                $passSignatures = [
                    1 => ['match' => 'Analyze the COMPLETE email history chronologically', 'name' => 'Business Relationship Timeline', 'agent' => 'general'],
                    2 => ['match' => 'PRESSURE TACTICS', 'name' => 'Pressure & Manipulation Detection', 'agent' => 'deception_detector'],
                    3 => ['match' => 'psychological and business profiles for EACH', 'name' => 'Psychological Profiles', 'agent' => 'contact_profiler'],
                    4 => ['match' => 'ALL PRICES QUOTED', 'name' => 'Financial & Business Patterns', 'agent' => 'quote_analyst'],
                    5 => ['match' => 'CONCRETE win-back strategy', 'name' => 'Win-Back Strategy', 'agent' => 'general']
                ];

                $allResponses = $mongo->findAll('ai_query_responses', [
                    'thread_ids' => $threadId
                ], [
                    'sort' => ['created_at' => 1]
                ]);

                foreach ($allResponses as $r) {
                    $q = $r['question'] ?? '';
                    foreach ($passSignatures as $passNum => $sig) {
                        if (stripos($q, $sig['match']) !== false) {
                            $r['deep_analysis_pass'] = $passNum;
                            $r['deep_analysis_name'] = $sig['name'];
                            $r['agent'] = $r['agent'] ?? $sig['agent'];
                            $responses[] = $r;
                            break;
                        }
                    }
                }
            }

            // Group by pass
            $passes = [];
            foreach ($responses as $r) {
                $passNum = $r['deep_analysis_pass'] ?? 0;
                if (!isset($passes[$passNum])) {
                    $passes[$passNum] = [
                        'pass' => $passNum,
                        'name' => $r['deep_analysis_name'] ?? 'Pass ' . $passNum,
                        'agent' => $r['agent'] ?? 'general',
                        'responses' => []
                    ];
                }
                $passes[$passNum]['responses'][] = [
                    '_id' => (string)$r['_id'],
                    'provider' => $r['provider'] ?? '',
                    'model' => $r['model'] ?? '',
                    'response' => $r['response']['response'] ?? '',
                    'cost' => $r['response']['cost'] ?? 0,
                    'request_time' => $r['response']['request_time'] ?? 0,
                    'created_at' => $r['created_at'] ?? ''
                ];
            }

            // Re-index to sequential array
            ksort($passes);
            $passes = array_values($passes);

            jsonResponse([
                'success' => true,
                'passes' => $passes,
                'total_responses' => count($responses)
            ]);
            break;