# Context Management Implementation Plan
**Date:** January 25, 2026
**Version:** 0.1.3+ → 0.2.0
**Status:** 📋 APPROVED - READY FOR IMPLEMENTATION
---
## 📚 Approved Plans Summary
### **1. CONTEXT_FLOW_ANALYSIS.md**
**Key Findings:**
- ✅ Analyzed 12 distinct user interaction flows
- 🔴 Identified critical issues:
- Chat history NOT sent to Writing mode
- Writing mode notes ignored (don't update plan)
- Block refinement missing context
- Direct writing mode cannot execute (no plan)
- ✅ Mapped all context storage mechanisms
- ✅ Provided recommendations for fixes
**Critical Issues to Fix:**
| Issue | Severity | Impact |
|-------|----------|--------|
| Chat history not sent to Writing mode | 🔴 Critical | AI loses conversation context |
| Writing mode notes ignored | 🔴 Critical | User instructions silently ignored |
| Block refinement missing context | 🟡 Medium | AI doesn't understand original intent |
| Direct writing mode fails | 🟡 Medium | Confusing UX, no error handling |
---
### **2. AGENTIC_CONTEXT_STRATEGY.md**
**Key Solutions:**
- ✅ AI-powered context summarization (not hardcoded)
- ✅ AI-powered intent detection (language-agnostic)
- ✅ Cost-effective (~$0.0001 per summarization)
- ✅ Seamless agentic UX (proactive suggestions)
- ✅ Works in all languages (Indonesian, Arabic, Chinese, etc.)
**Core Philosophy:**
> "If AI is smart enough to write articles, it's smart enough to manage its own context."
**New Actions:**
| Action | Purpose | Cost | When |
|--------|---------|------|------|
| `summarize_context` | Condense chat history | $0.0001 | Before outline (if chat > 6 msgs) |
| `detect_intent` | Understand user's next step | $0.00002 | After each user message |
---
## 🎯 Implementation Goals
### **Primary Objectives**
1. **Fix Context Loss Issues**
- Send chat history to ALL endpoints
- Include context in block refinement
- Handle writing mode properly
2. **Implement Agentic Context Management**
- AI-powered summarization
- AI-powered intent detection
- Language-agnostic (no hardcoded keywords)
3. **Enhance User Experience**
- Proactive action suggestions
- Seamless mode transitions
- Transparent context operations
4. **Maintain Cost Efficiency**
- Total added cost: ~$0.34/month for 100 articles
- 76% token reduction vs full history
- Track all costs transparently
---
## 📋 Implementation Phases
### **Phase 1: Critical Fixes** (Priority: 🔴 HIGH)
**Goal:** Fix context loss issues identified in CONTEXT_FLOW_ANALYSIS.md
#### **1.1 Send Chat History Everywhere**
**Files to Modify:**
- `assets/js/sidebar.js`
**Changes:**
```javascript
// In ALL API request payloads, add chatHistory
const basePayload = {
messages: messages,
postId: postId,
chatHistory: messages.filter(m => m.role !== 'system'), // ✅ Add this
postConfig: postConfig,
type: agentMode
};
// Apply to:
// - handleExecuteArticle() → /execute-article
// - handleRefineBlock() → /refine-block
// - handleGenerateMeta() → /generate-meta
// - Any other endpoints that don't currently send chatHistory
```
**Backend Files to Modify:**
- `includes/class-gutenberg-sidebar.php`
**Changes:**
```php
// In handle_execute_article()
$chat_history = $params['chatHistory'] ?? array();
if (!empty($chat_history)) {
$chat_history_context = $this->build_chat_history_context($chat_history);
// Append to system prompt
}
// In handle_refine_block()
$chat_history = $params['chatHistory'] ?? array();
$plan = get_post_meta($post_id, '_wpaw_plan', true);
// Include both in refinement context
// In handle_generate_meta()
$chat_history = $params['chatHistory'] ?? array();
// Include for better meta description context
```
**Testing:**
- [ ] Test Chat → Writing mode (verify context preserved)
- [ ] Test block refinement (verify original intent understood)
- [ ] Test meta generation (verify context used)
**Estimated Time:** 2-3 hours
---
#### **1.2 Handle Writing Mode Properly**
**Problem:** User can switch to Writing mode without a plan, then cannot execute.
**Solution:** Show clear guidance and prevent confusion.
**Files to Modify:**
- `assets/js/sidebar.js`
**Changes:**
```javascript
// In renderWritingMode()
const renderWritingModeContent = () => {
if (!currentPlan) {
return (
📝
No Outline Yet
Writing mode requires an outline to structure your article.
Or switch to to discuss your ideas.
);
}
// Normal writing mode UI...
};
// In handleExecuteArticle()
if (!currentPlan) {
showError('Please create an outline first. Switch to Planning mode.');
return;
}
```
**CSS to Add:**
- `assets/css/sidebar.css`
```css
.writing-mode-empty {
display: flex;
align-items: center;
justify-content: center;
min-height: 300px;
}
.empty-state {
text-align: center;
max-width: 400px;
padding: 2rem;
}
.empty-state .icon {
font-size: 3rem;
display: block;
margin-bottom: 1rem;
}
.empty-state h3 {
margin: 0 0 0.5rem 0;
font-size: 1.5rem;
}
.empty-state p {
color: #666;
margin: 0.5rem 0;
}
.empty-state .hint {
font-size: 0.9rem;
margin-top: 1rem;
}
```
**Testing:**
- [ ] Test switching to Writing mode without plan
- [ ] Verify clear guidance shown
- [ ] Test "Create Outline First" button
- [ ] Test switching back to Chat mode
**Estimated Time:** 1-2 hours
---
#### **1.3 Handle Writing Mode Notes**
**Problem:** User adds notes in Writing mode, but notes don't update the plan.
**Solution:** Either update plan or show clear warning.
**Recommended Approach:** Show warning (simpler, clearer UX)
**Files to Modify:**
- `assets/js/sidebar.js`
**Changes:**
```javascript
// In Writing mode, when user sends a message
const handleWritingModeMessage = async (userMessage) => {
// Show info message
addSystemMessage(
'💡 Note: To modify the outline, switch to Planning mode. ' +
'Writing mode messages are for discussion only.'
);
// Still send to chat endpoint for conversation
await sendChatMessage(userMessage);
};
// Add mode indicator in input area
const renderInputArea = () => {
return (
{agentMode === 'writing' && currentPlan && (
💬 Chat mode active. To modify outline, switch to Planning mode.
)}
);
};
```
**Alternative Approach (Advanced):** Auto-update plan
- Detect if message is requesting plan changes
- Send to `/update-plan` endpoint
- Regenerate plan with modifications
- More complex, implement in Phase 3
**Testing:**
- [ ] Test adding notes in Writing mode
- [ ] Verify warning shown
- [ ] Verify notes don't silently fail
**Estimated Time:** 1 hour
---
### **Phase 2: Agentic Infrastructure** (Priority: 🟡 MEDIUM)
**Goal:** Implement AI-powered context management from AGENTIC_CONTEXT_STRATEGY.md
#### **2.1 Backend: Add Summarization Endpoint**
**Files to Modify:**
- `includes/class-gutenberg-sidebar.php`
**New Endpoint:**
```php
/**
* Register summarize-context endpoint.
*/
register_rest_route(
'wp-agentic-writer/v1',
'/summarize-context',
array(
'methods' => 'POST',
'callback' => array($this, 'handle_summarize_context'),
'permission_callback' => array($this, 'check_permissions'),
)
);
/**
* Handle context summarization request.
*
* @param WP_REST_Request $request REST request.
* @return WP_REST_Response|WP_Error Response.
*/
public function handle_summarize_context($request) {
$params = $request->get_json_params();
$chat_history = $params['chatHistory'] ?? array();
$post_id = $params['postId'] ?? 0;
// Short history doesn't need summarization
if (empty($chat_history) || count($chat_history) < 4) {
return new WP_REST_Response(
array(
'summary' => '',
'use_full_history' => true,
'cost' => 0,
),
200
);
}
// Build history text
$history_text = '';
foreach ($chat_history as $msg) {
$role = ucfirst($msg['role'] ?? 'Unknown');
$content = $msg['content'] ?? '';
$history_text .= "{$role}: {$content}\n\n";
}
// Build summarization prompt
$prompt = "Summarize this conversation into key points that capture the user's intent and requirements.
Focus on:
- Main topic
- Specific focus areas
- Rejected/excluded topics
- User preferences (tone, audience, etc.)
Keep the summary concise (max 200 words) but preserve critical context.
Write in the same language as the conversation.
Output format:
TOPIC: [main topic]
FOCUS: [what to include]
EXCLUDE: [what to avoid]
PREFERENCES: [any specific requirements]
Conversation:
{$history_text}";
// Call AI with cheap model
$provider = WP_Agentic_Writer_OpenRouter_Provider::get_instance();
$messages = array(
array(
'role' => 'user',
'content' => $prompt,
),
);
$response = $provider->chat($messages, array(), 'summarize');
if (is_wp_error($response)) {
return $response;
}
// Track cost
do_action(
'wp_aw_after_api_request',
$post_id,
$response['model'] ?? '',
'summarize_context',
$response['input_tokens'] ?? 0,
$response['output_tokens'] ?? 0,
$response['cost'] ?? 0
);
return new WP_REST_Response(
array(
'summary' => $response['content'] ?? '',
'use_full_history' => false,
'cost' => $response['cost'] ?? 0,
'tokens_saved' => count($chat_history) * 500 - ($response['output_tokens'] ?? 0),
),
200
);
}
```
**Testing:**
- [ ] Test with short history (< 4 messages) → returns use_full_history
- [ ] Test with long history (> 6 messages) → returns summary
- [ ] Test in multiple languages (English, Indonesian)
- [ ] Verify cost tracking
**Estimated Time:** 2-3 hours
---
#### **2.2 Backend: Add Intent Detection Endpoint**
**Files to Modify:**
- `includes/class-gutenberg-sidebar.php`
**New Endpoint:**
```php
/**
* Register detect-intent endpoint.
*/
register_rest_route(
'wp-agentic-writer/v1',
'/detect-intent',
array(
'methods' => 'POST',
'callback' => array($this, 'handle_detect_intent'),
'permission_callback' => array($this, 'check_permissions'),
)
);
/**
* Handle intent detection request.
*
* @param WP_REST_Request $request REST request.
* @return WP_REST_Response|WP_Error Response.
*/
public function handle_detect_intent($request) {
$params = $request->get_json_params();
$last_message = $params['lastMessage'] ?? '';
$has_plan = $params['hasPlan'] ?? false;
$current_mode = $params['currentMode'] ?? 'chat';
$post_id = $params['postId'] ?? 0;
if (empty($last_message)) {
return new WP_REST_Response(
array('intent' => 'continue_chat'),
200
);
}
// Build intent detection prompt
$prompt = "Based on the user's message, determine their intent. Choose ONE:
1. \"create_outline\" - User wants to create an article outline/structure
2. \"start_writing\" - User wants to write the full article
3. \"refine_content\" - User wants to improve existing content
4. \"continue_chat\" - User wants to continue discussing/exploring
5. \"clarify\" - User is asking questions or needs clarification
Consider:
- The user's explicit request
- Whether they have an outline already (has_plan: " . ($has_plan ? 'true' : 'false') . ")
- Current mode (current_mode: {$current_mode})
User's message: \"{$last_message}\"
Respond with ONLY the intent code (e.g., \"create_outline\"). No explanation.";
// Call AI with cheap model
$provider = WP_Agentic_Writer_OpenRouter_Provider::get_instance();
$messages = array(
array(
'role' => 'user',
'content' => $prompt,
),
);
$response = $provider->chat($messages, array(), 'intent_detection');
if (is_wp_error($response)) {
return $response;
}
// Track cost
do_action(
'wp_aw_after_api_request',
$post_id,
$response['model'] ?? '',
'detect_intent',
$response['input_tokens'] ?? 0,
$response['output_tokens'] ?? 0,
$response['cost'] ?? 0
);
// Clean up response
$intent = trim(strtolower($response['content'] ?? 'continue_chat'));
$intent = str_replace('"', '', $intent); // Remove quotes if present
// Validate intent
$valid_intents = array('create_outline', 'start_writing', 'refine_content', 'continue_chat', 'clarify');
if (!in_array($intent, $valid_intents)) {
$intent = 'continue_chat';
}
return new WP_REST_Response(
array(
'intent' => $intent,
'cost' => $response['cost'] ?? 0,
),
200
);
}
```
**Testing:**
- [ ] Test with "create outline" messages (various languages)
- [ ] Test with "write article" messages
- [ ] Test with questions/clarifications
- [ ] Verify correct intent returned
- [ ] Verify cost tracking
**Estimated Time:** 2-3 hours
---
#### **2.3 Backend: Update Cost Tracking**
**Files to Modify:**
- `includes/class-cost-tracker.php`
**Changes:**
```php
// Add new operation types
private function get_operation_label($operation) {
$labels = array(
'chat' => 'Chat',
'planning' => 'Planning',
'execution' => 'Article Writing',
'refinement' => 'Block Refinement',
'meta_description' => 'Meta Description',
'keyword_suggestion' => 'Keyword Suggestion',
'web_search' => 'Web Search',
'summarize_context' => 'Context Summarization', // ✅ New
'detect_intent' => 'Intent Detection', // ✅ New
);
return $labels[$operation] ?? ucfirst($operation);
}
```
**Testing:**
- [ ] Verify new operations tracked in cost table
- [ ] Verify cost breakdown shows summarization/intent costs
- [ ] Test cost report includes new operations
**Estimated Time:** 30 minutes
---
#### **2.4 Frontend: Implement Summarization**
**Files to Modify:**
- `assets/js/sidebar.js`
**New Functions:**
```javascript
/**
* Summarize chat history using AI.
*
* @param {Array} chatHistory - Full chat history.
* @returns {Promise