This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.

Analysis:
Let me chronologically analyze the entire conversation:

1. **Session Start**: This is a continuation from a previous conversation. The summary describes extensive prior work on an Email Intelligence System. Key prior work included: Two-Round AI feature, Thread view enhancements, Dashboard fixes, Delete functionality, Sorting & Filters, Contact name fix, Sync by domain, D3.js charts, Products tab hiding, AI model updates.

2. **First task - Thread pagination fix**: User reported "contacts tab not showing any contact" which was fixed in the prior session. The current session started with verifying that fix was solid.

3. **Thread pagination bug**: The `renderPagination` function uses `loadFunction.name` to build onclick handlers. The anonymous arrow function `(p) => loadEmails(p)` has empty `.name`, making pagination buttons non-functional. Fixed by passing `loadEmails` directly.

4. **Thread search by domain**: User reported searching "delta-engineering.be" only returned 1 result. The search only checked `subject` field. Fixed by adding `$or` on `subject`, `from_email`, `to_email`.

5. **Context builder improvements**: User reported not all threads showing in context builder when searching by domain. Fixed by increasing limits (5→100 threads, 5→10 contacts), adding "Add All" buttons, "Load More", and "Add All Full" that fetches all pages.

6. **Bulk delete found threads**: User needed to delete "Address not matched by Google GeoCoding" threads. Added `delete_threads_bulk` API endpoint, "Delete All Found" button in dashboard threads tab that appears when search/filter is active.

7. **Deep Analysis feature**: User asked for automated 5-pass analysis. Built `DEEP_ANALYSIS_PASSES` constant and `runDeepAnalysis()` function with 5 sequential passes (Timeline, Pressure, Profiles, Financial, Win-Back).

8. **Deep Analysis persistence**: User asked how to load results after leaving page. Added `load_deep_analysis` API endpoint, `loadDeepAnalysis()` JS function, "Load Deep Analysis" button, pass badges on saved responses, and fallback detection for responses saved without `deep_analysis_pass` field.

9. **Fixed save_ai_response**: The API endpoint wasn't persisting `agent`, `deep_analysis_pass`, or `deep_analysis_name` fields. Added them.

10. **Current task - Playbook system**: User wants configurable playbooks with dropdown selection, new playbooks for different scenarios (win-back, re-engagement emails, quote optimization). Plan was written and approved but implementation hasn't started yet.

Let me trace through all the specific code changes and files modified:

**Files Modified:**

1. `public/assets/app.js`:
   - Fixed pagination: `(p) => loadEmails(p)` → `loadEmails`
   - Added "Delete All Found" button visibility logic in `loadEmails()`
   - Added `deleteFoundThreads()` function
   - Hid delete button when no results

2. `src/QueryAdapter.php`:
   - Thread search: `$matchFilter['subject']` → `$matchFilter['$or']` on subject/from_email/to_email

3. `public/thread_view.php`:
   - Context builder: increased limits, added addAllSearchThreads(), addAllSearchThreadsFull(), loadMoreSearchThreads()
   - CSS: context-search-results max-height 250px → 400px
   - Contact thread limit: 20 → 100
   - Deep Analysis button UI next to "Send to AI"
   - Deep Analysis results container
   - DEEP_ANALYSIS_PASSES constant (5 passes)
   - runDeepAnalysis() function
   - loadDeepAnalysis() function
   - $hasDeepAnalysis PHP variable with fallback detection
   - "Load Deep Analysis" button in saved responses header
   - Deep analysis pass badges on saved responses (PHP + JS)

4. `public/api.php`:
   - `delete_threads_bulk` endpoint
   - `load_deep_analysis` endpoint with fallback detection
   - `save_ai_response`: added agent, deep_analysis_pass, deep_analysis_name fields

5. `public/index.php`:
   - "Delete All Found" button in thread filter bar

**Current state**: Plan mode was active with an approved plan for converting hardcoded DEEP_ANALYSIS_PASSES into a configurable DEEP_ANALYSIS_PLAYBOOKS system with 4 playbooks (Win Back, Re-Engagement Emails, Quote Optimization, Full Relationship Analysis) and dropdown selection UI.

Summary:
1. Primary Request and Intent:
   This session is a continuation of building an Email Intelligence System. The user's requests in this session were:

   - **Fix thread pagination**: Page 2/3 buttons in threads tab weren't working
   - **Fix thread search by domain**: Searching "delta-engineering.be" only returned 1 result instead of all matching threads
   - **Enhance context builder**: Show all matching threads when searching by domain, add "Add All" button for easy bulk addition
   - **Add bulk delete for found threads**: Need to delete junk threads like "Address not matched by Google GeoCoding" in bulk, safely by exact thread_id matching
   - **Create automated Deep Analysis**: 5-pass automated analysis with preset prompts (Timeline, Pressure Detection, Psychological Profiles, Financial Patterns, Win-Back Strategy)
   - **Persist Deep Analysis results**: Allow loading saved deep analysis results when returning to a thread page
   - **Convert to configurable playbooks**: Replace hardcoded 5-pass analysis with selectable playbooks via dropdown, add new playbooks:
     - "Win Back Lost Client" (existing 5 passes)
     - "Re-Engagement Emails" (5 passes with persuasion techniques, AI value proposition, indirect re-engagement)
     - "Quote Optimization" (5 passes for maximizing quote value with anchoring, negotiation tactics)
     - "Full Relationship Analysis" (4 passes)

2. Key Technical Concepts:
   - MongoDB aggregation pipelines with `$or`, `$match`, `$group`, `$lookup`
   - `renderPagination()` uses `loadFunction.name` for inline onclick — anonymous functions break this
   - `thread_for_ai` API endpoint strips quoted content via `ThreadAnalyzer::stripQuotedContent()` server-side
   - `MongoDatabase::insertOrUpdate()` for upserts, `MongoDatabase::delete()` uses deleteMany
   - AI proxy multi-provider simultaneous requests via `api_opus/api/query.php`
   - Conversation history builds across sequential passes via `addToConversation()` / `buildConversationContext()`
   - `saveAIResponse()` persists to MongoDB `ai_query_responses` collection
   - Token budget management: 85% of smallest model limit, truncation with `maxChars = Math.floor(modelLimit * 3.5 * 0.85)`
   - Fallback detection of deep analysis passes by matching question text patterns when `deep_analysis_pass` field doesn't exist
   - Cialdini persuasion principles (reciprocity, social proof, scarcity, authority, liking, commitment)
   - Negotiation techniques (anchoring, BATNA, concession strategy, value framing)

3. Files and Code Sections:

   - **`/var/www/mssql.danmarcrm.com/dev1/extension2v1/public/assets/app.js`**
     - Critical for dashboard functionality (contacts, threads, filters, delete, pagination)
     - **Pagination fix** (line 732): Changed `(p) => loadEmails(p)` to `loadEmails` because `renderPagination` uses `loadFunction.name` which is empty for anonymous arrows
     - **Delete button visibility** added after renderPagination in loadEmails():
       ```javascript
       var deleteBtn = document.getElementById('delete-found-threads-btn');
       if (deleteBtn) {
           var hasFilter = !!(tSearch || tContactFilter || tDateFrom || tDateTo || tStatus);
           if (hasFilter && data.pagination.total > 0) {
               deleteBtn.style.display = '';
               deleteBtn.textContent = 'Delete All ' + data.pagination.total + ' Found';
           } else {
               deleteBtn.style.display = 'none';
           }
       }
       ```
     - **Hide delete button when no results**:
       ```javascript
       if (data.threads.length === 0) {
           container.innerHTML = '<p class="loading">No threads found</p>';
           var deleteBtnEmpty = document.getElementById('delete-found-threads-btn');
           if (deleteBtnEmpty) deleteBtnEmpty.style.display = 'none';
           return;
       }
       ```
     - **`deleteFoundThreads()` function** (~80 lines): Reads filter params from DOM, fetches count for confirmation, double-confirms for >50 threads, fetches all matching thread_ids page by page, sends to `delete_threads_bulk` in batches of 100

   - **`/var/www/mssql.danmarcrm.com/dev1/extension2v1/src/QueryAdapter.php`**
     - Core data access layer for MongoDB
     - **Thread search fix** in `getThreadsMongo()` — changed from subject-only to `$or`:
       ```php
       if ($search) {
           $matchFilter['$or'] = [
               ['subject' => ['$regex' => $search, '$options' => 'i']],
               ['from_email' => ['$regex' => $search, '$options' => 'i']],
               ['to_email' => ['$regex' => $search, '$options' => 'i']]
           ];
       }
       ```

   - **`/var/www/mssql.danmarcrm.com/dev1/extension2v1/public/thread_view.php`**
     - Main thread view with inline CSS, HTML, and JS (~4000+ lines)
     - **Context builder CSS**: `.context-search-results` max-height changed from 250px to 400px
     - **searchContext() function rewritten**: Increased thread limit to 100, contacts to 10, added total count display, "Add All" buttons, "Load More" button
     - **addAllSearchThreads()**: Adds currently loaded threads to context
     - **addAllSearchThreadsFull()**: Fetches ALL pages then adds every thread (async with progress)
     - **loadContactThreads() limit**: Changed from 20 to 100
     - **DEEP_ANALYSIS_PASSES constant** (lines ~1567-1598): 5 passes with id, name, agent, prompt
     - **Deep Analysis button HTML**:
       ```html
       <div style="display:flex;gap:8px;">
           <button class="btn btn-primary" id="submit-ai-btn" onclick="submitToAI()" style="flex:1;">Send to AI</button>
           <button class="btn" id="deep-analysis-btn" onclick="runDeepAnalysis()" style="flex:1;background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;font-weight:600;">Deep Analysis (5-Pass)</button>
       </div>
       ```
     - **Deep Analysis results container HTML**: Card with gradient header, progress span, results div
     - **runDeepAnalysis() function** (~270 lines): Validates providers, builds base email content once (including context threads), loops through all passes sequentially: injects agent prompt, adds conversation history, sends to AI, displays results, saves to MongoDB, adds to conversation history, 2-second pause between passes
     - **loadDeepAnalysis() function** (~60 lines): Fetches saved results via `load_deep_analysis` API, renders same panel layout with per-pass sections
     - **$hasDeepAnalysis PHP variable**: Checks `deep_analysis_pass` exists, fallback checks question text pattern
     - **"Load Deep Analysis" button**: Shown in saved responses card header when $hasDeepAnalysis is true
     - **Deep analysis pass badges** on saved responses (PHP-rendered):
       ```php
       <?php if (!empty($saved['deep_analysis_pass'])): ?>
       <span style="margin-left:8px;background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;padding:2px 8px;border-radius:10px;font-size:0.75em;">Pass <?= (int)$saved['deep_analysis_pass'] ?>: <?= htmlspecialchars($saved['deep_analysis_name'] ?? '') ?></span>
       <?php endif; ?>
       ```
     - **Deep analysis badges in JS loadMoreResponses()**: Same badge via template literal

   - **`/var/www/mssql.danmarcrm.com/dev1/extension2v1/public/api.php`**
     - Central API router
     - **`delete_threads_bulk` endpoint**: Accepts `{thread_ids: [...]}`, max 500, loops calling `deleteThread()` for each
     - **`load_deep_analysis` endpoint**: Finds responses with `deep_analysis_pass` field, fallback detects by matching question text patterns, groups by pass number, returns sorted passes array
     - **Fallback signature matching** (order matters — win-back checked before pressure):
       ```php
       $passSignatures = [
           5 => ['match' => 'CONCRETE win-back strategy', ...],
           1 => ['match' => 'Analyze the COMPLETE email history chronologically', ...],
           3 => ['match' => 'psychological and business profiles for EACH', ...],
           4 => ['match' => 'ALL PRICES QUOTED', ...],
           2 => ['match' => 'PRESSURE TACTICS: Where did they push unreasonable', ...],
       ];
       ```
     - **`save_ai_response` endpoint updated**: Added `agent`, `deep_analysis_pass`, `deep_analysis_name` fields with null cleanup

   - **`/var/www/mssql.danmarcrm.com/dev1/extension2v1/public/index.php`**
     - Dashboard HTML
     - Added "Delete All Found" button in thread filter bar:
       ```html
       <button class="btn btn-sm" id="delete-found-threads-btn" style="background:#ef4444;color:white;display:none;" onclick="deleteFoundThreads()">Delete All Found</button>
       ```

4. Errors and Fixes:
   - **Thread pagination broken**: `renderPagination` uses `loadFunction.name` for onclick handlers. Anonymous arrow `(p) => loadEmails(p)` has empty `.name`, generating `onclick="(2)"` which does nothing. Fixed by passing `loadEmails` directly (named function).
   - **Thread search only searched subject**: `$matchFilter['subject']` only matched subject field. Fixed by using `$or` on subject, from_email, to_email.
   - **Context builder only showed 5 threads**: Hardcoded `limit=5` in fetch URL. Fixed by increasing to 100 and adding "Add All" / "Load More" UI.
   - **Deep analysis responses not persisting metadata**: `save_ai_response` API endpoint had fixed field list that didn't include `agent`, `deep_analysis_pass`, `deep_analysis_name`. Fixed by adding these fields.
   - **Fallback detection grouping error**: Win-back pass question text contained "PRESSURE TACTICS" substring, causing it to be grouped into Pass 2 instead of Pass 5. Fixed by checking Win-back signature first (order matters) and making Pass 2 match more specific: `'PRESSURE TACTICS: Where did they push unreasonable'`.
   - **$hasDeepAnalysis PHP check**: Only checked `deep_analysis_pass` field which didn't exist on old records. Added fallback regex check on question text.

5. Problem Solving:
   - Pagination fix: Traced from user report → `renderPagination` using `.name` → anonymous function issue → simple fix passing named function
   - Thread search: Tested API directly to confirm only 1 result with domain search → found subject-only filter → added `$or`
   - Context builder "Add All 296": Two-tier approach — "Add Shown" for quick action on loaded results, "Add All" (blue button) fetches all pages asynchronously with progress
   - Bulk delete safety: Multiple safety layers — exact same filters from DOM, count confirmation, double-confirm for >50, fetches exact thread_ids, deletes by exact ID only, max 500 cap
   - Deep analysis persistence: Discovered saved responses lacked `deep_analysis_pass` field because `save_ai_response` API had fixed field list. Added fields AND built fallback detection matching question text patterns for existing records.

6. All User Messages:
   - "what about searching by domain name?" — Reported that searching delta-engineering.be in threads only returned 1 result
   - "If I try in thread_view.php?thread_id=17f1bcc6d4d2e6ac to add all threads and emails from delta-engineering.be domain, there are some shown but not all for sure. In threads seems returns many more when searching for delta-engineering.be. Should return all of them and have a easy method to add all for context"
   - "Threads 296 found Add All 99 .. Should have a Add all 296 as well. Are we sure we add only the emails and not include all quoted emails? It is important as for example this emails are a lot to be analyzed"
   - "we don't have an option in threads search do delete all found records. pls make sure works flawlessly and we don't delete other records. For ex we have a lot of 'Address not matched by Google GeoCoding' matching delta emails, I need to delete them all before analyzing the delta emails"
   - "we have this email chain with all team and CEO from delta engineering. I need to get the most in deep sentiment analysis, business fails I had, pushes from delta guys, physical analysis, everything that can help us doing better business with them and re-gain them as clients. What prompt or how/what questions to ask?" — Asked for prompt strategy advice (not code changes)
   - "pls create the flow to be automated" — Asked to build the automated Deep Analysis feature
   - "I've run it one time, worked, displayed content, but after leaving that page how can I load it again?" — Asked for persistence/reload of deep analysis results
   - "I found it thank you, a new tab with all these results would be great pls create it. Additionally, how do we obtain these 5 steps? I guess we have some hardcoded instructions to be sent to AI models? If so, we need a config section to customize them and add new requests. In user interfaces I think the easiest way would be a dropdown to select what to be extracted/generated and hit the Deep Analyze button. Pls add sections as: How to regain client. Formulate an email to gain his interest back. Formulate an email to gain his interest back but must have AI content for his company... Consider 2-3 steps indirect interactions... Use any persuasive techniques as possible. For existing clients pls create a Quote Analysis value so we can use it to get the most amount of money for the task/project being discussed. Again pls add a few methods including the deep persuasion ones..." — The most recent and most complex request

7. Pending Tasks:
   - **Implement the Playbook System** (plan approved, not yet implemented):
     - Replace `DEEP_ANALYSIS_PASSES` with `DEEP_ANALYSIS_PLAYBOOKS` object containing 4 playbooks
     - Add dropdown UI to select playbook before running Deep Analysis
     - Update `runDeepAnalysis()` to read selected playbook from dropdown
     - Add all prompts for 4 playbooks (Win Back, Re-Engagement Emails, Quote Optimization, Full Relationship Analysis)
     - Populate dropdown on page load via `initPlaybookDropdown()`
     - Save `deep_analysis_playbook` field to MongoDB
     - Update `load_deep_analysis` API to also return playbook key

8. Current Work:
   The plan for the Playbook System was written to `/root/.claude/plans/scalable-doodling-peach.md` and **approved by the user**. The plan details converting the hardcoded `DEEP_ANALYSIS_PASSES` into a `DEEP_ANALYSIS_PLAYBOOKS` object with 4 playbooks, each containing 4-5 passes with detailed prompts. The plan includes dropdown UI, updated `runDeepAnalysis()`, and MongoDB persistence updates. Implementation has NOT started yet — the plan was just approved.

   The plan file contains full prompt text for all passes in all 4 playbooks:
   - **Win Back Lost Client** (5 passes): Timeline, Pressure, Profiles, Financial, Win-Back (existing prompts)
   - **Re-Engagement Emails** (5 passes): How to Regain, Direct Email, AI Value Email, Indirect Plan, Persuasion Toolkit
   - **Quote Optimization** (5 passes): History, Budget/Willingness, Value Framing, Anchoring/Negotiation, Optimal Quote
   - **Full Relationship Analysis** (4 passes): Timeline, Profiles, Financial, Pressure

9. Optional Next Step:
   Implement the approved playbook system plan. The user's last message was: "I found it thank you, a new tab with all these results would be great pls create it. Additionally, how do we obtain these 5 steps? I guess we have some hardcoded instructions to be sent to AI models? If so, we need a config section to customize them and add new requests. In user interfaces I think the easiest way would be a dropdown to select what to be extracted/generated and hit the Deep Analyze button."

   The plan was approved — next step is to implement it by:
   1. Replace `DEEP_ANALYSIS_PASSES` constant with `DEEP_ANALYSIS_PLAYBOOKS` in thread_view.php
   2. Add playbook dropdown UI
   3. Update `runDeepAnalysis()` to use selected playbook
   4. Add `initPlaybookDropdown()` and call it on page load
   5. Update `save_ai_response` API to persist `deep_analysis_playbook`
   6. Update `load_deep_analysis` API to return playbook info

If you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /root/.claude/projects/-var-www-mssql-danmarcrm-com-dev1-extension2/75ef92ac-556a-4223-9d55-17c4e535294d.jsonl
Please continue the conversation from where we left off without asking the user any further questions. Continue with the last task that you were asked to work on.


The user wants me to continue implementing the approved playbook system plan. I'm in plan mode, so I need to review the current plan and exit plan mode so I can start implementing.

Let me read the plan file to confirm it's complete and ready for implementation.


I have the approved plan for the Deep Analysis Playbook system. Let me review the current state of the plan file and the key files that need to be modified, then exit plan mode to begin implementation.


     1→# Deep Analysis Enhancement — Configurable Playbooks with Dropdown Selection
     2→
     3→## Context
     4→
     5→The current Deep Analysis feature has 5 hardcoded passes focused on one use case (lost client win-back). The user wants:
     6→1. **Configurable analysis playbooks** — not hardcoded, ability to add/edit/manage passes
     7→2. **Dropdown selection** — pick which playbook to run, then hit Deep Analysis
     8→3. **New playbooks** for different business scenarios (win-back, quote optimization, persuasion)
     9→4. **Results in a dedicated tab** — not just inline, a proper tabbed view for deep analysis results
    10→
    11→## Architecture
    12→
    13→### Replace hardcoded `DEEP_ANALYSIS_PASSES` with `DEEP_ANALYSIS_PLAYBOOKS`
    14→
    15→A **playbook** is a named collection of passes. The dropdown selects a playbook, and the Deep Analysis button runs all passes in that playbook sequentially.
    16→
    17→### File: `public/thread_view.php` (all changes in one file)
    18→
    19→---
    20→
    21→## Step 1: Define Playbooks Constant
    22→
    23→**Replace** the current `DEEP_ANALYSIS_PASSES` array (lines 1567-1598) with `DEEP_ANALYSIS_PLAYBOOKS` object:
    24→
    25→```javascript
    26→const DEEP_ANALYSIS_PLAYBOOKS = {
    27→    // ---- LOST CLIENT WIN-BACK ----
    28→    'win_back': {
    29→        name: 'Win Back Lost Client',
    30→        description: 'Full relationship analysis + win-back strategy',
    31→        passes: [
    32→            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
    33→            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' },
    34→            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
    35→            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
    36→            { id: 'winback', name: 'Win-Back Strategy', agent: 'general', prompt: '...' }
    37→        ]
    38→    },
    39→
    40→    // ---- RE-ENGAGEMENT EMAIL DRAFTS ----
    41→    'regain_email': {
    42→        name: 'Re-Engagement Emails',
    43→        description: 'Draft re-engagement emails with persuasion techniques',
    44→        passes: [
    45→            { id: 'regain_analysis', name: 'How to Regain Client', agent: 'general', prompt: '...' },
    46→            { id: 'regain_email_direct', name: 'Direct Re-engagement Email', agent: 'email_composer', prompt: '...' },
    47→            { id: 'regain_email_ai', name: 'AI Value Proposition Email', agent: 'email_composer', prompt: '...' },
    48→            { id: 'indirect_steps', name: 'Indirect Re-engagement Plan', agent: 'general', prompt: '...' },
    49→            { id: 'persuasion_toolkit', name: 'Persuasion Techniques', agent: 'general', prompt: '...' }
    50→        ]
    51→    },
    52→
    53→    // ---- QUOTE OPTIMIZATION ----
    54→    'quote_optimize': {
    55→        name: 'Quote Optimization',
    56→        description: 'Maximize quote value for current client discussions',
    57→        passes: [
    58→            { id: 'quote_history', name: 'Quote & Pricing History', agent: 'quote_analyst', prompt: '...' },
    59→            { id: 'client_budget', name: 'Client Budget & Willingness', agent: 'contact_profiler', prompt: '...' },
    60→            { id: 'value_framing', name: 'Value Framing Strategy', agent: 'general', prompt: '...' },
    61→            { id: 'anchoring', name: 'Anchoring & Negotiation Tactics', agent: 'general', prompt: '...' },
    62→            { id: 'quote_draft', name: 'Optimal Quote Recommendation', agent: 'quote_analyst', prompt: '...' }
    63→        ]
    64→    },
    65→
    66→    // ---- FULL RELATIONSHIP ANALYSIS ----
    67→    'relationship': {
    68→        name: 'Full Relationship Analysis',
    69→        description: 'Comprehensive relationship health check',
    70→        passes: [
    71→            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
    72→            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
    73→            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
    74→            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' }
    75→        ]
    76→    }
    77→};
    78→```
    79→
    80→---
    81→
    82→## Step 2: Playbook Dropdown + Deep Analysis Button UI
    83→
    84→**Replace** the current button area (lines 1437-1445) with dropdown + button:
    85→
    86→```html
    87→<div style="display:flex;gap:8px;">
    88→    <button class="btn btn-primary" id="submit-ai-btn" onclick="submitToAI()" style="flex:1;">
    89→        Send to AI
    90→    </button>
    91→</div>
    92→<div style="display:flex;gap:8px;margin-top:8px;">
    93→    <select id="deep-analysis-playbook" style="flex:2;padding:8px;border-radius:6px;border:1px solid #ccc;font-size:0.9em;">
    94→        <!-- Populated from DEEP_ANALYSIS_PLAYBOOKS by JS -->
    95→    </select>
    96→    <button class="btn" id="deep-analysis-btn" onclick="runDeepAnalysis()" style="flex:1;background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;font-weight:600;">
    97→        Deep Analysis
    98→    </button>
    99→</div>
   100→```
   101→
   102→Add JS to populate dropdown on page load:
   103→```javascript
   104→function initPlaybookDropdown() {
   105→    var sel = document.getElementById('deep-analysis-playbook');
   106→    for (var key in DEEP_ANALYSIS_PLAYBOOKS) {
   107→        var pb = DEEP_ANALYSIS_PLAYBOOKS[key];
   108→        var opt = document.createElement('option');
   109→        opt.value = key;
   110→        opt.textContent = pb.name + ' (' + pb.passes.length + ' passes)';
   111→        opt.title = pb.description;
   112→        sel.appendChild(opt);
   113→    }
   114→}
   115→```
   116→
   117→---
   118→
   119→## Step 3: Update `runDeepAnalysis()` to Use Selected Playbook
   120→
   121→Change the function to read the selected playbook from the dropdown instead of using the hardcoded `DEEP_ANALYSIS_PASSES`:
   122→
   123→```javascript
   124→async function runDeepAnalysis() {
   125→    var playbookKey = document.getElementById('deep-analysis-playbook').value;
   126→    var playbook = DEEP_ANALYSIS_PLAYBOOKS[playbookKey];
   127→    if (!playbook) { alert('Select a playbook'); return; }
   128→    var passes = playbook.passes;
   129→    // ... rest of function uses `passes` instead of `DEEP_ANALYSIS_PASSES`
   130→    // Also save `playbookKey` and `playbook.name` to MongoDB
   131→}
   132→```
   133→
   134→In the `saveAIResponse` call inside the loop, add `deep_analysis_playbook: playbookKey`.
   135→
   136→---
   137→
   138→## Step 4: Deep Analysis Results as Dedicated Tab
   139→
   140→Add a new tab to the thread view for deep analysis results, sitting alongside the existing email timeline and AI query panel.
   141→
   142→**Add tab button** in the thread view navigation area (where the main thread layout is):
   143→
   144→After the existing `ai-response-container`, add a container for the tabbed deep analysis results view. This uses the same `deep-analysis-container` div but enhances it with tabs for each playbook run.
   145→
   146→The `loadDeepAnalysis()` function already handles this — just make the container more prominent and keep it visible as a section rather than a popup.
   147→
   148→---
   149→
   150→## Step 5: Save Playbook to MongoDB
   151→
   152→Update `save_ai_response` API (api.php line ~4802) to persist new field:
   153→- `deep_analysis_playbook` — the playbook key (e.g., 'win_back', 'quote_optimize')
   154→
   155→Update `load_deep_analysis` API to also return the playbook key.
   156→
   157→---
   158→
   159→## Full Playbook Prompts
   160→
   161→### Playbook 1: Win Back Lost Client (existing 5 passes — keep as-is)
   162→
   163→### Playbook 2: Re-Engagement Emails
   164→
   165→**Pass 1 — How to Regain Client:**
   166→```
   167→Based on the complete email history, analyze WHY we lost this client and create a detailed re-engagement strategy:
   168→1. What exactly caused them to leave? (be specific, quote emails)
   169→2. What do they value most in a business partner?
   170→3. What unmet needs might their current supplier have?
   171→4. What timing signals suggest they might be open to reconnecting?
   172→5. What would make them give us a second chance?
   173→6. What should we absolutely avoid mentioning or doing?
   174→```
   175→
   176→**Pass 2 — Direct Re-engagement Email:**
   177→```
   178→Draft a professional re-engagement email to win back this client. Use these persuasion techniques:
   179→- RECIPROCITY: Offer something valuable upfront (insight, free consultation, industry report)
   180→- SOCIAL PROOF: Reference similar clients we've helped recently
   181→- SCARCITY: Mention limited availability or exclusive offer
   182→- AUTHORITY: Subtly demonstrate our expertise growth since we last worked together
   183→- LIKING: Reference specific positive memories from our past collaboration
   184→- COMMITMENT: Start with a small ask (meeting, not a contract)
   185→
   186→The email must feel natural, not salesy. Reference specific details from our history. Keep it under 200 words.
   187→```
   188→
   189→**Pass 3 — AI Value Proposition Email:**
   190→```
   191→Draft a re-engagement email specifically focused on how AI can benefit THIS client's company. Based on their industry and business:
   192→1. Research what their company does (from email context) and identify 3 specific AI use cases
   193→2. Explain how AI could solve problems they mentioned in emails or improve their operations
   194→3. Position us as the bridge between their business and AI transformation
   195→4. Include a concrete example or mini case study relevant to their industry
   196→5. Offer a free AI readiness assessment or demo
   197→
   198→Make it compelling, specific to THEIR company, not generic. Use the Cialdini persuasion principles subtly.
   199→```
   200→
   201→**Pass 4 — Indirect Re-engagement Plan:**
   202→```
   203→Create a 2-3 step INDIRECT re-engagement plan. Instead of contacting them directly, propose indirect touchpoints:
   204→1. STEP 1: Social/professional interaction (LinkedIn engagement, industry event, mutual connection intro, comment on their company news)
   205→2. STEP 2: Value-first contact (share a relevant article, invite to a webinar, send an industry report that benefits them)
   206→3. STEP 3: Warm re-engagement (after steps 1-2 create familiarity, make the direct ask)
   207→
   208→For each step: specify WHAT to do, WHEN, through which CHANNEL, and WHAT to say. Use persuasion psychology: mere exposure effect, Ben Franklin effect, door-in-the-face, foot-in-the-door techniques.
   209→```
   210→
   211→**Pass 5 — Persuasion Techniques Toolkit:**
   212→```
   213→Based on all email history and the client's psychological profile, create a persuasion toolkit:
   214→1. LOSS AVERSION: What are they losing by NOT working with us? Frame it.
   215→2. ANCHORING: What high-value anchor should we set before making our actual offer?
   216→3. CONTRAST PRINCIPLE: How to position our offer vs their current situation
   217→4. STORYTELLING: Craft a compelling narrative about a similar client's transformation
   218→5. OBJECTION HANDLING: List their likely objections and pre-written responses
   219→6. URGENCY TRIGGERS: What legitimate urgency factors can we introduce?
   220→7. NEGOTIATION PLAYBOOK: If they engage, what's our opening position, walkaway point, and BATNA?
   221→```
   222→
   223→### Playbook 3: Quote Optimization
   224→
   225→**Pass 1 — Quote & Pricing History:**
   226→```
   227→Analyze ALL pricing/quoting history in these emails:
   228→1. Create a TABLE of every quote, price, amount, date, and what it was for
   229→2. Track how prices changed over time — did we increase, decrease, or stay flat?
   230→3. What discounts did we give and why? Were they justified?
   231→4. How did the client react to each price point? (accepted quickly = too low, pushed back hard = near their limit)
   232→5. What's the client's apparent budget range based on their reactions?
   233→6. Are there patterns in WHEN they accept quotes (end of quarter, start of year, etc.)?
   234→```
   235→
   236→**Pass 2 — Client Budget & Willingness:**
   237→```
   238→Build a psychological pricing profile for this client:
   239→1. What's their budget authority? Who approves what amounts?
   240→2. Are they price-sensitive or value-sensitive? Evidence from emails.
   241→3. Do they comparison shop? Have they mentioned competitors or alternative quotes?
   242→4. What non-price factors influence their decision (speed, quality, relationship, support)?
   243→5. What's their pain threshold — at what price point do they push back vs walk away?
   244→6. Do they negotiate every time or accept fair prices? What's their negotiation style?
   245→7. WILLINGNESS TO PAY: Based on all evidence, what's the maximum they would pay for our typical service?
   246→```
   247→
   248→**Pass 3 — Value Framing Strategy:**
   249→```
   250→Create a value framing strategy to maximize what we can charge:
   251→1. REFRAME FROM COST TO INVESTMENT: How to position our price as ROI, not expense
   252→2. UNBUNDLING: Can we break our offering into components to increase perceived value?
   253→3. TIERED OPTIONS: Design 3 pricing tiers (Good/Better/Best) with the middle one being our target
   254→4. COMPARISON ANCHORING: What expensive alternatives exist that make our price seem reasonable?
   255→5. VALUE QUANTIFICATION: Calculate the actual dollar value we deliver (time saved, revenue generated, problems avoided)
   256→6. RISK REVERSAL: What guarantees or pilot offers reduce their perceived risk?
   257→```
   258→
   259→**Pass 4 — Anchoring & Negotiation Tactics:**
   260→```
   261→Design a negotiation playbook for the current discussion:
   262→1. OPENING ANCHOR: What price should we start with? (typically 15-30% above target)
   263→2. JUSTIFICATION: How to justify the anchor with value-based reasoning
   264→3. CONCESSION STRATEGY: Plan 3 concessions we can make (each smaller than the last) — what to give and what to get in return
   265→4. NIBBLING: Small add-ons we can include that cost us little but add perceived value
   266→5. DEADLINE STRATEGY: How to create legitimate urgency without being pushy
   267→6. WALK-AWAY POINT: Below what price is this project not worth doing?
   268→7. BATNA: What's our best alternative if this deal doesn't happen?
   269→8. IF THEY WANT TO NEGOTIATE: Script for handling "can you do better on price?" with reciprocity
   270→```
   271→
   272→**Pass 5 — Optimal Quote Recommendation:**
   273→```
   274→Based on all previous analysis, recommend the optimal quote:
   275→1. RECOMMENDED PRICE: Exact amount with justification
   276→2. FLOOR PRICE: Minimum acceptable amount
   277→3. CEILING PRICE: Maximum we could reasonably charge
   278→4. PRESENTATION FORMAT: How to structure the quote document for maximum impact
   279→5. WHAT TO INCLUDE: Line items, value descriptions, terms that favor us
   280→6. WHAT TO EXCLUDE: Items to hold back for negotiation leverage
   281→7. TIMING: When to send the quote for best acceptance probability
   282→8. FOLLOW-UP SCRIPT: What to say 3 days after sending if no response
   283→9. MULTI-ROUND PLAN: If they push back, what's the next version of the quote?
   284→```
   285→
   286→### Playbook 4: Full Relationship Analysis (reuses passes from win_back: timeline, profiles, financial, pressure — no win-back pass)
   287→
   288→---
   289→
   290→## Verification
   291→
   292→1. Page loads: dropdown populated with 4 playbooks
   293→2. Select "Win Back Lost Client" → button shows "Deep Analysis" → runs 5 passes sequentially
   294→3. Select "Quote Optimization" → runs 5 quote-focused passes
   295→4. Results display in the deep analysis container with per-pass sections
   296→5. "Load Deep Analysis" button on page reload restores all results
   297→6. Deep analysis pass badges shown on saved responses
   298→7. `php -l` passes on all modified PHP files
   299→

# Deep Analysis Enhancement — Configurable Playbooks with Dropdown Selection

## Context

The current Deep Analysis feature has 5 hardcoded passes focused on one use case (lost client win-back). The user wants:
1. **Configurable analysis playbooks** — not hardcoded, ability to add/edit/manage passes
2. **Dropdown selection** — pick which playbook to run, then hit Deep Analysis
3. **New playbooks** for different business scenarios (win-back, quote optimization, persuasion)
4. **Results in a dedicated tab** — not just inline, a proper tabbed view for deep analysis results

## Architecture

### Replace hardcoded `DEEP_ANALYSIS_PASSES` with `DEEP_ANALYSIS_PLAYBOOKS`

A **playbook** is a named collection of passes. The dropdown selects a playbook, and the Deep Analysis button runs all passes in that playbook sequentially.

### File: `public/thread_view.php` (all changes in one file)

---

## Step 1: Define Playbooks Constant

**Replace** the current `DEEP_ANALYSIS_PASSES` array (lines 1567-1598) with `DEEP_ANALYSIS_PLAYBOOKS` object:

```javascript
const DEEP_ANALYSIS_PLAYBOOKS = {
    // ---- LOST CLIENT WIN-BACK ----
    'win_back': {
        name: 'Win Back Lost Client',
        description: 'Full relationship analysis + win-back strategy',
        passes: [
            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' },
            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
            { id: 'winback', name: 'Win-Back Strategy', agent: 'general', prompt: '...' }
        ]
    },

    // ---- RE-ENGAGEMENT EMAIL DRAFTS ----
    'regain_email': {
        name: 'Re-Engagement Emails',
        description: 'Draft re-engagement emails with persuasion techniques',
        passes: [
            { id: 'regain_analysis', name: 'How to Regain Client', agent: 'general', prompt: '...' },
            { id: 'regain_email_direct', name: 'Direct Re-engagement Email', agent: 'email_composer', prompt: '...' },
            { id: 'regain_email_ai', name: 'AI Value Proposition Email', agent: 'email_composer', prompt: '...' },
            { id: 'indirect_steps', name: 'Indirect Re-engagement Plan', agent: 'general', prompt: '...' },
            { id: 'persuasion_toolkit', name: 'Persuasion Techniques', agent: 'general', prompt: '...' }
        ]
    },

    // ---- QUOTE OPTIMIZATION ----
    'quote_optimize': {
        name: 'Quote Optimization',
        description: 'Maximize quote value for current client discussions',
        passes: [
            { id: 'quote_history', name: 'Quote & Pricing History', agent: 'quote_analyst', prompt: '...' },
            { id: 'client_budget', name: 'Client Budget & Willingness', agent: 'contact_profiler', prompt: '...' },
            { id: 'value_framing', name: 'Value Framing Strategy', agent: 'general', prompt: '...' },
            { id: 'anchoring', name: 'Anchoring & Negotiation Tactics', agent: 'general', prompt: '...' },
            { id: 'quote_draft', name: 'Optimal Quote Recommendation', agent: 'quote_analyst', prompt: '...' }
        ]
    },

    // ---- FULL RELATIONSHIP ANALYSIS ----
    'relationship': {
        name: 'Full Relationship Analysis',
        description: 'Comprehensive relationship health check',
        passes: [
            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' }
        ]
    }
};
```

---

## Step 2: Playbook Dropdown + Deep Analysis Button UI

**Replace** the current button area (lines 1437-1445) with dropdown + button:

```html
<div style="display:flex;gap:8px;">
    <button class="btn btn-primary" id="submit-ai-btn" onclick="submitToAI()" style="flex:1;">
        Send to AI
    </button>
</div>
<div style="display:flex;gap:8px;margin-top:8px;">
    <select id="deep-analysis-playbook" style="flex:2;padding:8px;border-radius:6px;border:1px solid #ccc;font-size:0.9em;">
        <!-- Populated from DEEP_ANALYSIS_PLAYBOOKS by JS -->
    </select>
    <button class="btn" id="deep-analysis-btn" onclick="runDeepAnalysis()" style="flex:1;background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;font-weight:600;">
        Deep Analysis
    </button>
</div>
```

Add JS to populate dropdown on page load:
```javascript
function initPlaybookDropdown() {
    var sel = document.getElementById('deep-analysis-playbook');
    for (var key in DEEP_ANALYSIS_PLAYBOOKS) {
        var pb = DEEP_ANALYSIS_PLAYBOOKS[key];
        var opt = document.createElement('option');
        opt.value = key;
        opt.textContent = pb.name + ' (' + pb.passes.length + ' passes)';
        opt.title = pb.description;
        sel.appendChild(opt);
    }
}
```

---

## Step 3: Update `runDeepAnalysis()` to Use Selected Playbook

Change the function to read the selected playbook from the dropdown instead of using the hardcoded `DEEP_ANALYSIS_PASSES`:

```javascript
async function runDeepAnalysis() {
    var playbookKey = document.getElementById('deep-analysis-playbook').value;
    var playbook = DEEP_ANALYSIS_PLAYBOOKS[playbookKey];
    if (!playbook) { alert('Select a playbook'); return; }
    var passes = playbook.passes;
    // ... rest of function uses `passes` instead of `DEEP_ANALYSIS_PASSES`
    // Also save `playbookKey` and `playbook.name` to MongoDB
}
```

In the `saveAIResponse` call inside the loop, add `deep_analysis_playbook: playbookKey`.

---

## Step 4: Deep Analysis Results as Dedicated Tab

Add a new tab to the thread view for deep analysis results, sitting alongside the existing email timeline and AI query panel.

**Add tab button** in the thread view navigation area (where the main thread layout is):

After the existing `ai-response-container`, add a container for the tabbed deep analysis results view. This uses the same `deep-analysis-container` div but enhances it with tabs for each playbook run.

The `loadDeepAnalysis()` function already handles this — just make the container more prominent and keep it visible as a section rather than a popup.

---

## Step 5: Save Playbook to MongoDB

Update `save_ai_response` API (api.php line ~4802) to persist new field:
- `deep_analysis_playbook` — the playbook key (e.g., 'win_back', 'quote_optimize')

Update `load_deep_analysis` API to also return the playbook key.

---

## Full Playbook Prompts

### Playbook 1: Win Back Lost Client (existing 5 passes — keep as-is)

### Playbook 2: Re-Engagement Emails

**Pass 1 — How to Regain Client:**
```
Based on the complete email history, analyze WHY we lost this client and create a detailed re-engagement strategy:
1. What exactly caused them to leave? (be specific, quote emails)
2. What do they value most in a business partner?
3. What unmet needs might their current supplier have?
4. What timing signals suggest they might be open to reconnecting?
5. What would make them give us a second chance?
6. What should we absolutely avoid mentioning or doing?
```

**Pass 2 — Direct Re-engagement Email:**
```
Draft a professional re-engagement email to win back this client. Use these persuasion techniques:
- RECIPROCITY: Offer something valuable upfront (insight, free consultation, industry report)
- SOCIAL PROOF: Reference similar clients we've helped recently
- SCARCITY: Mention limited availability or exclusive offer
- AUTHORITY: Subtly demonstrate our expertise growth since we last worked together
- LIKING: Reference specific positive memories from our past collaboration
- COMMITMENT: Start with a small ask (meeting, not a contract)

The email must feel natural, not salesy. Reference specific details from our history. Keep it under 200 words.
```

**Pass 3 — AI Value Proposition Email:**
```
Draft a re-engagement email specifically focused on how AI can benefit THIS client's company. Based on their industry and business:
1. Research what their company does (from email context) and identify 3 specific AI use cases
2. Explain how AI could solve problems they mentioned in emails or improve their operations
3. Position us as the bridge between their business and AI transformation
4. Include a concrete example or mini case study relevant to their industry
5. Offer a free AI readiness assessment or demo

Make it compelling, specific to THEIR company, not generic. Use the Cialdini persuasion principles subtly.
```

**Pass 4 — Indirect Re-engagement Plan:**
```
Create a 2-3 step INDIRECT re-engagement plan. Instead of contacting them directly, propose indirect touchpoints:
1. STEP 1: Social/professional interaction (LinkedIn engagement, industry event, mutual connection intro, comment on their company news)
2. STEP 2: Value-first contact (share a relevant article, invite to a webinar, send an industry report that benefits them)
3. STEP 3: Warm re-engagement (after steps 1-2 create familiarity, make the direct ask)

For each step: specify WHAT to do, WHEN, through which CHANNEL, and WHAT to say. Use persuasion psychology: mere exposure effect, Ben Franklin effect, door-in-the-face, foot-in-the-door techniques.
```

**Pass 5 — Persuasion Techniques Toolkit:**
```
Based on all email history and the client's psychological profile, create a persuasion toolkit:
1. LOSS AVERSION: What are they losing by NOT working with us? Frame it.
2. ANCHORING: What high-value anchor should we set before making our actual offer?
3. CONTRAST PRINCIPLE: How to position our offer vs their current situation
4. STORYTELLING: Craft a compelling narrative about a similar client's transformation
5. OBJECTION HANDLING: List their likely objections and pre-written responses
6. URGENCY TRIGGERS: What legitimate urgency factors can we introduce?
7. NEGOTIATION PLAYBOOK: If they engage, what's our opening position, walkaway point, and BATNA?
```

### Playbook 3: Quote Optimization

**Pass 1 — Quote & Pricing History:**
```
Analyze ALL pricing/quoting history in these emails:
1. Create a TABLE of every quote, price, amount, date, and what it was for
2. Track how prices changed over time — did we increase, decrease, or stay flat?
3. What discounts did we give and why? Were they justified?
4. How did the client react to each price point? (accepted quickly = too low, pushed back hard = near their limit)
5. What's the client's apparent budget range based on their reactions?
6. Are there patterns in WHEN they accept quotes (end of quarter, start of year, etc.)?
```

**Pass 2 — Client Budget & Willingness:**
```
Build a psychological pricing profile for this client:
1. What's their budget authority? Who approves what amounts?
2. Are they price-sensitive or value-sensitive? Evidence from emails.
3. Do they comparison shop? Have they mentioned competitors or alternative quotes?
4. What non-price factors influence their decision (speed, quality, relationship, support)?
5. What's their pain threshold — at what price point do they push back vs walk away?
6. Do they negotiate every time or accept fair prices? What's their negotiation style?
7. WILLINGNESS TO PAY: Based on all evidence, what's the maximum they would pay for our typical service?
```

**Pass 3 — Value Framing Strategy:**
```
Create a value framing strategy to maximize what we can charge:
1. REFRAME FROM COST TO INVESTMENT: How to position our price as ROI, not expense
2. UNBUNDLING: Can we break our offering into components to increase perceived value?
3. TIERED OPTIONS: Design 3 pricing tiers (Good/Better/Best) with the middle one being our target
4. COMPARISON ANCHORING: What expensive alternatives exist that make our price seem reasonable?
5. VALUE QUANTIFICATION: Calculate the actual dollar value we deliver (time saved, revenue generated, problems avoided)
6. RISK REVERSAL: What guarantees or pilot offers reduce their perceived risk?
```

**Pass 4 — Anchoring & Negotiation Tactics:**
```
Design a negotiation playbook for the current discussion:
1. OPENING ANCHOR: What price should we start with? (typically 15-30% above target)
2. JUSTIFICATION: How to justify the anchor with value-based reasoning
3. CONCESSION STRATEGY: Plan 3 concessions we can make (each smaller than the last) — what to give and what to get in return
4. NIBBLING: Small add-ons we can include that cost us little but add perceived value
5. DEADLINE STRATEGY: How to create legitimate urgency without being pushy
6. WALK-AWAY POINT: Below what price is this project not worth doing?
7. BATNA: What's our best alternative if this deal doesn't happen?
8. IF THEY WANT TO NEGOTIATE: Script for handling "can you do better on price?" with reciprocity
```

**Pass 5 — Optimal Quote Recommendation:**
```
Based on all previous analysis, recommend the optimal quote:
1. RECOMMENDED PRICE: Exact amount with justification
2. FLOOR PRICE: Minimum acceptable amount
3. CEILING PRICE: Maximum we could reasonably charge
4. PRESENTATION FORMAT: How to structure the quote document for maximum impact
5. WHAT TO INCLUDE: Line items, value descriptions, terms that favor us
6. WHAT TO EXCLUDE: Items to hold back for negotiation leverage
7. TIMING: When to send the quote for best acceptance probability
8. FOLLOW-UP SCRIPT: What to say 3 days after sending if no response
9. MULTI-ROUND PLAN: If they push back, what's the next version of the quote?
```

### Playbook 4: Full Relationship Analysis (reuses passes from win_back: timeline, profiles, financial, pressure — no win-back pass)

---

## Verification

1. Page loads: dropdown populated with 4 playbooks
2. Select "Win Back Lost Client" → button shows "Deep Analysis" → runs 5 passes sequentially
3. Select "Quote Optimization" → runs 5 quote-focused passes
4. Results display in the deep analysis container with per-pass sections
5. "Load Deep Analysis" button on page reload restores all results
6. Deep analysis pass badges shown on saved responses
7. `php -l` passes on all modified PHP files


Task

Explore current deep analysis code

Prompt:
I need to understand the current Deep Analysis implementation in thread_view.php. Find:

1. The DEEP_ANALYSIS_PASSES constant definition (exact line numbers and content)
2. The runDeepAnalysis() function (exact line numbers)
3. The Deep Analysis button HTML (exact line numbers)
4. The loadDeepAnalysis() function (exact line numbers)
5. The initPlaybookDropdown or similar initialization code if it exists
6. Where the deep analysis container HTML is defined

Search in /var/www/mssql.danmarcrm.com/dev1/extension2v1/public/thread_view.php

Also check /var/www/mssql.danmarcrm.com/dev1/extension2v1/public/api.php for:
1. The save_ai_response endpoint (line numbers where deep_analysis fields are handled)
2. The load_deep_analysis endpoint (line numbers)

Return exact line numbers for all findings.


Explore current deep analysis code


Perfect! Now I have all the information needed. Let me compile the comprehensive report:

## Deep Analysis Implementation - Complete Findings

### thread_view.php

#### 1. DEEP_ANALYSIS_PASSES Constant Definition
**Location:** Lines 1567-1598

```javascript
const DEEP_ANALYSIS_PASSES = [
    {
        id: 'timeline',
        name: 'Business Relationship Timeline',
        agent: 'general',
        prompt: '...'
    },
    {
        id: 'pressure',
        name: 'Pressure & Manipulation Detection',
        agent: 'deception_detector',
        prompt: '...'
    },
    {
        id: 'profiles',
        name: 'Psychological Profiles',
        agent: 'contact_profiler',
        prompt: '...'
    },
    {
        id: 'financial',
        name: 'Financial & Business Patterns',
        agent: 'quote_analyst',
        prompt: '...'
    },
    {
        id: 'winback',
        name: 'Win-Back Strategy',
        agent: 'general',
        prompt: '...'
    }
];
```

#### 2. Deep Analysis Button HTML
**Location:** Lines 1442-1444

```html
<button class="btn" id="deep-analysis-btn" onclick="runDeepAnalysis()" style="flex:1;background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;font-weight:600;">
    Deep Analysis (5-Pass)
</button>
```

#### 3. Deep Analysis Container HTML
**Location:** Lines 1221-1233

```html
<!-- Deep Analysis Results Container -->
<div id="deep-analysis-container" style="display:none; margin-bottom:20px;">
    <div class="card">
        <div class="card-header" style="background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;">
            <h2 style="color:white;">Deep Analysis</h2>
            <div style="display:flex;gap:8px;align-items:center;">
                <span id="deep-analysis-progress" style="font-size:0.85em;opacity:0.9;"></span>
                <button class="btn" style="background:rgba(255,255,255,0.2);color:white;border:1px solid rgba(255,255,255,0.3);" onclick="document.getElementById('deep-analysis-container').style.display='none'">Close</button>
            </div>
        </div>
        <div id="deep-analysis-results" style="padding:15px;"></div>
    </div>
</div>
```

#### 4. Load Deep Analysis Button HTML
**Location:** Lines 1241-1242

```html
<button class="btn" onclick="loadDeepAnalysis()" style="background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;font-size:0.85em;">Load Deep Analysis</button>
```

#### 5. runDeepAnalysis() Function
**Location:** Lines 3079-3350

The function:
- Validates provider selection (line 3081-3085)
- Builds models map (line 3088-3092)
- Confirms with user (line 3095-3098)
- Gets content settings (line 3101-3107)
- Shows deep analysis container (line 3110-3115)
- Disables buttons (line 3118-3120)
- Builds base email content once (line 3123-3156)
- **Runs each pass sequentially** (line 3160-3329):
  - Gets pass definition from DEEP_ANALYSIS_PASSES (line 3161)
  - Builds agent prompt + full content (line 3180-3195)
  - Sends to AI via api_opus proxy (line 3232-3240)
  - **Saves response with deep_analysis_pass + deep_analysis_name fields** (line 3272-3290)
  - Adds to conversation history (line 3298-3300)
  - Pauses 2 seconds between passes (line 3325-3328)
- Shows completion summary (line 3332-3340)

#### 6. loadDeepAnalysis() Function
**Location:** Lines 3353-3413

The function:
- Gets saved deep analysis from MongoDB via `api.php?action=load_deep_analysis` (line 3364)
- Groups responses by pass number (implicit in API response)
- Renders each pass as a section (line 3376-3400)
- Shows pass name, agent, provider responses with model/time/cost (line 3382-3395)
- Shows completion footer (line 3402-3407)

#### 7. saveAIResponse() Function
**Location:** Lines 3716-3726

```javascript
async function saveAIResponse(responseData) {
    try {
        await fetch('api.php?action=save_ai_response', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(responseData)
        });
    } catch (error) {
        console.error('Failed to save response:', error);
    }
}
```

**Key:** Called from runDeepAnalysis() at line 3272 with responseData containing:
- `deep_analysis_pass`: pass number (1-5)
- `deep_analysis_name`: pass name (e.g., 'Business Relationship Timeline')

### api.php

#### 1. save_ai_response Endpoint
**Location:** Lines 4762-4819

**Deep Analysis Fields Handling:**

- **Line 4802:** `'deep_analysis_pass' => isset($jsonData['deep_analysis_pass']) ? (int)$jsonData['deep_analysis_pass'] : null,`
- **Line 4803:** `'deep_analysis_name' => $jsonData['deep_analysis_name'] ?? null,`
- **Line 4809:** `if ($responseDoc['deep_analysis_pass'] === null) unset($responseDoc['deep_analysis_pass']);`
- **Line 4810:** `if ($responseDoc['deep_analysis_name'] === null) unset($responseDoc['deep_analysis_name']);`
- **Line 4812:** Inserts into `ai_query_responses` collection

#### 2. load_deep_analysis Endpoint
**Location:** Lines 4938-5016

**Key Operations:**

1. **Primary query** (lines 4946-4951): Finds all responses with `deep_analysis_pass` field
   ```php
   $mongo->findAll('ai_query_responses', [
       'thread_ids' => $threadId,
       'deep_analysis_pass' => ['$exists' => true]
   ], [
       'sort' => ['deep_analysis_pass' => 1, 'created_at' => -1]
   ]);
   ```

2. **Fallback detection** (lines 4954-4982): If no tagged responses, matches question text patterns
   - Pass 5: 'CONCRETE win-back strategy'
   - Pass 1: 'Analyze the COMPLETE email history chronologically'
   - Pass 3: 'psychological and business profiles for EACH'
   - Pass 4: 'ALL PRICES QUOTED'
   - Pass 2: 'PRESSURE TACTICS: Where did they push unreasonable'

3. **Grouping by pass** (lines 4985-5005): Organizes responses by pass number with:
   - `pass`: pass number
   - `name`: deep_analysis_name
   - `agent`: agent identifier
   - `responses`: array with provider, model, response text, cost, request_time

4. **Response format** (lines 5011-5015):
   ```php
   jsonResponse([
       'success' => true,
       'passes' => $passes,
       'total_responses' => count($responses)
   ]);
   ```

---

## Summary

The Deep Analysis system is a 5-pass sequential analysis pipeline:
1. Each pass is defined in `DEEP_ANALYSIS_PASSES` constant
2. `runDeepAnalysis()` iterates through passes, sending each to AI with accumulated conversation history
3. Responses are saved with `deep_analysis_pass` (1-5) and `deep_analysis_name` field to identify which pass they belong to
4. `loadDeepAnalysis()` retrieves saved responses via API endpoint
5. The API endpoint groups responses by pass number for display

All absolute file paths are:
- `/var/www/mssql.danmarcrm.com/dev1/extension2v1/public/thread_view.php`
- `/var/www/mssql.danmarcrm.com/dev1/extension2v1/public/api.php`

agentId: a31ca17 (for resuming to continue this agent's work if needed)
<usage>total_tokens: 38076
tool_uses: 18
duration_ms: 38891</usage>

Prompt:
I need to understand the current Deep Analysis implementation in thread_view.php. Find:

1. The DEEP_ANALYSIS_PASSES constant definition (exact line numbers and content)
2. The runDeepAnalysis() function (exact line numbers)
3. The Deep Analysis button HTML (exact line numbers)
4. The loadDeepAnalysis() function (exact line numbers)
5. The initPlaybookDropdown or similar initialization code if it exists
6. Where the deep analysis container HTML is defined

Search in /var/www/mssql.danmarcrm.com/dev1/extension2v1/public/thread_view.php

Also check /var/www/mssql.danmarcrm.com/dev1/extension2v1/public/api.php for:
1. The save_ai_response endpoint (line numbers where deep_analysis fields are handled)
2. The load_deep_analysis endpoint (line numbers)

Return exact line numbers for all findings.


I have the plan and the exploration results. The plan is complete and was previously approved by the user. I'm in plan mode, so I need to exit plan mode to start implementation. The plan file is already complete with all the details needed. Let me exit plan mode.


The plan is complete and comprehensive. All the key locations have been confirmed:

- **DEEP_ANALYSIS_PASSES**: Lines 1567-1598 in thread_view.php
- **Deep Analysis button**: Lines 1442-1444
- **Deep Analysis container**: Lines 1221-1233
- **runDeepAnalysis()**: Lines 3079-3350
- **loadDeepAnalysis()**: Lines 3353-3413
- **save_ai_response** (deep analysis fields): Lines 4802-4810 in api.php
- **load_deep_analysis** endpoint: Lines 4938-5016 in api.php

The plan covers all 5 steps:
1. Replace `DEEP_ANALYSIS_PASSES` with `DEEP_ANALYSIS_PLAYBOOKS` (4 playbooks with full prompts)
2. Add dropdown UI for playbook selection
3. Update `runDeepAnalysis()` to use selected playbook
4. Deep Analysis results container enhancement
5. MongoDB persistence of `deep_analysis_playbook` field

Let me exit plan mode to begin implementation.


ExitPlanMode

# Deep Analysis Enhancement — Configurable Playbooks with Dropdown Selection

## Context

The current Deep Analysis feature has 5 hardcoded passes focused on one use case (lost client win-back). The user wants:
1. **Configurable analysis playbooks** — not hardcoded, ability to add/edit/manage passes
2. **Dropdown selection** — pick which playbook to run, then hit Deep Analysis
3. **New playbooks** for different business scenarios (win-back, quote optimization, persuasion)
4. **Results in a dedicated tab** — not just inline, a proper tabbed view for deep analysis results

## Architecture

### Replace hardcoded `DEEP_ANALYSIS_PASSES` with `DEEP_ANALYSIS_PLAYBOOKS`

A **playbook** is a named collection of passes. The dropdown selects a playbook, and the Deep Analysis button runs all passes in that playbook sequentially.

### File: `public/thread_view.php` (all changes in one file)

---

## Step 1: Define Playbooks Constant

**Replace** the current `DEEP_ANALYSIS_PASSES` array (lines 1567-1598) with `DEEP_ANALYSIS_PLAYBOOKS` object:

```javascript
const DEEP_ANALYSIS_PLAYBOOKS = {
    // ---- LOST CLIENT WIN-BACK ----
    'win_back': {
        name: 'Win Back Lost Client',
        description: 'Full relationship analysis + win-back strategy',
        passes: [
            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' },
            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
            { id: 'winback', name: 'Win-Back Strategy', agent: 'general', prompt: '...' }
        ]
    },

    // ---- RE-ENGAGEMENT EMAIL DRAFTS ----
    'regain_email': {
        name: 'Re-Engagement Emails',
        description: 'Draft re-engagement emails with persuasion techniques',
        passes: [
            { id: 'regain_analysis', name: 'How to Regain Client', agent: 'general', prompt: '...' },
            { id: 'regain_email_direct', name: 'Direct Re-engagement Email', agent: 'email_composer', prompt: '...' },
            { id: 'regain_email_ai', name: 'AI Value Proposition Email', agent: 'email_composer', prompt: '...' },
            { id: 'indirect_steps', name: 'Indirect Re-engagement Plan', agent: 'general', prompt: '...' },
            { id: 'persuasion_toolkit', name: 'Persuasion Techniques', agent: 'general', prompt: '...' }
        ]
    },

    // ---- QUOTE OPTIMIZATION ----
    'quote_optimize': {
        name: 'Quote Optimization',
        description: 'Maximize quote value for current client discussions',
        passes: [
            { id: 'quote_history', name: 'Quote & Pricing History', agent: 'quote_analyst', prompt: '...' },
            { id: 'client_budget', name: 'Client Budget & Willingness', agent: 'contact_profiler', prompt: '...' },
            { id: 'value_framing', name: 'Value Framing Strategy', agent: 'general', prompt: '...' },
            { id: 'anchoring', name: 'Anchoring & Negotiation Tactics', agent: 'general', prompt: '...' },
            { id: 'quote_draft', name: 'Optimal Quote Recommendation', agent: 'quote_analyst', prompt: '...' }
        ]
    },

    // ---- FULL RELATIONSHIP ANALYSIS ----
    'relationship': {
        name: 'Full Relationship Analysis',
        description: 'Comprehensive relationship health check',
        passes: [
            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' }
        ]
    }
};
```

---

## Step 2: Playbook Dropdown + Deep Analysis Button UI

**Replace** the current button area (lines 1437-1445) with dropdown + button:

```html
<div style="display:flex;gap:8px;">
    <button class="btn btn-primary" id="submit-ai-btn" onclick="submitToAI()" style="flex:1;">
        Send to AI
    </button>
</div>
<div style="display:flex;gap:8px;margin-top:8px;">
    <select id="deep-analysis-playbook" style="flex:2;padding:8px;border-radius:6px;border:1px solid #ccc;font-size:0.9em;">
        <!-- Populated from DEEP_ANALYSIS_PLAYBOOKS by JS -->
    </select>
    <button class="btn" id="deep-analysis-btn" onclick="runDeepAnalysis()" style="flex:1;background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;font-weight:600;">
        Deep Analysis
    </button>
</div>
```

Add JS to populate dropdown on page load:
```javascript
function initPlaybookDropdown() {
    var sel = document.getElementById('deep-analysis-playbook');
    for (var key in DEEP_ANALYSIS_PLAYBOOKS) {
        var pb = DEEP_ANALYSIS_PLAYBOOKS[key];
        var opt = document.createElement('option');
        opt.value = key;
        opt.textContent = pb.name + ' (' + pb.passes.length + ' passes)';
        opt.title = pb.description;
        sel.appendChild(opt);
    }
}
```

---

## Step 3: Update `runDeepAnalysis()` to Use Selected Playbook

Change the function to read the selected playbook from the dropdown instead of using the hardcoded `DEEP_ANALYSIS_PASSES`:

```javascript
async function runDeepAnalysis() {
    var playbookKey = document.getElementById('deep-analysis-playbook').value;
    var playbook = DEEP_ANALYSIS_PLAYBOOKS[playbookKey];
    if (!playbook) { alert('Select a playbook'); return; }
    var passes = playbook.passes;
    // ... rest of function uses `passes` instead of `DEEP_ANALYSIS_PASSES`
    // Also save `playbookKey` and `playbook.name` to MongoDB
}
```

In the `saveAIResponse` call inside the loop, add `deep_analysis_playbook: playbookKey`.

---

## Step 4: Deep Analysis Results as Dedicated Tab

Add a new tab to the thread view for deep analysis results, sitting alongside the existing email timeline and AI query panel.

**Add tab button** in the thread view navigation area (where the main thread layout is):

After the existing `ai-response-container`, add a container for the tabbed deep analysis results view. This uses the same `deep-analysis-container` div but enhances it with tabs for each playbook run.

The `loadDeepAnalysis()` function already handles this — just make the container more prominent and keep it visible as a section rather than a popup.

---

## Step 5: Save Playbook to MongoDB

Update `save_ai_response` API (api.php line ~4802) to persist new field:
- `deep_analysis_playbook` — the playbook key (e.g., 'win_back', 'quote_optimize')

Update `load_deep_analysis` API to also return the playbook key.

---

## Full Playbook Prompts

### Playbook 1: Win Back Lost Client (existing 5 passes — keep as-is)

### Playbook 2: Re-Engagement Emails

**Pass 1 — How to Regain Client:**
```
Based on the complete email history, analyze WHY we lost this client and create a detailed re-engagement strategy:
1. What exactly caused them to leave? (be specific, quote emails)
2. What do they value most in a business partner?
3. What unmet needs might their current supplier have?
4. What timing signals suggest they might be open to reconnecting?
5. What would make them give us a second chance?
6. What should we absolutely avoid mentioning or doing?
```

**Pass 2 — Direct Re-engagement Email:**
```
Draft a professional re-engagement email to win back this client. Use these persuasion techniques:
- RECIPROCITY: Offer something valuable upfront (insight, free consultation, industry report)
- SOCIAL PROOF: Reference similar clients we've helped recently
- SCARCITY: Mention limited availability or exclusive offer
- AUTHORITY: Subtly demonstrate our expertise growth since we last worked together
- LIKING: Reference specific positive memories from our past collaboration
- COMMITMENT: Start with a small ask (meeting, not a contract)

The email must feel natural, not salesy. Reference specific details from our history. Keep it under 200 words.
```

**Pass 3 — AI Value Proposition Email:**
```
Draft a re-engagement email specifically focused on how AI can benefit THIS client's company. Based on their industry and business:
1. Research what their company does (from email context) and identify 3 specific AI use cases
2. Explain how AI could solve problems they mentioned in emails or improve their operations
3. Position us as the bridge between their business and AI transformation
4. Include a concrete example or mini case study relevant to their industry
5. Offer a free AI readiness assessment or demo

Make it compelling, specific to THEIR company, not generic. Use the Cialdini persuasion principles subtly.
```

**Pass 4 — Indirect Re-engagement Plan:**
```
Create a 2-3 step INDIRECT re-engagement plan. Instead of contacting them directly, propose indirect touchpoints:
1. STEP 1: Social/professional interaction (LinkedIn engagement, industry event, mutual connection intro, comment on their company news)
2. STEP 2: Value-first contact (share a relevant article, invite to a webinar, send an industry report that benefits them)
3. STEP 3: Warm re-engagement (after steps 1-2 create familiarity, make the direct ask)

For each step: specify WHAT to do, WHEN, through which CHANNEL, and WHAT to say. Use persuasion psychology: mere exposure effect, Ben Franklin effect, door-in-the-face, foot-in-the-door techniques.
```

**Pass 5 — Persuasion Techniques Toolkit:**
```
Based on all email history and the client's psychological profile, create a persuasion toolkit:
1. LOSS AVERSION: What are they losing by NOT working with us? Frame it.
2. ANCHORING: What high-value anchor should we set before making our actual offer?
3. CONTRAST PRINCIPLE: How to position our offer vs their current situation
4. STORYTELLING: Craft a compelling narrative about a similar client's transformation
5. OBJECTION HANDLING: List their likely objections and pre-written responses
6. URGENCY TRIGGERS: What legitimate urgency factors can we introduce?
7. NEGOTIATION PLAYBOOK: If they engage, what's our opening position, walkaway point, and BATNA?
```

### Playbook 3: Quote Optimization

**Pass 1 — Quote & Pricing History:**
```
Analyze ALL pricing/quoting history in these emails:
1. Create a TABLE of every quote, price, amount, date, and what it was for
2. Track how prices changed over time — did we increase, decrease, or stay flat?
3. What discounts did we give and why? Were they justified?
4. How did the client react to each price point? (accepted quickly = too low, pushed back hard = near their limit)
5. What's the client's apparent budget range based on their reactions?
6. Are there patterns in WHEN they accept quotes (end of quarter, start of year, etc.)?
```

**Pass 2 — Client Budget & Willingness:**
```
Build a psychological pricing profile for this client:
1. What's their budget authority? Who approves what amounts?
2. Are they price-sensitive or value-sensitive? Evidence from emails.
3. Do they comparison shop? Have they mentioned competitors or alternative quotes?
4. What non-price factors influence their decision (speed, quality, relationship, support)?
5. What's their pain threshold — at what price point do they push back vs walk away?
6. Do they negotiate every time or accept fair prices? What's their negotiation style?
7. WILLINGNESS TO PAY: Based on all evidence, what's the maximum they would pay for our typical service?
```

**Pass 3 — Value Framing Strategy:**
```
Create a value framing strategy to maximize what we can charge:
1. REFRAME FROM COST TO INVESTMENT: How to position our price as ROI, not expense
2. UNBUNDLING: Can we break our offering into components to increase perceived value?
3. TIERED OPTIONS: Design 3 pricing tiers (Good/Better/Best) with the middle one being our target
4. COMPARISON ANCHORING: What expensive alternatives exist that make our price seem reasonable?
5. VALUE QUANTIFICATION: Calculate the actual dollar value we deliver (time saved, revenue generated, problems avoided)
6. RISK REVERSAL: What guarantees or pilot offers reduce their perceived risk?
```

**Pass 4 — Anchoring & Negotiation Tactics:**
```
Design a negotiation playbook for the current discussion:
1. OPENING ANCHOR: What price should we start with? (typically 15-30% above target)
2. JUSTIFICATION: How to justify the anchor with value-based reasoning
3. CONCESSION STRATEGY: Plan 3 concessions we can make (each smaller than the last) — what to give and what to get in return
4. NIBBLING: Small add-ons we can include that cost us little but add perceived value
5. DEADLINE STRATEGY: How to create legitimate urgency without being pushy
6. WALK-AWAY POINT: Below what price is this project not worth doing?
7. BATNA: What's our best alternative if this deal doesn't happen?
8. IF THEY WANT TO NEGOTIATE: Script for handling "can you do better on price?" with reciprocity
```

**Pass 5 — Optimal Quote Recommendation:**
```
Based on all previous analysis, recommend the optimal quote:
1. RECOMMENDED PRICE: Exact amount with justification
2. FLOOR PRICE: Minimum acceptable amount
3. CEILING PRICE: Maximum we could reasonably charge
4. PRESENTATION FORMAT: How to structure the quote document for maximum impact
5. WHAT TO INCLUDE: Line items, value descriptions, terms that favor us
6. WHAT TO EXCLUDE: Items to hold back for negotiation leverage
7. TIMING: When to send the quote for best acceptance probability
8. FOLLOW-UP SCRIPT: What to say 3 days after sending if no response
9. MULTI-ROUND PLAN: If they push back, what's the next version of the quote?
```

### Playbook 4: Full Relationship Analysis (reuses passes from win_back: timeline, profiles, financial, pressure — no win-back pass)

---

## Verification

1. Page loads: dropdown populated with 4 playbooks
2. Select "Win Back Lost Client" → button shows "Deep Analysis" → runs 5 passes sequentially
3. Select "Quote Optimization" → runs 5 quote-focused passes
4. Results display in the deep analysis container with per-pass sections
5. "Load Deep Analysis" button on page reload restores all results
6. Deep analysis pass badges shown on saved responses
7. `php -l` passes on all modified PHP files


User has approved your plan. You can now start coding. Start with updating your todo list if applicable

Your plan has been saved to: /root/.claude/plans/scalable-doodling-peach.md
You can refer back to it if needed during implementation.

## Approved Plan:
# Deep Analysis Enhancement — Configurable Playbooks with Dropdown Selection

## Context

The current Deep Analysis feature has 5 hardcoded passes focused on one use case (lost client win-back). The user wants:
1. **Configurable analysis playbooks** — not hardcoded, ability to add/edit/manage passes
2. **Dropdown selection** — pick which playbook to run, then hit Deep Analysis
3. **New playbooks** for different business scenarios (win-back, quote optimization, persuasion)
4. **Results in a dedicated tab** — not just inline, a proper tabbed view for deep analysis results

## Architecture

### Replace hardcoded `DEEP_ANALYSIS_PASSES` with `DEEP_ANALYSIS_PLAYBOOKS`

A **playbook** is a named collection of passes. The dropdown selects a playbook, and the Deep Analysis button runs all passes in that playbook sequentially.

### File: `public/thread_view.php` (all changes in one file)

---

## Step 1: Define Playbooks Constant

**Replace** the current `DEEP_ANALYSIS_PASSES` array (lines 1567-1598) with `DEEP_ANALYSIS_PLAYBOOKS` object:

```javascript
const DEEP_ANALYSIS_PLAYBOOKS = {
    // ---- LOST CLIENT WIN-BACK ----
    'win_back': {
        name: 'Win Back Lost Client',
        description: 'Full relationship analysis + win-back strategy',
        passes: [
            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' },
            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
            { id: 'winback', name: 'Win-Back Strategy', agent: 'general', prompt: '...' }
        ]
    },

    // ---- RE-ENGAGEMENT EMAIL DRAFTS ----
    'regain_email': {
        name: 'Re-Engagement Emails',
        description: 'Draft re-engagement emails with persuasion techniques',
        passes: [
            { id: 'regain_analysis', name: 'How to Regain Client', agent: 'general', prompt: '...' },
            { id: 'regain_email_direct', name: 'Direct Re-engagement Email', agent: 'email_composer', prompt: '...' },
            { id: 'regain_email_ai', name: 'AI Value Proposition Email', agent: 'email_composer', prompt: '...' },
            { id: 'indirect_steps', name: 'Indirect Re-engagement Plan', agent: 'general', prompt: '...' },
            { id: 'persuasion_toolkit', name: 'Persuasion Techniques', agent: 'general', prompt: '...' }
        ]
    },

    // ---- QUOTE OPTIMIZATION ----
    'quote_optimize': {
        name: 'Quote Optimization',
        description: 'Maximize quote value for current client discussions',
        passes: [
            { id: 'quote_history', name: 'Quote & Pricing History', agent: 'quote_analyst', prompt: '...' },
            { id: 'client_budget', name: 'Client Budget & Willingness', agent: 'contact_profiler', prompt: '...' },
            { id: 'value_framing', name: 'Value Framing Strategy', agent: 'general', prompt: '...' },
            { id: 'anchoring', name: 'Anchoring & Negotiation Tactics', agent: 'general', prompt: '...' },
            { id: 'quote_draft', name: 'Optimal Quote Recommendation', agent: 'quote_analyst', prompt: '...' }
        ]
    },

    // ---- FULL RELATIONSHIP ANALYSIS ----
    'relationship': {
        name: 'Full Relationship Analysis',
        description: 'Comprehensive relationship health check',
        passes: [
            { id: 'timeline', name: 'Business Relationship Timeline', agent: 'general', prompt: '...' },
            { id: 'profiles', name: 'Psychological Profiles', agent: 'contact_profiler', prompt: '...' },
            { id: 'financial', name: 'Financial & Business Patterns', agent: 'quote_analyst', prompt: '...' },
            { id: 'pressure', name: 'Pressure & Manipulation Detection', agent: 'deception_detector', prompt: '...' }
        ]
    }
};
```

---

## Step 2: Playbook Dropdown + Deep Analysis Button UI

**Replace** the current button area (lines 1437-1445) with dropdown + button:

```html
<div style="display:flex;gap:8px;">
    <button class="btn btn-primary" id="submit-ai-btn" onclick="submitToAI()" style="flex:1;">
        Send to AI
    </button>
</div>
<div style="display:flex;gap:8px;margin-top:8px;">
    <select id="deep-analysis-playbook" style="flex:2;padding:8px;border-radius:6px;border:1px solid #ccc;font-size:0.9em;">
        <!-- Populated from DEEP_ANALYSIS_PLAYBOOKS by JS -->
    </select>
    <button class="btn" id="deep-analysis-btn" onclick="runDeepAnalysis()" style="flex:1;background:linear-gradient(135deg,#8b5cf6,#3b82f6);color:white;font-weight:600;">
        Deep Analysis
    </button>
</div>
```

Add JS to populate dropdown on page load:
```javascript
function initPlaybookDropdown() {
    var sel = document.getElementById('deep-analysis-playbook');
    for (var key in DEEP_ANALYSIS_PLAYBOOKS) {
        var pb = DEEP_ANALYSIS_PLAYBOOKS[key];
        var opt = document.createElement('option');
        opt.value = key;
        opt.textContent = pb.name + ' (' + pb.passes.length + ' passes)';
        opt.title = pb.description;
        sel.appendChild(opt);
    }
}
```

---

## Step 3: Update `runDeepAnalysis()` to Use Selected Playbook

Change the function to read the selected playbook from the dropdown instead of using the hardcoded `DEEP_ANALYSIS_PASSES`:

```javascript
async function runDeepAnalysis() {
    var playbookKey = document.getElementById('deep-analysis-playbook').value;
    var playbook = DEEP_ANALYSIS_PLAYBOOKS[playbookKey];
    if (!playbook) { alert('Select a playbook'); return; }
    var passes = playbook.passes;
    // ... rest of function uses `passes` instead of `DEEP_ANALYSIS_PASSES`
    // Also save `playbookKey` and `playbook.name` to MongoDB
}
```

In the `saveAIResponse` call inside the loop, add `deep_analysis_playbook: playbookKey`.

---

## Step 4: Deep Analysis Results as Dedicated Tab

Add a new tab to the thread view for deep analysis results, sitting alongside the existing email timeline and AI query panel.

**Add tab button** in the thread view navigation area (where the main thread layout is):

After the existing `ai-response-container`, add a container for the tabbed deep analysis results view. This uses the same `deep-analysis-container` div but enhances it with tabs for each playbook run.

The `loadDeepAnalysis()` function already handles this — just make the container more prominent and keep it visible as a section rather than a popup.

---

## Step 5: Save Playbook to MongoDB

Update `save_ai_response` API (api.php line ~4802) to persist new field:
- `deep_analysis_playbook` — the playbook key (e.g., 'win_back', 'quote_optimize')

Update `load_deep_analysis` API to also return the playbook key.

---

## Full Playbook Prompts

### Playbook 1: Win Back Lost Client (existing 5 passes — keep as-is)

### Playbook 2: Re-Engagement Emails

**Pass 1 — How to Regain Client:**
```
Based on the complete email history, analyze WHY we lost this client and create a detailed re-engagement strategy:
1. What exactly caused them to leave? (be specific, quote emails)
2. What do they value most in a business partner?
3. What unmet needs might their current supplier have?
4. What timing signals suggest they might be open to reconnecting?
5. What would make them give us a second chance?
6. What should we absolutely avoid mentioning or doing?
```

**Pass 2 — Direct Re-engagement Email:**
```
Draft a professional re-engagement email to win back this client. Use these persuasion techniques:
- RECIPROCITY: Offer something valuable upfront (insight, free consultation, industry report)
- SOCIAL PROOF: Reference similar clients we've helped recently
- SCARCITY: Mention limited availability or exclusive offer
- AUTHORITY: Subtly demonstrate our expertise growth since we last worked together
- LIKING: Reference specific positive memories from our past collaboration
- COMMITMENT: Start with a small ask (meeting, not a contract)

The email must feel natural, not salesy. Reference specific details from our history. Keep it under 200 words.
```

**Pass 3 — AI Value Proposition Email:**
```
Draft a re-engagement email specifically focused on how AI can benefit THIS client's company. Based on their industry and business:
1. Research what their company does (from email context) and identify 3 specific AI use cases
2. Explain how AI could solve problems they mentioned in emails or improve their operations
3. Position us as the bridge between their business and AI transformation
4. Include a concrete example or mini case study relevant to their industry
5. Offer a free AI readiness assessment or demo

Make it compelling, specific to THEIR company, not generic. Use the Cialdini persuasion principles subtly.
```

**Pass 4 — Indirect Re-engagement Plan:**
```
Create a 2-3 step INDIRECT re-engagement plan. Instead of contacting them directly, propose indirect touchpoints:
1. STEP 1: Social/professional interaction (LinkedIn engagement, industry event, mutual connection intro, comment on their company news)
2. STEP 2: Value-first contact (share a relevant article, invite to a webinar, send an industry report that benefits them)
3. STEP 3: Warm re-engagement (after steps 1-2 create familiarity, make the direct ask)

For each step: specify WHAT to do, WHEN, through which CHANNEL, and WHAT to say. Use persuasion psychology: mere exposure effect, Ben Franklin effect, door-in-the-face, foot-in-the-door techniques.
```

**Pass 5 — Persuasion Techniques Toolkit:**
```
Based on all email history and the client's psychological profile, create a persuasion toolkit:
1. LOSS AVERSION: What are they losing by NOT working with us? Frame it.
2. ANCHORING: What high-value anchor should we set before making our actual offer?
3. CONTRAST PRINCIPLE: How to position our offer vs their current situation
4. STORYTELLING: Craft a compelling narrative about a similar client's transformation
5. OBJECTION HANDLING: List their likely objections and pre-written responses
6. URGENCY TRIGGERS: What legitimate urgency factors can we introduce?
7. NEGOTIATION PLAYBOOK: If they engage, what's our opening position, walkaway point, and BATNA?
```

### Playbook 3: Quote Optimization

**Pass 1 — Quote & Pricing History:**
```
Analyze ALL pricing/quoting history in these emails:
1. Create a TABLE of every quote, price, amount, date, and what it was for
2. Track how prices changed over time — did we increase, decrease, or stay flat?
3. What discounts did we give and why? Were they justified?
4. How did the client react to each price point? (accepted quickly = too low, pushed back hard = near their limit)
5. What's the client's apparent budget range based on their reactions?
6. Are there patterns in WHEN they accept quotes (end of quarter, start of year, etc.)?
```

**Pass 2 — Client Budget & Willingness:**
```
Build a psychological pricing profile for this client:
1. What's their budget authority? Who approves what amounts?
2. Are they price-sensitive or value-sensitive? Evidence from emails.
3. Do they comparison shop? Have they mentioned competitors or alternative quotes?
4. What non-price factors influence their decision (speed, quality, relationship, support)?
5. What's their pain threshold — at what price point do they push back vs walk away?
6. Do they negotiate every time or accept fair prices? What's their negotiation style?
7. WILLINGNESS TO PAY: Based on all evidence, what's the maximum they would pay for our typical service?
```

**Pass 3 — Value Framing Strategy:**
```
Create a value framing strategy to maximize what we can charge:
1. REFRAME FROM COST TO INVESTMENT: How to position our price as ROI, not expense
2. UNBUNDLING: Can we break our offering into components to increase perceived value?
3. TIERED OPTIONS: Design 3 pricing tiers (Good/Better/Best) with the middle one being our target
4. COMPARISON ANCHORING: What expensive alternatives exist that make our price seem reasonable?
5. VALUE QUANTIFICATION: Calculate the actual dollar value we deliver (time saved, revenue generated, problems avoided)
6. RISK REVERSAL: What guarantees or pilot offers reduce their perceived risk?
```

**Pass 4 — Anchoring & Negotiation Tactics:**
```
Design a negotiation playbook for the current discussion:
1. OPENING ANCHOR: What price should we start with? (typically 15-30% above target)
2. JUSTIFICATION: How to justify the anchor with value-based reasoning
3. CONCESSION STRATEGY: Plan 3 concessions we can make (each smaller than the last) — what to give and what to get in return
4. NIBBLING: Small add-ons we can include that cost us little but add perceived value
5. DEADLINE STRATEGY: How to create legitimate urgency without being pushy
6. WALK-AWAY POINT: Below what price is this project not worth doing?
7. BATNA: What's our best alternative if this deal doesn't happen?
8. IF THEY WANT TO NEGOTIATE: Script for handling "can you do better on price?" with reciprocity
```

**Pass 5 — Optimal Quote Recommendation:**
```
Based on all previous analysis, recommend the optimal quote:
1. RECOMMENDED PRICE: Exact amount with justification
2. FLOOR PRICE: Minimum acceptable amount
3. CEILING PRICE: Maximum we could reasonably charge
4. PRESENTATION FORMAT: How to structure the quote document for maximum impact
5. WHAT TO INCLUDE: Line items, value descriptions, terms that favor us
6. WHAT TO EXCLUDE: Items to hold back for negotiation leverage
7. TIMING: When to send the quote for best acceptance probability
8. FOLLOW-UP SCRIPT: What to say 3 days after sending if no response
9. MULTI-ROUND PLAN: If they push back, what's the next version of the quote?
```

### Playbook 4: Full Relationship Analysis (reuses passes from win_back: timeline, profiles, financial, pressure — no win-back pass)

---

## Verification

1. Page loads: dropdown populated with 4 playbooks
2. Select "Win Back Lost Client" → button shows "Deep Analysis" → runs 5 passes sequentially
3. Select "Quote Optimization" → runs 5 quote-focused passes
4. Results display in the deep analysis container with per-pass sections
5. "Load Deep Analysis" button on page reload restores all results
6. Deep analysis pass badges shown on saved responses
7. `php -l` passes on all modified PHP files


Now I can start implementing. Let me set up the todo list and begin reading the files I need to modify.


Let me set up the task list and start reading the files I need to modify.


TodoWrite

Replace DEEP_ANALYSIS_PASSES with DEEP_ANALYSIS_PLAYBOOKS constant (4 playbooks, full prompts)

Replacing DEEP_ANALYSIS_PASSES with DEEP_ANALYSIS_PLAYBOOKS constant

Add playbook dropdown UI + update Deep Analysis button

Update runDeepAnalysis() to use selected playbook

Updating runDeepAnalysis() to use selected playbook

Add initPlaybookDropdown() and call on page load

Update api.php: save_ai_response to persist deep_analysis_playbook field

Update api.php: load_deep_analysis to return playbook info

Updating load_deep_analysis API endpoint

Verify with php -l syntax check


Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable

Replace DEEP_ANALYSIS_PASSES with DEEP_ANALYSIS_PLAYBOOKS constant (4 playbooks, full prompts)

Replacing DEEP_ANALYSIS_PASSES with DEEP_ANALYSIS_PLAYBOOKS constant

Add playbook dropdown UI + update Deep Analysis button

Update runDeepAnalysis() to use selected playbook

Updating runDeepAnalysis() to use selected playbook

Add initPlaybookDropdown() and call on page load

Update api.php: save_ai_response to persist deep_analysis_playbook field

Update api.php: load_deep_analysis to return playbook info

Updating load_deep_analysis API endpoint

Verify with php -l syntax check