Cognitive Process Emulator for Gemini | 认知过程模拟器
Transform Gemini into a "Backtracking Cognitive Simulator" through Q1-Q4 Cognitive Meta-Architecture
git clone https://github.com/abwoo/LearnThinkingChain.git
cd LearnThinkingChain
npm install
npm run build:extension
npm run build:web- Open Chrome and navigate to
chrome://extensions/ - Enable "Developer mode" (toggle in top-right)
- Click "Load unpacked"
- Select the
dist/extensionfolder
npm run build:webDashboard output will be in dist/web.
- Visit Gemini
- Look for the ⚡ THINKING CHAIN floating panel (top-right)
- Toggle the switch to ON
- Select your preferred cognitive protocol:
- Novice Backtracker: Peer learning perspective
- Socratic Guide: Question-based guidance
- First Principles: Atomic truth reduction
- Analogy Weaver: Analogical reasoning
The Thinking Chain Hub appears as a floating panel in Gemini's interface:
- Toggle Switch: Activate/deactivate the cognitive framework
- Protocol Selector: Choose your cognitive mode
- Status Indicator: Shows system health and connection status
- Type your question in Gemini's input box
- Press Enter or click Send
- The extension intercepts your input at the capture phase
- Your prompt is enhanced with cognitive scaffolding:
- Q1: Blind Spot identification
- Q2: Entropy path exploration
- Q3: Deep backtracking
- Q4: Cognitive handover
- Gemini receives the enhanced prompt and responds accordingly
- Blue Glow: Extension is active and processing
- Red Indicator: Error detected (check console)
- Green Status: All systems operational
LearnThinkingChain implements a recursive search pattern that transforms linear problem-solving into a backtracking loop:
User Input
↓
Q1: Novice Emulator (ZPD Perspective)
↓
Q2: Path Branching
├─→ Common Pitfall Path (intuitive but wrong)
└─→ First Principles Path (correct but requires backtracking)
↓
Q3: Recursive Backtracking
└─→ Identify pivot point where paths diverge
↓
Q4: Cognitive Handover
└─→ Provide direction, stop before answer, ask open question
The system enforces first-principles thinking by:
- Stripping Analogies: Remove surface-level comparisons
- Identifying Atomic Truths: Break down to fundamental definitions
- Rebuilding Logic Chain: Construct solution from axioms
- Validating Each Step: Verify against boundary conditions
The system dynamically adjusts complexity based on:
- Knowledge Debt: High debt → Lower complexity
- Weak Points: Frequent failures → More scaffolding
- Preferred Heuristics: Visual/Analytical/Analogical → Tailored approach
The RequestInterceptor hijacks React events using capture phase interception:
// Event listener with capture flag (true = capture phase)document.addEventListener('keydown',handler,true);// Stop all subsequent handlersevent.stopImmediatePropagation();event.stopPropagation();event.preventDefault();// Process through middlewareconstprocessed=awaitPromptMiddleware.process(input);// Re-dispatch event with processed valueelement.dispatchEvent(syntheticEvent);Key Selectors (updated for latest Gemini DOM):
inputSelectors: ['div[contenteditable="true"][data-lexical-editor="true"]','div[contenteditable="true"][role="textbox"]','div[contenteditable="true"]','textarea[aria-label*="message"]','textarea[aria-label*="消息"]']
submitSelectors: ['button[aria-label*="Send"]','button[aria-label*="发送"]','button[data-testid="send-button"]']interfaceUserCognitiveProfile{// Weak Points: Topic → Failure FrequencyweakPoints: Map<string,number>;// Preferred Learning StylepreferredHeuristics: 'visual'|'analytical'|'analogical';// Session HistorysessionLogs: Array<{timestamp: number;logicBridgeUsed: string;promptText: string;responseLength: number;skillsDetected: string[];}>;// Knowledge Debt: Concept → Debt ScoreknowledgeDebt: Map<string,number>;// MetadatalastUpdated: number;totalSessions: number;averageResponseTime: number;}Storage Location: chrome.storage.local['ltc_cognitive_profile']
The system prompt template can be customized for different learning subjects:
constmathTemplate={q1_blind_spot: "Identify the most tempting formula or shortcut",q2_entropy: "Follow the intuitive calculation, show where it breaks",q3_backtrack: "Return to fundamental definitions (e.g., limit, derivative)",q4_handover: "Ask: 'What happens if we change this variable?'"};constcodeTemplate={q1_blind_spot: "Identify the surface-level syntax that misleads",q2_entropy: "Write the naive solution, show the edge case failure",q3_backtrack: "Return to data structures and algorithm fundamentals",q4_handover: "Ask: 'How would you optimize this for scale?'"};constphilosophyTemplate={q1_blind_spot: "Identify the common-sense assumption",q2_entropy: "Follow the intuitive argument, reveal the logical gap",q3_backtrack: "Return to first principles (definitions, axioms)",q4_handover: "Ask: 'What would a counter-argument look like?'"};Modification Location: src/content/main.ts → getDefaultProtocols()
The extension uses a multi-layer messaging architecture:
// Content Script → Backgroundchrome.runtime.sendMessage({type: 'STATE_UPDATE',payload: {isActive: true,mode: 'novice'}});// Background → Content Scriptchrome.runtime.onMessage.addListener((message,sender,sendResponse)=>{if(message.type==='PROFILE_UPDATE'){updateProfile(message.payload);}});// Background → Dashboard (via chrome.runtime.sendMessage)chrome.runtime.sendMessage({type: 'STATE_PUSH',payload: {active: true,mode: 'novice',latestResponse: { ... }}});// Dashboard listens via chrome.runtime.onMessagechrome.runtime.onMessage.addListener((message)=>{if(message.type==='STATE_PUSH'){updateDashboard(message.payload);}});// Any component can listen to storage changeschrome.storage.onChanged.addListener((changes,areaName)=>{if(changes.ltc_active){// React to active state change}if(changes.ltc_profile){// React to profile update}});User Action (Gemini Page)
↓
Content Script (RequestInterceptor)
↓
PromptMiddleware (Core Engine)
↓
CognitiveBridge (Knowledge Analysis)
↓
CognitiveProfileService (Storage)
↓
Background Script (State Sync)
↓
Dashboard (Real-time Display)
1. Check if extension is active
├─→ Toggle switch ON? → Yes → Continue
└─→ No → Turn ON and retry
2. Check DOM selectors
├─→ Open DevTools → Console
├─→ Run: document.querySelector('div[contenteditable="true"]')
└─→ If null → Gemini updated DOM structure
└─→ Update selectors in src/content/main.ts
3. Check for errors
├─→ Open DevTools → Console
├─→ Look for "RequestInterceptor" errors
└─→ Check chrome://extensions/ → Errors section
4. Verify event interception
├─→ Add breakpoint in RequestInterceptor.onKeydownCapture
└─→ Press Enter → Should hit breakpoint
1. Check storage quota
├─→ chrome.storage.local.getBytesInUse(null, console.log)
└─→ If > 90% → Clear old logs/errors
2. Verify storage listeners
├─→ Check chrome.storage.onChanged listeners are registered
└─→ Test: chrome.storage.local.set({ ltc_active: true })
3. Check message channels
├─→ Verify chrome.runtime.sendMessage is working
└─→ Check background script is running (chrome://extensions/)
1. Check ShadowHost mounting
├─→ Verify shadowHost.mount() was called
└─→ Check console for "ShadowHost: Mounted successfully"
2. Check CSS isolation
├─→ Inspect shadow root in DevTools
├─→ Verify styles are injected
└─→ Check for host CSS interference
3. Check z-index conflicts
├─→ Verify shadow host z-index: 999999
└─→ Check Gemini's UI z-index values
1. Check CognitiveFeedbackLoop
├─→ Verify response DOM is being analyzed
└─→ Check console for "CognitiveFeedbackLoop: Analysis complete"
2. Check storage permissions
├─→ Verify "storage" permission in manifest.json
└─→ Check chrome.storage.local.set() is not throwing errors
3. Check profile service
├─→ Verify CognitiveProfileService.save() is called
└─→ Check chrome.storage.local.get('ltc_cognitive_profile')
| Error Code | Meaning | Solution |
|---|---|---|
DOM_SELECTION_FAILED | Input element not found | Update selectors or wait for page load |
STORAGE_QUOTA_EXCEEDED | Storage limit reached | Clear old data via GlobalErrorHandler |
CIRCUIT_BREAKER_OPEN | Too many failures | Check console for root cause, wait 30s |
SHADOW_DOM_MOUNT_FAILED | Shadow root creation failed | Check DOM readiness, verify permissions |
// In Chrome DevTools Console (on Gemini page)// Check extension statechrome.storage.local.get(['ltc_active','ltc_mode'],console.log);// View cognitive profilechrome.storage.local.get('ltc_cognitive_profile',console.log);// View recent errorschrome.storage.local.get('ltc_global_errors',console.log);// View logschrome.storage.local.get('ltc_logs',console.log);// Clear all data (reset)chrome.storage.local.clear();// Check input elementdocument.querySelector('div[contenteditable="true"]');// Check if interceptor is active// (Add breakpoint in RequestInterceptor.start())- ARCHITECTURE.md - Detailed architecture documentation
- PRODUCTION_GUIDE.md - Production deployment guide
- CONTRIBUTING.md - Contribution guidelines
- IMPLEMENTATION_COMPLETE.md - Implementation status
- GitHub Repository: https://github.com/abwoo/LearnThinkingChain
- Cloud Dashboard: https://abwoo.github.io/LearnThinkingChain/
- Issues: https://github.com/abwoo/LearnThinkingChain/issues
ISC License - See LICENSE file for details.
Built with ❤️ for Cognitive Enhancement
Last Updated: 2026-01-28