Conversation
When users ask about specific entities like Saino Cafe, the RAG search now prioritizes similarity scores over importance levels to ensure the most relevant results appear first. This fixes the issue where Engineer Cafe results (0.48 similarity) were ranking higher than Saino Cafe results (0.79 similarity) for Saino-specific queries. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Remove square bracket tags [Tag Name] from RAG search results - Add explicit instructions to prompts to avoid including tags in responses - Post-process responses to remove any leaked tags - Add response length check for specific requests (max 150 chars) - Extract key information if response is too long for specific requests - Ensure operating hours queries return only the requested information - Clean up both single-language and multi-language search formatting This fixes the issue where the system was returning entire knowledge base entries with tags instead of just the specific information requested (e.g., operating hours). 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Add sessionId parameter to EnhancedQAAgent.answerQuestion method - Pass sessionId from API route to agent for proper memory association - Store sessionId with each message in SimplifiedMemorySystem - Add comprehensive debug logging to track memory storage and retrieval - Ensure requestType metadata is preserved in conversation memory This fixes the issue where the agent couldn't remember previous questions when users provided clarifying responses (e.g., "才能の方で" after asking about cafe hours). 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
## STT Correction System - Add automatic speech-to-text correction for common misrecognitions - Implement context-aware corrections for "カフェ" vs "壁" confusion - Add monitoring system to track correction patterns - Include test scripts and database migration ## Documentation Updates - Update README.md with latest features including STT corrections, monitoring, and CRON jobs - Enhance CLAUDE.md with SimplifiedMemorySystem improvements and recent fixes - Update all docs/ files with current implementation status - Add production monitoring and automated update documentation ## Code Improvements - Enhance memory system with sessionId tracking - Fix conversation context retrieval for follow-up questions - Add specific request type extraction and tracking - Improve response precision for contextual questions ## Cleanup - Remove obsolete test result files - Remove historical RAG fix documentation - Clean up outdated implementation logs This comprehensive update brings all documentation in line with the current state of the project and adds critical STT correction functionality to improve user experience. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Fix date in README.md from 2025/01/30 to 2025/06/30 - Update README-EN.md with all latest features: - STT correction system for Japanese misrecognition - Enhanced memory system with SimplifiedMemorySystem - Response precision improvements - Production monitoring features - CRON job documentation - Complete audio system refactoring details - All new development commands - Updated project structure - STT misrecognition troubleshooting - Updated performance metrics - Ensure both Japanese and English documentation are in sync 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
- Fix module not found error by updating import from './supabase-client' to './supabase' - Resolves build error preventing API routes from loading 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
Walkthroughこの変更は、音声認識(STT)補正システムの導入・強化、会話メモリシステムのセッションID管理やリクエストタイプ判定の改善、AIエージェントの回答精度向上、監視・分析基盤の拡充、関連ドキュメント・テスト・スクリプトの追加・修正を含む大規模なアップデートです。コード・ドキュメント・SQL・テスト全体にわたり反映されています。 Changes
Sequence Diagram(s)STT補正システム & QAエージェント連携sequenceDiagram
participant User
participant GoogleCloudVoiceSimple
participant STT Corrections
participant EnhancedQAAgent
participant SimplifiedMemorySystem
participant Supabase
User->>GoogleCloudVoiceSimple: 音声入力
GoogleCloudVoiceSimple->>GoogleCloudVoiceSimple: Google STTで文字起こし
GoogleCloudVoiceSimple->>STT Corrections: applySttCorrections(transcript)
STT Corrections-->>GoogleCloudVoiceSimple: 補正済みテキスト・信頼度
GoogleCloudVoiceSimple->>EnhancedQAAgent: 補正済みテキスト
EnhancedQAAgent->>EnhancedQAAgent: リクエストタイプ抽出・履歴参照
EnhancedQAAgent->>SimplifiedMemorySystem: メッセージ保存(sessionId, requestType)
EnhancedQAAgent->>Supabase: ナレッジ検索・履歴取得
EnhancedQAAgent->>User: 精密化された回答を返却
STT補正ログ・監視sequenceDiagram
participant STT Corrections
participant SttCorrectionMonitor
participant Supabase
STT Corrections->>SttCorrectionMonitor: logCorrection(補正イベント)
SttCorrectionMonitor->>SttCorrectionMonitor: バッファに蓄積
Note over SttCorrectionMonitor: 10件または1分ごとに
SttCorrectionMonitor->>Supabase: stt_correction_logsへバッチ書き込み
Possibly related PRs
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
src/mastra/agents/enhanced-qa-agent.tsOops! Something went wrong! :( ESLint: 9.27.0 ESLint couldn't find an eslint.config.(js|mjs|cjs) file. From ESLint v9.0.0, the default configuration file is now eslint.config.js. https://eslint.org/docs/latest/use/configure/migration-guide If you still have problems after following the migration guide, please stop by src/lib/shared-memory-service.tsOops! Something went wrong! :( ESLint: 9.27.0 ESLint couldn't find an eslint.config.(js|mjs|cjs) file. From ESLint v9.0.0, the default configuration file is now eslint.config.js. https://eslint.org/docs/latest/use/configure/migration-guide If you still have problems after following the migration guide, please stop by src/mastra/agents/realtime-agent.tsOops! Something went wrong! :( ESLint: 9.27.0 ESLint couldn't find an eslint.config.(js|mjs|cjs) file. From ESLint v9.0.0, the default configuration file is now eslint.config.js. https://eslint.org/docs/latest/use/configure/migration-guide If you still have problems after following the migration guide, please stop by
✨ Finishing Touches
🧪 Generate Unit Tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 7
🧹 Nitpick comments (7)
src/app/api/qa/route.ts (1)
62-62: sessionIdパラメータの追加とswitch文の改善sessionIdパラメータの追加により、セッション認識機能が強化されました。ただし、静的解析ツールが指摘するswitch文内での変数宣言の問題を修正することをお勧めします。
以下の修正を適用してswitch文の安全性を向上させてください:
case 'ask_question': + { if (!question) { return NextResponse.json( { error: 'Question text required' }, { status: 400 } ); } // Set language if provided if (language) { await qaAgent.memory.store('language', language); } const answer = await qaAgent.answerQuestion(question, language, sessionId); const category = await qaAgent.categorizeQuestion(question); // Convert answer to speech const voiceService = navigator.getTool('voiceService'); let audioResponse = null; if (voiceService) { const currentLanguage = await qaAgent.memory.get('language') || 'ja'; const audioBuffer = await voiceService.textToSpeech(answer, { language: currentLanguage }); audioResponse = Buffer.from(audioBuffer).toString('base64'); } // Log the interaction const externalTool = navigator.getTool('externalApi'); if (externalTool && sessionId) { await externalTool.execute({ action: 'logVisitorActivity', data: { sessionId, activity: 'qa_interaction', details: { question, answer, category, timestamp: new Date().toISOString(), }, }, }); } return NextResponse.json({ success: true, answer, category, audioResponse, hasAudio: !!audioResponse, }); + }src/mastra/tools/rag-search.ts (1)
71-84: 特定クエリ検出のハードコード値を設定可能にすることを検討してください特定クエリの判定条件("saino", "才能", "併設")と類似度差の閾値(0.2)がハードコードされています。これらの値を設定可能にすることで、より柔軟な調整が可能になります。
以下のように設定値として外部化することを提案します:
+// Configuration for specific query handling +const SPECIFIC_QUERY_KEYWORDS = ['saino', '才能', '併設']; +const SIMILARITY_THRESHOLD_DIFF = 0.2; + // Check if this is a specific query (e.g., Saino Cafe) - const isSpecificQuery = query.toLowerCase().includes('saino') || - query.toLowerCase().includes('才能') || - query.toLowerCase().includes('併設'); + const isSpecificQuery = SPECIFIC_QUERY_KEYWORDS.some(keyword => + query.toLowerCase().includes(keyword.toLowerCase())); const sorted = results.sort((a,b)=>{ // For specific queries, prioritize similarity over importance if (isSpecificQuery) { // If similarity difference is significant (>0.2), use similarity const simDiff = b.similarity - a.similarity; - if (Math.abs(simDiff) > 0.2) { + if (Math.abs(simDiff) > SIMILARITY_THRESHOLD_DIFF) { return simDiff; } }scripts/test-stt-corrections.ts (1)
38-59: テスト実行とレポート機能の品質向上を提案します現在のテスト実行ロジックは基本的な検証を行っていますが、以下の改善を検討してください:
for (const testCase of testCases) { const result = applySttCorrections(testCase.input); const isCorrect = result === testCase.expected; + const executionTime = performance.now(); + const finalTime = performance.now() - executionTime; if (isCorrect) { passed++; console.log(`✅ PASS`); } else { failed++; console.log(`❌ FAIL`); } console.log(` Input: "${testCase.input}"`); console.log(` Expected: "${testCase.expected}"`); console.log(` Got: "${result}"`); + console.log(` Time: ${finalTime.toFixed(2)}ms`); if (likelyContainsMisrecognition(testCase.input)) { console.log(` ⚠️ Likely contains misrecognition`); }docs/STATUS.md (1)
61-61: 環境変数リストの文法を修正してください静的解析ツールが指摘する通り、連続するカンマが存在します。
✅ Core functionality: - `GOOGLE_CLOUD_PROJECT_ID`, `GOOGLE_CLOUD_CREDENTIALS`, `GOOGLE_GENERATIVE_AI_API_KEY` -- `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY` +- `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY` - `OPENAI_API_KEY` - For embeddings (1536 dimensions)src/lib/stt-correction-monitor.ts (1)
19-24: 静的クラス設計の再考を提案静的解析ツールが指摘している通り、すべてのメンバーが静的なクラスよりも、モジュールレベルの関数を使用する方が適切かもしれません。特にテスタビリティと依存性注入の観点から改善の余地があります。
-export class SttCorrectionMonitor { - private static corrections: CorrectionEvent[] = []; - private static readonly BATCH_SIZE = 10; - private static readonly FLUSH_INTERVAL = 60000; - private static flushTimer: NodeJS.Timeout | null = null; +// モジュールレベルの実装への変更を検討 +let corrections: CorrectionEvent[] = []; +const BATCH_SIZE = 10; +const FLUSH_INTERVAL = 60000; +let flushTimer: NodeJS.Timeout | null = null; +export const SttCorrectionMonitor = { + logCorrection, + getStats, + shutdown +} as const;src/utils/stt-corrections.ts (1)
82-108: 補正ルール適用ロジックの改善を提案します。現在の実装は基本的には正しいですが、補正の順序や重複適用の防止について改善の余地があります。
// Apply each correction rule for (const rule of CORRECTION_RULES) { + // Skip if pattern doesn't match to avoid unnecessary regex operations + if (!rule.pattern.test(corrected)) { + continue; + } + // Check if context is required and matches if (rule.context) { if (!rule.context.test(corrected)) { continue; // Skip this rule if context doesn't match } } - // Check if the pattern matches - if (rule.pattern.test(corrected)) { const before = corrected; corrected = corrected.replace(rule.pattern, rule.replacement); if (before !== corrected) { corrections.push(rule.description); + // Reset pattern to ensure we reprocess the text for other rules + rule.pattern.lastIndex = 0; } - } }docs/API.md (1)
689-689: タイポの修正が必要です。
"embedingModel"は"embeddingModel"であるべきです。- "embedingModel": "text-embedding-004", + "embeddingModel": "text-embedding-004",
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (25)
CLAUDE.md(7 hunks)README-EN.md(10 hunks)README.md(6 hunks)_docs/blog/2025-06-29_AIアシスタントが空気を読めるようになった話〜会話の文脈を理解してピンポイントで答える技術〜.md(1 hunks)docs/API-ja.md(3 hunks)docs/API.md(6 hunks)docs/DEPLOYMENT.md(5 hunks)docs/DEVELOPMENT.md(6 hunks)docs/STATUS.md(7 hunks)docs/rag-fix-completed.md(0 hunks)docs/rag-improvement-action-summary.md(0 hunks)package.json(1 hunks)scripts/create-stt-correction-logs-table.sql(1 hunks)scripts/test-stt-corrections.ts(1 hunks)src/app/api/qa/route.ts(1 hunks)src/lib/simplified-memory.ts(6 hunks)src/lib/stt-correction-monitor.ts(1 hunks)src/mastra/agents/enhanced-qa-agent.ts(12 hunks)src/mastra/agents/realtime-agent.ts(2 hunks)src/mastra/tools/rag-search.ts(3 hunks)src/mastra/voice/google-cloud-voice-simple.ts(2 hunks)src/test/source-prioritization-test-results.md(0 hunks)src/test/test-memory-storage.ts(1 hunks)src/test/test-summary.md(0 hunks)src/utils/stt-corrections.ts(1 hunks)
💤 Files with no reviewable changes (4)
- docs/rag-fix-completed.md
- src/test/source-prioritization-test-results.md
- src/test/test-summary.md
- docs/rag-improvement-action-summary.md
🧰 Additional context used
🧠 Learnings (16)
package.json (2)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Always use Tailwind CSS v3.4.17, postcss@8.4.47, and autoprefixer@10.4.20; do not upgrade to Tailwind CSS v4 due to breaking changes and incompatibility.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: PostCSS configuration must use 'tailwindcss: {}' instead of '@tailwindcss/postcss: {}'.
src/mastra/tools/rag-search.ts (1)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The RAG system supports multi-language knowledge base and cross-language search, using Google text-embedding-004 (768d, padded to 1536) as primary and OpenAI text-embedding-3-small (1536d) as fallback.
src/test/test-memory-storage.ts (2)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
docs/DEVELOPMENT.md (2)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
docs/STATUS.md (7)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Always use Tailwind CSS v3.4.17, postcss@8.4.47, and autoprefixer@10.4.20; do not upgrade to Tailwind CSS v4 due to breaking changes and incompatibility.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Automated CRON jobs update the knowledge base and slides every 6 hours, secured by a CRON_SECRET, with error recovery and retry logic.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: All admin and management interfaces (e.g., knowledge base, categories, metadata templates) are accessible via dedicated API endpoints and require proper authentication.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Monitoring and alerting are implemented via real-time dashboards and webhook endpoints, tracking RAG performance, cache efficiency, API usage, and error rates.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The RAG system supports multi-language knowledge base and cross-language search, using Google text-embedding-004 (768d, padded to 1536) as primary and OpenAI text-embedding-3-small (1536d) as fallback.
_docs/blog/2025-06-29_AIアシスタントが空気を読めるようになった話〜会話の文脈を理解してピンポイントで答える技術〜.md (3)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The RAG system supports multi-language knowledge base and cross-language search, using Google text-embedding-004 (768d, padded to 1536) as primary and OpenAI text-embedding-3-small (1536d) as fallback.
src/mastra/agents/realtime-agent.ts (1)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
src/lib/simplified-memory.ts (2)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
scripts/create-stt-correction-logs-table.sql (1)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: All database tables must have Row Level Security (RLS) enabled, with service role access for secure operations.
README.md (5)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Audio playback must use Web Audio API as primary, with HTMLAudioElement as fallback, and include device-specific optimizations for iOS/Android.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The RAG system supports multi-language knowledge base and cross-language search, using Google text-embedding-004 (768d, padded to 1536) as primary and OpenAI text-embedding-3-small (1536d) as fallback.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Automated CRON jobs update the knowledge base and slides every 6 hours, secured by a CRON_SECRET, with error recovery and retry logic.
README-EN.md (10)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Audio playback must use Web Audio API as primary, with HTMLAudioElement as fallback, and include device-specific optimizations for iOS/Android.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Lip-sync analysis uses optimized frequency band analysis (O(n)), not heavy FFT, and includes caching with hybrid memory/localStorage and auto-cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: For iPad/iOS Safari, always initialize AudioContext after explicit user interaction and provide fallback to audio-only mode if lip-sync fails.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The AudioPlaybackService provides a unified API for all audio playback, supporting optional lip-sync and consistent error handling.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Automated CRON jobs update the knowledge base and slides every 6 hours, secured by a CRON_SECRET, with error recovery and retry logic.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Monitoring and alerting are implemented via real-time dashboards and webhook endpoints, tracking RAG performance, cache efficiency, API usage, and error rates.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: All admin and management interfaces (e.g., knowledge base, categories, metadata templates) are accessible via dedicated API endpoints and require proper authentication.
docs/DEPLOYMENT.md (5)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Automated CRON jobs update the knowledge base and slides every 6 hours, secured by a CRON_SECRET, with error recovery and retry logic.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Monitoring and alerting are implemented via real-time dashboards and webhook endpoints, tracking RAG performance, cache efficiency, API usage, and error rates.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: For iPad/iOS Safari, always initialize AudioContext after explicit user interaction and provide fallback to audio-only mode if lip-sync fails.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Audio playback must use Web Audio API as primary, with HTMLAudioElement as fallback, and include device-specific optimizations for iOS/Android.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: AudioContext initialization should be deferred until the first user interaction to comply with mobile browser autoplay policies.
docs/API-ja.md (4)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Automated CRON jobs update the knowledge base and slides every 6 hours, secured by a CRON_SECRET, with error recovery and retry logic.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The RAG system supports multi-language knowledge base and cross-language search, using Google text-embedding-004 (768d, padded to 1536) as primary and OpenAI text-embedding-3-small (1536d) as fallback.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: All admin and management interfaces (e.g., knowledge base, categories, metadata templates) are accessible via dedicated API endpoints and require proper authentication.
docs/API.md (7)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Automated CRON jobs update the knowledge base and slides every 6 hours, secured by a CRON_SECRET, with error recovery and retry logic.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: All admin and management interfaces (e.g., knowledge base, categories, metadata templates) are accessible via dedicated API endpoints and require proper authentication.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The RAG system supports multi-language knowledge base and cross-language search, using Google text-embedding-004 (768d, padded to 1536) as primary and OpenAI text-embedding-3-small (1536d) as fallback.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Monitoring and alerting are implemented via real-time dashboards and webhook endpoints, tracking RAG performance, cache efficiency, API usage, and error rates.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
CLAUDE.md (9)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Always use Tailwind CSS v3.4.17, postcss@8.4.47, and autoprefixer@10.4.20; do not upgrade to Tailwind CSS v4 due to breaking changes and incompatibility.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: PostCSS configuration must use 'tailwindcss: {}' instead of '@tailwindcss/postcss: {}'.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Automated CRON jobs update the knowledge base and slides every 6 hours, secured by a CRON_SECRET, with error recovery and retry logic.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The RAG system supports multi-language knowledge base and cross-language search, using Google text-embedding-004 (768d, padded to 1536) as primary and OpenAI text-embedding-3-small (1536d) as fallback.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Monitoring and alerting are implemented via real-time dashboards and webhook endpoints, tracking RAG performance, cache efficiency, API usage, and error rates.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: All admin and management interfaces (e.g., knowledge base, categories, metadata templates) are accessible via dedicated API endpoints and require proper authentication.
src/mastra/agents/enhanced-qa-agent.ts (3)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The EnhancedQAAgent uses detectSpecificRequest() to identify specific user requests and limits responses to essential information, prioritizing precision over completeness.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
🧬 Code Graph Analysis (7)
src/mastra/voice/google-cloud-voice-simple.ts (1)
src/utils/stt-corrections.ts (2)
applySttCorrections(82-128)adjustConfidenceAfterCorrection(157-170)
scripts/test-stt-corrections.ts (1)
src/utils/stt-corrections.ts (3)
applySttCorrections(82-128)likelyContainsMisrecognition(135-147)CORRECTION_RULES(17-73)
src/test/test-memory-storage.ts (2)
src/lib/simplified-memory.ts (1)
SimplifiedMemorySystem(14-457)src/lib/supabase.ts (1)
supabaseAdmin(78-82)
src/mastra/agents/realtime-agent.ts (1)
src/utils/stt-corrections.ts (1)
applySttCorrections(82-128)
src/lib/stt-correction-monitor.ts (1)
src/lib/supabase.ts (1)
supabaseAdmin(78-82)
src/lib/simplified-memory.ts (1)
src/lib/supabase.ts (1)
supabaseAdmin(78-82)
src/utils/stt-corrections.ts (1)
src/lib/stt-correction-monitor.ts (1)
SttCorrectionMonitor(19-196)
🪛 Biome (1.9.4)
src/app/api/qa/route.ts
[error] 62-62: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
src/lib/stt-correction-monitor.ts
[error] 19-196: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
[error] 47-47: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 59-59: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 59-59: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 60-60: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 63-63: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 71-71: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 73-73: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 74-74: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 75-75: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 82-82: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 85-85: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 86-86: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 87-87: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 91-91: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 92-92: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 110-110: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 117-117: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 190-190: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 191-191: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 192-192: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 194-194: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
🪛 LanguageTool
docs/STATUS.md
[typographical] ~61-~61: Two consecutive commas
Context: ...ROJECT_ID, GOOGLE_CLOUD_CREDENTIALS, GOOGLE_GENERATIVE_AI_API_KEY-NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY, SUPAB...
(DOUBLE_PUNCTUATION)
[uncategorized] ~193-~193: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...dardize environment variable usage ### Medium Priority 1. Implement Web Speech API for cost re...
(EN_COMPOUND_ADJECTIVE_INTERNAL)
[uncategorized] ~199-~199: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...t compatibility (iOS audio issues) ### Low Priority 1. Implement facial expression detectio...
(EN_COMPOUND_ADJECTIVE_INTERNAL)
README-EN.md
[misspelling] ~34-~34: This word is normally spelled as one.
Context: ... Japanese speech-to-text misrecognition auto-correction (営業時間/料金/場所 etc.) - **🎯 Response Preci...
(EN_COMPOUNDS_AUTO_CORRECTION)
[typographical] ~476-~476: If specifying a range, consider using an en dash instead of a hyphen.
Context: ...sync Cache System - First Analysis: 1-3 seconds (optimized algorithms, down fro...
(HYPHEN_TO_EN)
docs/API.md
[uncategorized] ~35-~35: The preposition ‘to’ seems more likely in this position.
Context: ....client3. Download JSON key and place at./config/service-account-key.json` 4. ...
(AI_HYDRA_LEO_REPLACE_AT_TO)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Cursor BugBot
🔇 Additional comments (61)
package.json (1)
76-76: 開発依存関係の追加を承認新しい監視・ログ機能のためのnode-fetchの追加は適切です。
src/lib/simplified-memory.ts (4)
37-37: メタデータにrequestTypeフィールドを追加コンテキスト追跡のためのrequestTypeフィールドの追加は、システムの分析機能向上に貢献します。
67-73: 詳細なロギングの追加sessionIdとrequestTypeを含む包括的なロギングにより、デバッグと監視が大幅に改善されます。
271-272: クエリの最適化とロギングの改善currentTime変数の一貫した使用とメッセージ取得のロギングにより、パフォーマンスと可観測性が向上しています。
Also applies to: 287-287
297-297: requestTypeメタデータの取得対応返却メタデータにrequestTypeを含めることで、下流コンポーネントでの適切なコンテキスト処理が可能になります。
src/mastra/agents/realtime-agent.ts (2)
12-12: STT補正ユーティリティのインポート新しいSTT補正システムとの統合により、音声認識の精度向上が期待できます。
45-50: 入力正規化メソッドのリファクタリングGoogleCloudVoiceSimpleでの主要な補正処理への移譲により、責任分担が明確化され、フォールバック機能として適切に機能します。
src/mastra/voice/google-cloud-voice-simple.ts (3)
8-8: STT補正ユーティリティのインポート音声認識の後処理改善のためのユーティリティ関数のインポートが適切に追加されています。
200-218: STT補正システムの統合Google Cloud Speech-to-TextのAPIレスポンスに対する後処理として、STT補正とconfidence調整が適切に実装されています。補正前後のロギングにより、システムの動作を適切に監視できます。
222-223: 補正後のトランスクリプトと信頼度の返却補正されたトランスクリプトと調整された信頼度スコアの返却により、下流コンポーネントはより正確なデータを受け取ることができます。
src/mastra/tools/rag-search.ts (1)
324-325: フォーマット変更による一貫性の向上を評価しますタイトルを除去してコンテンツのみを返却する変更により、出力がより簡潔になり一貫性が向上しています。この変更は適切です。
Also applies to: 382-383
scripts/test-stt-corrections.ts (2)
11-30: 包括的なテストケースの設計を評価しますテストケースは日本語・英語の補正、コンテキストがない場合の非補正、複雑なケースを適切にカバーしています。テストの設計は良好です。
77-77: 終了コードの設定を確認してください失敗時に適切な終了コードを返すことで、CI/CDパイプラインでの自動テストが可能になります。この実装は適切です。
src/test/test-memory-storage.ts (1)
48-69: データベース検証ロジックの品質を評価しますデータベース内のメッセージを詳細に検証し、適切なエラーハンドリングを実装している点は優秀です。expires_atフィールドの確認も含まれており、TTL機能の検証が適切に行われています。
docs/DEVELOPMENT.md (2)
53-63: 環境変数ドキュメントの改善を評価しますOpenAI API keyの説明に埋め込み次元(1536次元)の情報を追加し、CRON認証用の新しい環境変数を追加したことで、設定の明確性が向上しています。
768-825: 新機能開発ガイドの実用性を評価しますメモリシステム、音声再生サービス、RAG検索の具体的な使用例を提供することで、開発者の理解と実装を促進する優れたドキュメントです。コード例は実践的で分かりやすくなっています。
docs/STATUS.md (2)
36-44: 実装状況の詳細な更新を評価します依存関係のバージョン更新(@pixiv/three-vrm 3.4.1、Supabase 2.49.8)と新機能(多言語RAG、統一メモリシステム、モバイル音声対応、本番監視)の追加により、現在の実装状況が正確に反映されています。
205-230: 新機能セクションの追加による文書化の充実を評価しますメモリシステム、音声システム、RAG拡張、本番機能の詳細な説明により、開発者が新機能を理解しやすくなっています。各機能の具体的な利点と実装詳細が適切に文書化されています。
_docs/blog/2025-06-29_AIアシスタントが空気を読めるようになった話〜会話の文脈を理解してピンポイントで答える技術〜.md (1)
1-209: 技術ブログとして優れた内容!この記事は実装の背景と技術的詳細を非常にわかりやすく説明しており、開発者向けの価値の高いコンテンツになっています。特に具体的なコードサンプルと実際の問題解決プロセスが含まれているのが素晴らしいです。
記事で言及されている技術実装が、今回のPRで追加された他のファイル(STT補正システム、会話記憶システム)と整合していることも確認できました。
docs/DEPLOYMENT.md (2)
742-790: 監視ダッシュボードのJSONレスポンス構造が詳細で優秀監視メトリクスの構造が非常に包括的で、本番運用に必要な指標が適切に定義されています。特にRAG検索、キャッシュ、外部API、システムヘルスの各メトリクスが体系的に整理されているのが素晴らしいです。
844-854: iPad/iOS音声問題の対処法が具体的AudioContextの問題とその解決策が明確に記載されており、実際のトラブルシューティングに役立ちます。MobileAudioServiceとAudioInteractionManagerによる自動フォールバック機構の説明も適切です。
scripts/create-stt-correction-logs-table.sql (4)
2-10: テーブル設計が適切で効率的STT補正ログテーブルの設計が非常に良く考えられています:
corrections_applied TEXT[]配列型の使用が適切confidence FLOATでSTTの信頼度を記録languageフィールドで多言語対応created_atでタイムスタンプ管理データ型の選択と正規化レベルが補正ログの用途に最適化されています。
13-16: インデックス設計が查询パフォーマンスに最適化3つのインデックスが適切に設計されています:
created_at DESCで最新ログの高速取得languageで言語別フィルタリングoriginal_textで特定の誤認識パターン検索補正ログの典型的な查询パターンを考慮した効率的な設計です。
18-27: 分析用ビューが洞察に富んでいる
stt_misrecognition_patternsビューが非常に有用です:
- 誤認識の発生頻度を集計
- 初回・最終発生日時を追跡
- 複数の補正パターンを配列で管理
この構造により誤認識傾向の分析と補正ルールの改善が効率的に行えます。
30-43: RLSポリシーがセキュリティ要件を満たしているRow Level Securityの実装が適切です:
service_roleへの完全アクセス権限(システムによる自動ログ記録用)authenticatedユーザーへの読み取り専用アクセス(分析・監視用)補正ログの性質上、この権限設計は理想的です。learned learningsに記載されたRLS要件とも一致しています。
src/lib/stt-correction-monitor.ts (4)
35-65: バッチ処理ロジックが効率的補正イベントのバッチ処理実装が非常によく設計されています:
- 実際に補正が行われた場合のみログ記録
- 開発環境でのデバッグ出力
- バッチサイズ到達時の自動フラッシュ
- タイマーベースの定期フラッシュ
この実装により、パフォーマンスとリアルタイム性のバランスが取れています。
94-119: エラーハンドリングとフェイルセーフが優秀データベース保存失敗時の処理が非常に堅牢です:
- 失敗したイベントを配列の先頭に戻す
- try-catchによる包括的エラーキャッチ
- 適切なエラーログ出力
この実装により、一時的なネットワーク障害やデータベース問題でもデータ損失を防げます。
124-184: 統計分析機能が洞察に富んでいる
getStatsメソッドの実装が非常に有用です:
- 期間指定による柔軟な分析
- 補正タイプ別の集計
- 最頻出誤認識パターンの特定
- エラー処理による堅牢性
この機能により補正ルールの効果測定と改善が効率的に行えます。
199-202: プロセス終了時のクリーンアップが適切SIGINTとSIGTERMハンドラーの実装により、プロセス終了時に未保存のイベントが確実にフラッシュされます。本番環境での信頼性に重要な実装です。
README.md (6)
17-42: 最新アップデート情報が包括的で詳細新機能の説明が非常に充実しており、特にSTT誤認識対策の具体例(「じかつきしゅうスペース」→「集中スペース」)が実用的です。各機能の技術的詳細と実装状況が明確に記載されているのが素晴らしいです。
146-152: AIモデル情報の詳細化が有用Google text-embedding-004の768次元から1536次元へのパディング詳細と、OpenAI text-embedding-3-smallのフォールバック戦略の説明が技術者にとって非常に有益な情報です。
560-575: パフォーマンス指標の実測値が説得力あり総合応答時間1.3秒の達成とSimplifiedMemorySystemの具体的なパフォーマンス数値(メモリ追加<100ms、コンテキスト取得<200ms)が記載されており、システムの実用性を明確に示しています。
678-698: STT誤認識対処法の説明が実践的音声認識の誤認識問題と対処法が具体的に説明されており、特に手動対処方法のTypeScriptコードサンプルが実装者にとって非常に有用です。自動対処機能の説明も適切です。
940-970: 開発コマンド一覧が開発効率に貢献CRONジョブ、知識ベース管理、データベース操作など、運用に必要なコマンドが体系的に整理されています。特に本番環境での手動トリガーコマンドの記載が運用面で重要です。
972-988: 知識ベースシステムの技術詳細が充実RAG検索システムの多言語対応、ハイブリッド埋め込み戦略、管理UIの説明が非常に詳細で、システムの技術的優位性がよく表現されています。84件以上のエントリーという具体的な規模感も有用です。
src/utils/stt-corrections.ts (1)
119-124: 動的インポートのエラーハンドリングが適切です。lazy importを使用してcircular dependencyを回避し、監視システムのエラーを適切に無視する実装は優秀です。
README-EN.md (2)
34-36: 新機能の文書化が優秀です。STT補正システム、レスポンス精度システム、メモリ対応会話システムの追加が適切に文書化されています。機能の価値と実装が明確に説明されています。
334-342: 新しいテストとモニタリングコマンドが有用です。APIテスト、RAG検索テスト、外部API統合テスト、監視ダッシュボード、ヘルスチェックのコマンドが追加され、開発とオペレーションの効率性が向上します。
docs/API-ja.md (2)
38-44: CRON認証の仕様が明確です。CRON_SECRET環境変数によるBearer token認証の仕様が適切に文書化されており、セキュリティの実装が明確です。
621-756: 新しいAPIエンドポイントの文書化が包括的です。知識ベース検索API、監視API、管理API、CRON API、ヘルスチェックAPIが詳細に文書化されており、リクエスト・レスポンス例も適切に提供されています。
docs/API.md (2)
694-698: クロス言語検索機能の説明が優秀です。マルチ言語RAG検索の機能説明が技術的に正確で、Google text-embedding-004とOpenAIの組み合わせ、重複除去機能が明確に説明されています。
861-869: v2.1.0の変更ログが包括的です。新機能の変更ログが詳細で、SimplifiedMemorySystem、マルチ言語RAG、モバイル音声互換性、監視ダッシュボードなどの主要な改善が適切に文書化されています。
CLAUDE.md (9)
18-18:typecheckコマンドの追加を確認しましたTypeScriptの型チェックコマンドの追加は開発品質向上に役立ちます。
28-28: 埋め込み更新コマンドの追加を確認しました既存のナレッジベースの埋め込みを更新するコマンドの追加は、ベクトル検索の精度向上に重要です。
38-42: 監視・ヘルスチェックコマンドの追加を確認しましたシステムヘルスチェックとパフォーマンスメトリクスのコマンド追加により、本番環境の監視が強化されます。
61-61: STT補正システムの文書化を確認しました日本語認識精度向上のためのSTT補正システムの追加が適切に文書化されています。
612-633: STT補正システムセクションの追加音声認識の誤認識パターンに対する補正システムの詳細が適切に文書化されています。エンジニアカフェ特有の用語や技術用語の処理について明確に説明されています。
634-649: レスポンス精度向上システムの文書化特定のリクエストタイプの検出と簡潔な回答生成の仕組みが明確に説明されています。ユーザー体験の向上に貢献する重要な機能です。
651-664: SimplifiedMemorySystemの改善点を確認しましたセッションID処理の修正やクエリパフォーマンスの最適化など、重要な改善点が適切に文書化されています。
665-695: 最近の修正と改善の包括的な文書化2024年の主要な修正と改善が体系的にまとめられており、システムの進化が明確に記録されています。
33-33: 本番環境での誤実行防止チェックを確認してください
pnpm db:resetが開発環境専用コマンドとしてのみ動作し、実装側で$NODE_ENV !== 'production'などによる明示的なセーフティチェック(誤実行時の早期終了やユーザー確認)を行っているかをご確認ください。確認ポイント:
- package.json の scripts セクションに定義されている
db:reset("db:reset": …)- CLI 実装ファイル(例:scripts/db-reset.ts 等)内の環境判定ロジック
ご対応をお願いします。
src/mastra/agents/enhanced-qa-agent.ts (10)
8-8: STT補正モジュールのインポートを確認しました音声認識の誤認識を補正する
applySttCorrections関数のインポートが適切に追加されています。
48-48: セッションID対応の改善
answerQuestionメソッドにオプションのsessionIdパラメータが追加され、会話の連続性が向上します。
58-67: メモリコンテキスト取得のデバッグログ強化メモリコンテキストの取得結果を詳細にログ出力することで、問題の診断が容易になります。
173-201: コンテキスト応答の精度向上前の会話から特定のリクエストタイプを抽出し、より的確な応答を生成する仕組みが実装されています。営業時間、料金、場所などの具体的な情報要求に対して適切に対応できます。
257-275: レスポンスの後処理とクリーンアップ角括弧付きのタグを除去し、特定のリクエストに対する長すぎる回答を簡潔にする処理が適切に実装されています。
280-288: メモリへのリクエストタイプとセッションIDの保存会話履歴にリクエストタイプとセッションIDを含めることで、コンテキストの追跡性が向上します。
391-406: RAG検索前のSTT補正処理検索クエリに対してSTT補正を適用することで、「エンジンカフェ」→「エンジニアカフェ」などの一般的な誤認識を修正し、検索精度が向上します。補正が適用された場合のログ出力も適切です。
542-550: 質問分類でのSTT補正適用
categorizeQuestionメソッドでもSTT補正が適用され、質問の分類精度が向上します。
949-953: メタデータからのリクエストタイプ取得会話履歴のメタデータに保存されたリクエストタイプを優先的に使用する仕組みが追加され、コンテキストの継続性が向上します。
978-1009: 新しいリクエストタイプ抽出メソッド質問から営業時間、料金、場所などの具体的なリクエストタイプを抽出する専用メソッドが追加されました。包括的なパターンマッチングにより、様々な質問形式に対応できます。
| // Step 1: Clear any existing memory | ||
| console.log('\n1. Clearing existing memory...'); | ||
| await supabaseAdmin | ||
| .from('agent_memory') | ||
| .delete() | ||
| .eq('agent_name', 'EnhancedQAAgent'); | ||
| console.log('✅ Memory cleared'); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
データベースクリーンアップのスコープを制限することを検討してください
現在のクリーンアップはすべてのEnhancedQAAgentエントリを削除しますが、他の並行テストに影響する可能性があります。
より安全なアプローチとして、一意のテストIDを使用することを提案します:
+// Generate unique test ID for isolation
+const testId = `test_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
+const testAgentName = `EnhancedQAAgent_${testId}`;
+
-const memory = new SimplifiedMemorySystem('EnhancedQAAgent', {
+const memory = new SimplifiedMemorySystem(testAgentName, {
ttlSeconds: 180, // 3 minutes
maxEntries: 100
});
// Step 1: Clear any existing memory
console.log('\n1. Clearing existing memory...');
await supabaseAdmin
.from('agent_memory')
.delete()
- .eq('agent_name', 'EnhancedQAAgent');
+ .eq('agent_name', testAgentName);🤖 Prompt for AI Agents
In src/test/test-memory-storage.ts around lines 14 to 20, the current database
cleanup deletes all entries for 'EnhancedQAAgent', which may affect other
concurrent tests. Modify the cleanup to target only entries associated with a
unique test ID or identifier specific to the current test run. This involves
adding a filter condition using this unique test ID in the delete query to limit
the scope of deletion and avoid interfering with parallel tests.
| console.log('\n6. Testing memory stats...'); | ||
| const stats = await memory.getMemoryStats(); | ||
| console.log('Memory stats:', JSON.stringify(stats, null, 2)); | ||
|
|
||
| // Step 7: Test isConversationActive | ||
| console.log('\n7. Testing isConversationActive...'); | ||
| const isActive = await memory.isConversationActive(); | ||
| console.log('Is conversation active?', isActive); | ||
|
|
||
| // Step 8: Test session summary | ||
| console.log('\n8. Testing session summary...'); | ||
| const summary = await memory.getSessionSummary('ja'); | ||
| console.log('Session summary:', summary); |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
メモリ統計とセッション要約のテストを検証してください
メモリ統計とセッション要約の機能テストが含まれていますが、戻り値の詳細な検証は行われていません。
メモリ統計とセッション要約の戻り値を検証するスクリプトを実行して、期待される構造を確認してください:
🏁 Script executed:
#!/bin/bash
# SimplifiedMemorySystemの戻り値構造を確認
# getMemoryStats()の戻り値構造を検索
ast-grep --pattern $'getMemoryStats() {
$$$
return {
$$$
}
$$$
}'
# getSessionSummary()の戻り値構造を検索
ast-grep --pattern $'getSessionSummary($_) {
$$$
return $$$
$$$
}'Length of output: 152
関数実装箇所の再検索
getMemoryStats および getSessionSummary の定義が ast-grep で検出されなかったため、下記スクリプトで実装箇所を検索し、戻り値構造を確認できるファイルと行番号を特定してください。
🏁 Script executed:
#!/bin/bash
# getMemoryStats と getSessionSummary の定義を検索
rg -n "getMemoryStats" .
rg -n "getSessionSummary" .Length of output: 712
メモリ統計とセッション要約のテストにアサーションを追加してください
現在のテストでは console.log で出力を確認するのみとなっており、戻り値の構造や型に対する検証が不足しています。以下の点を修正してください。
・テストファイル:src/test/test-memory-storage.ts(89–100行目)
・定義元:src/lib/simplified-memory.ts
– getMemoryStats() 定義(約213行目)
– getSessionSummary() 定義(約162行目)
例:
// 6. Testing memory stats...
const stats = await memory.getMemoryStats();
expect(stats).toBeDefined();
expect(typeof stats.totalItems).toBe('number');
expect(stats).toHaveProperty('createdAt');
expect(typeof stats.createdAt).toBe('string');
// 8. Testing session summary...
const summary = await memory.getSessionSummary('ja');
expect(typeof summary).toBe('string');
expect(summary.length).toBeGreaterThan(0);– 必要に応じて getMemoryStats の戻り値が持つ全プロパティ(数値/日付文字列など)を明示的に検証してください
– getSessionSummary については文字列であること、かつ非空であることをチェックしてください
これらのアサーションを追加した後、CIが正常に通過することを確認してください。
🤖 Prompt for AI Agents
In src/test/test-memory-storage.ts around lines 88 to 100, replace the
console.log output checks for getMemoryStats() and getSessionSummary() with
proper assertions. For getMemoryStats(), add assertions to verify the object is
defined, check that numeric properties like totalItems are numbers, and date
properties like createdAt are strings. For getSessionSummary(), assert that the
returned value is a non-empty string. This ensures the tests validate the
structure and types of the returned data instead of just printing them. After
adding these assertions, run the tests to confirm CI passes.
| ## 🔧 開発用コマンド一覧 | ||
|
|
||
| ### 開発・ビルド | ||
| ```bash | ||
| pnpm dev # 開発サーバー起動 (http://localhost:3000) | ||
| pnpm dev:clean # キャッシュクリア後に開発サーバー起動 | ||
| pnpm build # 本番ビルド作成 | ||
| pnpm start # 本番サーバー起動 | ||
| pnpm lint # Next.js リンティング | ||
| ``` | ||
|
|
||
| ### 依存関係管理 | ||
| ```bash | ||
| pnpm install:css # Tailwind CSS v3 依存関係の正しいインストール | ||
| # 注意: Tailwind CSS v4にアップグレードしないでください | ||
| ``` | ||
|
|
||
| ### 知識ベース管理 | ||
| ```bash | ||
| pnpm seed:knowledge # 初期データで知識ベースをシード | ||
| pnpm migrate:embeddings # 既存知識をOpenAI埋め込みに移行 | ||
| pnpm import:knowledge # マークダウンファイルから知識をインポート | ||
| pnpm import:narrations # スライドナレーションをインポート | ||
| ``` | ||
|
|
||
| ### データベース管理 | ||
| ```bash | ||
| pnpm db:migrate # データベースマイグレーション実行 | ||
| pnpm db:setup-admin # 管理知識インターフェースのセットアップ | ||
| ``` | ||
|
|
||
| ### CRONジョブ(本番環境) | ||
| ```bash | ||
| pnpm cron:update-knowledge # 知識ベース更新を手動でトリガー | ||
| pnpm cron:update-slides # スライド更新を手動でトリガー | ||
| ``` | ||
|
|
||
| ### 監視・分析 | ||
| ```bash | ||
| pnpm monitor:baseline # パフォーマンスベースライン収集 | ||
| pnpm monitor:migration # マイグレーションステータス監視 | ||
| pnpm compare:implementations # 実装パフォーマンス比較 | ||
| pnpm validate:production # 本番環境準備状況検証 | ||
| pnpm check:deployment # デプロイメント準備状況確認 | ||
| ``` |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
開発コマンドの整理と検証が必要です
多数の新しいコマンドが追加されていますが、これらがすべて実際に定義されているか確認が必要です。
すべての開発コマンドの存在確認スクリプト:
🏁 Script executed:
#!/bin/bash
# 全開発コマンドの存在確認
commands=(
"dev" "dev:clean" "build" "start" "lint" "install:css"
"seed:knowledge" "migrate:embeddings" "import:knowledge" "import:narrations"
"db:migrate" "db:setup-admin"
"cron:update-knowledge" "cron:update-slides"
"monitor:baseline" "monitor:migration" "compare:implementations"
"validate:production" "check:deployment"
)
echo "Checking development commands in package.json..."
for cmd in "${commands[@]}"; do
if cat package.json | jq -r ".scripts.\"$cmd\"" | grep -q "null"; then
echo "❌ $cmd not defined"
else
echo "✅ $cmd exists"
fi
doneLength of output: 3495
docs/DEVELOPMENT.md に記載されている未定義の npm スクリプトを整理してください
以下のコマンドが package.json の scripts に存在しませんでした。ドキュメントへ残す場合は該当スクリプトを追加し、不要であればドキュメントから削除してください。
• import:knowledge
• import:narrations
• db:migrate
• db:setup-admin
• cron:update-knowledge
• cron:update-slides
• monitor:baseline
• monitor:migration
• compare:implementations
• validate:production
• check:deployment
File: docs/DEVELOPMENT.md
Lines: 889–933
🤖 Prompt for AI Agents
In docs/DEVELOPMENT.md between lines 889 and 933, several npm scripts listed
under various categories do not exist in the package.json scripts section. To
fix this, verify each listed script's presence in package.json; if a script is
missing but needed, add it to package.json with the correct command. If a script
is not used or planned, remove its entry from the DEVELOPMENT.md documentation
to keep it accurate and up to date.
| ### 利用可能なテストコマンド | ||
|
|
||
| ```bash | ||
| # API接続テスト | ||
| pnpm test:api | ||
| ``` | ||
|
|
||
| このコマンドは`scripts/test-api-connection.ts`を実行し、APIエンドポイントの基本的な動作を確認します。 | ||
| # RAG検索機能テスト | ||
| pnpm test:rag | ||
|
|
||
| # 外部API統合テスト | ||
| pnpm test:external-apis | ||
|
|
||
| # ローカル環境セットアップテスト | ||
| pnpm test:local | ||
|
|
||
| # 本番環境デプロイメントテスト | ||
| pnpm test:production | ||
|
|
||
| # 外部データフェッチャーテスト | ||
| pnpm test:external-data | ||
| ``` |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
テストコマンドの拡張を検証してください
新しく追加されたテストコマンド(pnpm test:rag、pnpm test:external-apisなど)が実際にpackage.jsonで定義されているか確認が必要です。
package.jsonでテストコマンドの定義を確認してください:
🏁 Script executed:
#!/bin/bash
# package.jsonでテストコマンドの定義を確認
# テストコマンドの存在確認
cat package.json | jq '.scripts | with_entries(select(.key | test("test:")))'
# 特定のテストコマンドの確認
echo "Checking specific test commands..."
for cmd in "test:rag" "test:external-apis" "test:local" "test:production" "test:external-data"; do
if cat package.json | jq -r ".scripts.\"$cmd\"" | grep -q "null"; then
echo "❌ $cmd not found"
else
echo "✅ $cmd exists"
fi
doneLength of output: 1308
package.json にテストコマンド定義がありません
docs/DEVELOPMENT.md(619–639行)に記載されている以下のテストコマンドが、package.json の scripts セクションに定義されていません:
- test:api
- test:rag
- test:external-apis
- test:local
- test:production
- test:external-data
package.json に不足しているスクリプトを追加してください。例えば:
"scripts": {
+ "test:api": "jest --config=jest.api.config.js",
+ "test:rag": "jest --config=jest.rag.config.js",
+ "test:external-apis": "jest --config=jest.external-apis.config.js",
+ "test:local": "jest --config=jest.local.config.js",
+ "test:production": "jest --config=jest.production.config.js",
+ "test:external-data": "jest --config=jest.external-data.config.js",
...
}Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In docs/DEVELOPMENT.md around lines 619 to 639, the listed test commands are not
defined in package.json scripts. To fix this, add the missing test scripts
(test:api, test:rag, test:external-apis, test:local, test:production,
test:external-data) to the package.json "scripts" section with appropriate
command values matching the described tests.
| 3. Clean up unused dependencies (face-api.js) | ||
| 4. Standardize environment variable usage | ||
|
|
||
| ### Medium Priority | ||
| 1. Implement Web Speech API for cost reduction | ||
| 2. Add comprehensive API tests | ||
| 3. Create developer onboarding documentation | ||
| 4. Add performance monitoring | ||
| 4. Enhance mobile/tablet compatibility (iOS audio issues) | ||
|
|
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
推奨事項の優先度設定を検証してください
未使用の依存関係(face-api.js)のクリーンアップやモバイル互換性の改善が言及されていますが、これらの項目が実際に必要かどうか確認が必要です。
未使用依存関係とモバイル対応の現状確認:
🏁 Script executed:
#!/bin/bash
# 未使用依存関係の確認
# face-api.jsの使用状況確認
echo "Checking face-api.js usage..."
rg "face-api" --type ts --type js --type tsx --type jsx
# モバイル音声対応の実装状況確認
echo "Checking mobile audio implementation..."
rg "MobileAudioService|WebAudioPlayer" --type ts --type tsx -A 2
# iOS音声問題の現状確認
echo "Checking iOS audio compatibility..."
rg "iOS|safari|webkit" --type ts --type tsx -i -A 2Length of output: 499
tsxファイルのタイプ指定でエラーが出ているため、全ファイルを対象にして未使用依存とモバイル音声実装状況を再度検索します(node_modulesと.gitは除外)。
🏁 Script executed:
#!/bin/bash
echo "Checking face-api.js usage across all files..."
rg "face-api" --glob '!.git/*' --glob '!node_modules/*'
echo "Checking mobile audio implementation across all files..."
rg "MobileAudioService|WebAudioPlayer" --glob '!.git/*' --glob '!node_modules/*'
echo "Checking iOS audio compatibility across all files..."
rg "iOS|safari|webkit" -i --glob '!.git/*' --glob '!node_modules/*'Length of output: 23240
🔄 STATUS.md のタスク優先度とステータスの更新
以下のとおりご確認ください。
-
face-api.js のクリーンアップは有効です
- 実装コード中に利用箇所がなく、
src/app/layout.tsxの<script>タグ読み込みと README(README.md/README-EN.md)の記載のみです - 依存を削除する場合は該当の script タグ・ドキュメント記載・
package.jsonから除去してください
- 実装コード中に利用箇所がなく、
-
モバイル/タブレット互換性(iOS 音声問題)は既に実装済みです
MobileAudioService/WebAudioPlayerによる Web Audio API 対応と Safari/iOS 向け最適化が入っているため- “Enhance mobile/tablet compatibility (iOS audio issues)” は Medium Priority から削除、または完了(✅)に更新してください
🧰 Tools
🪛 LanguageTool
[uncategorized] ~193-~193: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...dardize environment variable usage ### Medium Priority 1. Implement Web Speech API for cost re...
(EN_COMPOUND_ADJECTIVE_INTERNAL)
🤖 Prompt for AI Agents
In docs/STATUS.md around lines 190 to 198, update the task list to reflect that
face-api.js cleanup requires removing its script tag from src/app/layout.tsx,
deleting related README mentions, and removing it from package.json. Also, mark
the "Enhance mobile/tablet compatibility (iOS audio issues)" task as completed
or remove it from Medium Priority since it is already implemented with
MobileAudioService and WebAudioPlayer optimizations.
| "crons": [ | ||
| { | ||
| "path": "/api/cron/update-knowledge-base", | ||
| "schedule": "0 */6 * * *" // 6時間ごと | ||
| }, | ||
| { | ||
| "path": "/api/cron/update-slides", | ||
| "schedule": "0 0 * * *" // 毎日午前0時 | ||
| } | ||
| ] | ||
| } | ||
| ``` | ||
|
|
||
| #### CRON ジョブセキュリティ | ||
|
|
||
| ```typescript | ||
| // api/cron/update-knowledge-base/route.ts | ||
| export async function POST(request: NextRequest) { | ||
| // CRONシークレット検証 | ||
| const authHeader = request.headers.get('authorization'); | ||
| if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
|
|
||
| // 知識ベース更新処理 | ||
| // ... | ||
| } | ||
| ``` |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
CRON認証のセキュリティ実装を確認
CRON_SECRETによる認証機構は良い実装ですが、実際のAPIルートでの実装が確実に行われているかを確認する必要があります。
🏁 Script executed:
#!/bin/bash
# CRON API実装の確認
echo "CRON API実装をチェック中..."
# CRON APIルートの存在確認
fd -t f "route.ts" api/cron --exec grep -l "CRON_SECRET" {} \;
# 認証実装の詳細確認
ast-grep --pattern $'export async function POST($request) {
$$$
const authHeader = $$$
$$$
CRON_SECRET
$$$
}'Length of output: 329
CRON API ルートハンドラが見つかっていないようです。Next.js の app/api/cron 配下に実装されている可能性が高いため、以下のスクリプトで route.ts ファイルと CRON_SECRET の使用箇所を全リポジトリから検索してください。
🏁 Script executed:
#!/bin/bash
set -e
echo "🔍 route.ts ファイルを全リポジトリから検索中..."
fd route.ts
echo "🔍 CRON_SECRET の使用箇所を全リポジトリから検索中..."
grep -R "CRON_SECRET" -n .Length of output: 1807
CRON エンドポイントで認証処理が確実に行われているかを確認するため、以下のスクリプトで両ファイルの実装をチェックしてください。
🏁 Script executed:
#!/bin/bash
set -e
echo "🔍 update-knowledge-base ルート実装を表示"
sed -n '1,200p' src/app/api/cron/update-knowledge-base/route.ts
echo
echo "🔍 認証ロジックが含まれる行を抽出"
grep -n "authHeader" -n src/app/api/cron/update-knowledge-base/route.ts || echo "認証ロジック無し"
echo
echo "🔍 update-slides ルート実装を表示"
sed -n '1,200p' src/app/api/cron/update-slides/route.ts
echo
echo "🔍 認証ロジックが含まれる行を抽出"
grep -n "authHeader" -n src/app/api/cron/update-slides/route.ts || echo "認証ロジック無し"Length of output: 4212
update-slides エンドポイントに認証チェックを追加してください
以下の対応が必要です:
- src/app/api/cron/update-slides/route.ts に CRON_SECRET を検証する認証ロジックが実装されていません。update-knowledge-base と同様に、GET ハンドラの冒頭で以下を追加してください:
const authHeader = request.headers.get('authorization'); const cronSecret = process.env.CRON_SECRET; if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); }
- docs/DEPLOYMENT.md のサンプルでは update-knowledge-base のハンドラを
POSTとしていますが、実際の実装はGETです。ドキュメントのメソッド表記をコードに合わせてGETに修正してください。
🤖 Prompt for AI Agents
In docs/DEPLOYMENT.md around lines 308 to 335, add the CRON_SECRET authorization
check to the update-slides endpoint's GET handler similar to
update-knowledge-base by verifying the authorization header against
process.env.CRON_SECRET and returning a 401 JSON response if unauthorized. Also,
change the documented HTTP method for update-knowledge-base from POST to GET to
match the actual implementation.
| { | ||
| pattern: /会議室/g, | ||
| replacement: '会議室', | ||
| context: /壁/, | ||
| description: 'Prevent over-correction when actually talking about walls in meeting rooms' | ||
| } |
There was a problem hiding this comment.
補正ルールのロジックエラーを修正してください。
67-72行の補正ルールは混乱を招きます。パターンと置換が同じ(会議室 → 会議室)で、コンテキストに/壁/が設定されていますが、これは過剰補正を防ぐ目的としては機能しません。
- // Other common Japanese misrecognitions
- {
- pattern: /会議室/g,
- replacement: '会議室',
- context: /壁/,
- description: 'Prevent over-correction when actually talking about walls in meeting rooms'
- }
+ // Skip correction when actually talking about walls in meeting rooms
+ // This should be handled in the correction logic, not as a replacement ruleまたは、このルールを削除して、補正ロジック内で適切なコンテキスト処理を実装することを検討してください。
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/utils/stt-corrections.ts lines 67 to 72, the correction rule has the same
pattern and replacement ('会議室' → '会議室') with a context of /壁/, which does not
prevent over-correction as intended. Either remove this redundant rule entirely
or revise the correction logic to properly handle context-based exceptions,
ensuring that corrections only apply when the context does not include '壁'.
There was a problem hiding this comment.
Bug: Duplicate Messages in RealtimeAgent
The RealtimeAgent stores messages redundantly, leading to duplicate entries and polluted conversation history. User messages are stored twice in sharedMemory within processTextInput, and an early, potentially redundant, storage also occurs in processVoiceInput. Additionally, both SimplifiedMemorySystem and SharedMemoryService are configured to use the same 'shared' namespace, causing all conversation turns (user and assistant messages) to be duplicated in the underlying memory.
src/mastra/agents/realtime-agent.ts#L124-L192
engineer-cafe-navigator/src/mastra/agents/realtime-agent.ts
Lines 124 to 192 in 0589b7f
Bug: Voice Input Data Stored Twice
In the processVoiceInput method, user transcripts are redundantly stored in shared memory. An initial storage occurs before AI response generation, followed by a duplicate storage with additional metadata after the response is generated.
src/mastra/agents/realtime-agent.ts#L355-L395
engineer-cafe-navigator/src/mastra/agents/realtime-agent.ts
Lines 355 to 395 in 0589b7f
Was this report helpful? Give feedback by reacting with 👍 or 👎
There was a problem hiding this comment.
Actionable comments posted: 7
🔭 Outside diff range comments (1)
src/mastra/agents/enhanced-qa-agent.ts (1)
1-1313: 包括的なコード品質改善の推奨このファイルの機能拡張は包括的で適切ですが、以下の観点で改善を推奨します:
アーキテクチャ面:
- 長いメソッドの分割(単一責任原則の適用)
- 共通ロジックの抽出(DRY原則の適用)
- 型安全性の向上
パフォーマンス面:
- LLM呼び出しの最適化
- メモリアクセスパターンの効率化
保守性面:
- 設定値の外部化
- エラーメッセージの国際化対応
これらの改善により、システムの安定性と保守性が大幅に向上します。
♻️ Duplicate comments (1)
src/utils/stt-corrections.ts (1)
67-72: 補正ルールのロジックエラーを修正してくださいこの補正ルールは機能しません。パターンと置換が同じ(
会議室→会議室)で、意図された過剰補正の防止効果がありません。- // Other common Japanese misrecognitions - { - pattern: /会議室/g, - replacement: '会議室', - context: /壁/, - description: 'Prevent over-correction when actually talking about walls in meeting rooms' - }この無効なルールを削除するか、適切な例外処理ロジックを補正関数内に実装してください。
🧹 Nitpick comments (7)
src/lib/shared-memory-service.ts (1)
54-76: メタデータの型安全性を改善することを検討
addMessageメソッドは柔軟なメタデータ構造を提供していますが、[key: string]: anyのインデックス署名により型安全性が低下しています。metadata?: { agentName?: string; emotion?: string; confidence?: number; requestType?: string | null; } & Record<string, unknown>; // より制限的な型を使用src/mastra/agents/realtime-agent.ts (1)
164-191: メモリ保存の重複を最適化することを検討現在、ユーザーメッセージとアシスタントメッセージの両方が共有メモリとローカルメモリの両方に保存されており、重複した保存処理が発生しています。
パフォーマンスの改善のため、以下を検討してください:
- 主要なメモリストレージを共有メモリに統一
- ローカルメモリは特定のエージェント固有データのみに使用
- バッチ保存処理の実装
src/mastra/agents/enhanced-qa-agent.ts (5)
14-14: 共有メモリの設定における防御的プログラミングの改善sharedMemoryの設定は適切ですが、configから渡される値のnullチェックを追加することを推奨します。
- this.sharedMemory = config.sharedMemory; + this.sharedMemory = config.sharedMemory || null;これにより、undefinedが渡された場合の予期しない動作を防げます。
Also applies to: 32-34
98-120: コンテキスト応答処理の可読性改善新しいコンテキスト応答処理ロジックは機能的には適切ですが、ネストが深く可読性に課題があります。メソッドの分割を検討してください。
+ private async handleContextualResponse(question: string, memoryContext: any): Promise<string | null> { + if (!this.isContextualResponse(question) || memoryContext.recentMessages.length === 0) { + return null; + } + + const lastAssistantMessage = memoryContext.recentMessages + .filter(msg => msg.role === 'assistant') + .slice(-1)[0]; + + if (lastAssistantMessage && this.isClarificationMessage(lastAssistantMessage.content)) { + const originalContext = this.extractOriginalContext(memoryContext.recentMessages); + if (originalContext) { + return await this.processContextualResponse(question, originalContext, language); + } + } + + return null; + }
318-339: メモリストレージの重複コード削減共有メモリとローカルメモリでの処理が重複しています。共通のヘルパーメソッドを作成することを推奨します。
+ private async storeConversation(question: string, response: string, requestType: string | null, sessionId?: string) { + if (this.sharedMemory) { + await this.sharedMemory.addMessage('user', question, { + agentName: 'EnhancedQAAgent', + requestType: requestType + }); + await this.sharedMemory.addMessage('assistant', response, { + agentName: 'EnhancedQAAgent' + }); + } else { + await this.simplifiedMemory.addMessage('user', question, { + requestType: requestType, + sessionId: sessionId + }); + await this.simplifiedMemory.addMessage('assistant', response, { + sessionId: sessionId + }); + } + }
1012-1016: メタデータアクセスの型安全性向上メタデータからのrequestType取得は適切ですが、オプショナルチェーンを使用してより安全なアクセスを実装することを推奨します。
- if (msg.metadata?.requestType) { + if (msg.metadata && typeof msg.metadata === 'object' && 'requestType' in msg.metadata) { console.log('[EnhancedQAAgent] Found stored request type in metadata:', msg.metadata.requestType); return msg.metadata.requestType; }
305-314: 応答時間最適化の検討コード内で複数のLLM呼び出し(要約処理とコンテキスト応答生成)が順次実行されており、応答時間の増加が懸念されます。以下の最適化を検討してください:
- 要約処理の条件を厳密化(150文字→200文字など)
- 並行処理が可能な場合の
Promise.all使用- 応答キャッシュの実装
- if (isSpecificRequest && cleanedResponse.length > 150) { + if (isSpecificRequest && cleanedResponse.length > 200 && cleanedResponse.split('\n').length > 3) {Also applies to: 1279-1281
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/lib/shared-memory-service.ts(1 hunks)src/mastra/agents/enhanced-qa-agent.ts(15 hunks)src/mastra/agents/realtime-agent.ts(10 hunks)src/mastra/index.ts(2 hunks)src/utils/stt-corrections.ts(1 hunks)
🧰 Additional context used
🧠 Learnings (4)
src/mastra/index.ts (1)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
src/lib/shared-memory-service.ts (2)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
src/mastra/agents/realtime-agent.ts (3)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The application architecture is multi-layered: frontend (Next.js/React), AI agent (Mastra), audio (Web Audio API), and data (Supabase/PostgreSQL with pgvector).
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
src/mastra/agents/enhanced-qa-agent.ts (3)
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The EnhancedQAAgent uses detectSpecificRequest() to identify specific user requests and limits responses to essential information, prioritizing precision over completeness.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: Memory-aware question handling: The system detects memory-related queries (e.g., 'remember', 'さっき', 'what did I ask') and uses conversation history instead of knowledge base search for responses.
Learnt from: CR
PR: terisuke/engineer-cafe-navigator#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-24T22:31:34.870Z
Learning: The SimplifiedMemorySystem provides unified, context-aware conversation memory with a 3-minute TTL, agent isolation, and automatic cleanup.
🧬 Code Graph Analysis (2)
src/mastra/index.ts (1)
src/lib/shared-memory-service.ts (1)
getSharedMemoryService(135-140)
src/lib/shared-memory-service.ts (2)
src/lib/simplified-memory.ts (1)
SimplifiedMemorySystem(14-457)src/mastra/types/config.ts (1)
SupportedLanguage(83-83)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: Cursor BugBot
🔇 Additional comments (14)
src/mastra/index.ts (2)
10-10: LGTM: 共有メモリサービスの適切な統合新しい共有メモリサービスのインポートが追加され、統一されたメモリ管理アーキテクチャに向けた良い第一歩です。
57-66: LGTM: エージェント設定の適切な更新
mastra.memoryから新しいsharedMemoryサービスへの移行が適切に実装されています。全てのエージェントが同じ共有メモリインスタンスを使用することで、エージェント間の会話コンテキスト共有が実現されます。src/lib/shared-memory-service.ts (2)
8-19: LGTM: 良い設計とコンストラクタ実装SharedMemoryServiceクラスの設計は適切で、SimplifiedMemorySystemをラップしつつ、セッション管理と言語設定の追加機能を提供しています。TTL 180秒(3分)と最大100エントリの設定も妥当です。
135-147: LGTM: 適切なシングルトンパターンの実装シングルトンパターンとリセット機能の実装は適切です。特にテスト用のリセット機能の提供は良いプラクティスです。
src/mastra/agents/realtime-agent.ts (4)
6-6: LGTM: 共有メモリサービスの適切な統合SharedMemoryServiceのインポートにより、エージェント間のメモリ共有が可能になります。
52-54: LGTM: STT補正ユーティリティの適切な統合
applySttCorrections関数の使用により、音声認識エラーの補正が一元化され、コードの重複が削減されています。
93-95: LGTM: 統一されたメモリネームスペースの使用'shared'ネームスペースの使用により、エージェント間でメモリが共有される設計になっています。これは適切な統合です。
983-987: LGTM: セッション開始時の適切な共有メモリ設定セッション開始時に共有メモリサービスのセッションIDと言語を設定することで、エージェント間で一貫したセッション管理が実現されています。
src/utils/stt-corrections.ts (3)
17-48: LGTM: 包括的な補正ルールの定義エンジニアカフェ/壁の混同問題に対する補正ルールが適切に定義されています。コンテキストを考慮した補正は誤補正を防ぐ良いアプローチです。
82-128: LGTM: 堅牢な補正適用ロジック補正適用関数は適切に実装されています:
- 入力検証
- コンテキストチェック
- ログ記録
- 監視システムとの統合
エラーハンドリングも適切で、監視システムエラーが補正処理を妨げないよう設計されています。
176-204: 品質分析機能の追加価値
analyzeSttQuality関数は補正システムの効果測定と改善に有用な機能です。統計情報の提供により、補正ルールの最適化が可能になります。src/mastra/agents/enhanced-qa-agent.ts (3)
7-7: 新しい依存関係の適切な統合SharedMemoryServiceとSTT補正ユーティリティのインポートは、システム全体のメモリ管理とスピーチツーテキスト補正機能の統合に必要です。
Also applies to: 9-9
52-52: セッション管理の適切な実装sessionIdパラメータの追加により、セッション対応のメモリ操作が可能になります。オプショナルパラメータとしているため、既存のAPIとの後方互換性も保たれています。
442-458: STT補正機能の適切な統合STT補正機能が適切に統合されており、補正が実行された場合のみログ出力する条件分岐も良い実装です。音声認識の精度向上に寄与します。
Also applies to: 594-595
| async clearSession(): Promise<void> { | ||
| if (!this.currentSessionId) { | ||
| console.warn('[SharedMemoryService] No session ID set, cannot clear session'); | ||
| return; | ||
| } | ||
|
|
||
| // Since SimplifiedMemorySystem doesn't have a clear method, | ||
| // we'll rely on TTL to expire old messages | ||
| console.log(`[SharedMemoryService] Session ${this.currentSessionId} will expire based on TTL`); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
セッションクリア機能の改善を検討
現在のclearSessionメソッドはTTLに依存するだけで、即座にセッションデータをクリアできません。緊急時や明示的なクリアが必要な場合に対応できません。
基盤となるSimplifiedMemorySystemにクリア機能の追加を検討するか、セッションIDベースのフィルタリング機能を実装することをお勧めします。
🤖 Prompt for AI Agents
In src/lib/shared-memory-service.ts around lines 106 to 115, the clearSession
method currently only relies on TTL to expire session data and does not clear it
immediately. To fix this, enhance the SimplifiedMemorySystem by adding a clear
or delete method that can remove session data explicitly, or implement session
ID-based filtering to selectively clear data for the current session. Then
update clearSession to call this new method to immediately clear session data
when invoked.
| private extractRequestTypeFromQuestion(question: string): string | null { | ||
| const lowerQuestion = question.toLowerCase(); | ||
|
|
||
| if (lowerQuestion.includes('営業時間') || lowerQuestion.includes('hours') || lowerQuestion.includes('time') || | ||
| lowerQuestion.includes('何時') || lowerQuestion.includes('いつまで') || lowerQuestion.includes('when') || | ||
| lowerQuestion.includes('open') || lowerQuestion.includes('close') || lowerQuestion.includes('開いて') || | ||
| lowerQuestion.includes('閉まる')) { | ||
| return 'hours'; | ||
| } else if (lowerQuestion.includes('料金') || lowerQuestion.includes('price') || lowerQuestion.includes('cost') || | ||
| lowerQuestion.includes('値段') || lowerQuestion.includes('無料') || lowerQuestion.includes('有料') || | ||
| lowerQuestion.includes('fee') || lowerQuestion.includes('費用')) { | ||
| return 'price'; | ||
| } else if (lowerQuestion.includes('場所') || lowerQuestion.includes('location') || lowerQuestion.includes('where') || | ||
| lowerQuestion.includes('どこ') || lowerQuestion.includes('階') || lowerQuestion.includes('address') || | ||
| lowerQuestion.includes('住所')) { | ||
| return 'location'; | ||
| } else if (lowerQuestion.includes('予約') || lowerQuestion.includes('booking') || lowerQuestion.includes('reservation') || | ||
| lowerQuestion.includes('reserve') || lowerQuestion.includes('申し込み') || lowerQuestion.includes('申込')) { | ||
| return 'booking'; | ||
| } else if (lowerQuestion.includes('設備') || lowerQuestion.includes('facility') || lowerQuestion.includes('equipment') || | ||
| lowerQuestion.includes('何がある') || lowerQuestion.includes('what is there') || lowerQuestion.includes('利用できる')) { | ||
| return 'facility'; | ||
| } else if (lowerQuestion.includes('アクセス') || lowerQuestion.includes('access') || lowerQuestion.includes('行き方') || | ||
| lowerQuestion.includes('directions') || lowerQuestion.includes('how to get')) { | ||
| return 'access'; | ||
| } | ||
|
|
||
| return null; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
ヘルパーメソッドの重複ロジック削減
新しいヘルパーメソッドは機能的に適切ですが、extractRequestTypeFromQuestionとdetectSpecificRequestメソッド間で類似のパターンマッチングロジックが重複しています。共通の定数またはヘルパー関数を作成することを検討してください。
+ private static readonly REQUEST_TYPE_PATTERNS = {
+ hours: ['営業時間', 'hours', 'time', '何時', 'いつまで', 'when', 'open', 'close'],
+ price: ['料金', 'price', 'cost', '値段', '無料', '有料', 'fee', '費用'],
+ // ... 他のパターン
+ };Also applies to: 1167-1182
🤖 Prompt for AI Agents
In src/mastra/agents/enhanced-qa-agent.ts around lines 1044 to 1072 and also
1167 to 1182, the pattern matching logic in extractRequestTypeFromQuestion and
detectSpecificRequest methods is duplicated. To fix this, extract the keyword
lists for each request type into shared constants or a single helper function
that both methods can use for matching. Refactor both methods to reference these
shared resources to eliminate redundancy and improve maintainability.
| let memoryContext; | ||
| if (this.sharedMemory) { | ||
| memoryContext = await this.sharedMemory.getContext(question, { | ||
| includeKnowledgeBase: false, | ||
| language: this.memory.get('language') || 'ja' | ||
| }); | ||
| } else { | ||
| memoryContext = await this.simplifiedMemory.getContext(question, { | ||
| includeKnowledgeBase: false, | ||
| language: this.memory.get('language') || 'ja' | ||
| }); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
新しいメソッドでのエラーハンドリング強化
新しく追加されたメモリ取得とメッセージ保存処理でエラーハンドリングが不足しています。サービスの可用性を向上させるため、適切なエラーハンドリングを追加してください。
+ try {
if (this.sharedMemory) {
memoryContext = await this.sharedMemory.getContext(question, {
includeKnowledgeBase: false,
language: this.memory.get('language') || 'ja'
});
} else {
memoryContext = await this.simplifiedMemory.getContext(question, {
includeKnowledgeBase: false,
language: this.memory.get('language') || 'ja'
});
}
+ } catch (error) {
+ console.error('[EnhancedQAAgent] Error in contextual response memory access:', error);
+ return false; // Safe fallback
+ }Also applies to: 1284-1293
🤖 Prompt for AI Agents
In src/mastra/agents/enhanced-qa-agent.ts around lines 942 to 953, the new
memory context retrieval lacks error handling, which risks unhandled exceptions
affecting service availability. Wrap the await calls to
this.sharedMemory.getContext and this.simplifiedMemory.getContext in try-catch
blocks, and handle errors appropriately by logging them and providing fallback
behavior if needed. Apply the same error handling pattern to the similar code at
lines 1284 to 1293.
| private async processContextualResponse( | ||
| clarificationAnswer: string, | ||
| originalContext: { originalQuestion: string; requestType: string | null }, | ||
| language: SupportedLanguage | ||
| ): Promise<string> { | ||
| console.log('[EnhancedQAAgent] Processing contextual response:', { | ||
| clarificationAnswer, | ||
| originalQuestion: originalContext.originalQuestion, | ||
| requestType: originalContext.requestType | ||
| }); | ||
|
|
||
| // Determine what the user is clarifying about | ||
| const isAboutSaino = clarificationAnswer.toLowerCase().includes('saino') || | ||
| clarificationAnswer.includes('才能') || | ||
| clarificationAnswer.includes('カフェ&バー') || | ||
| clarificationAnswer.includes('併設'); | ||
|
|
||
| const isAboutEngineerCafe = clarificationAnswer.includes('エンジニアカフェ') || | ||
| clarificationAnswer.includes('engineer cafe') || | ||
| clarificationAnswer.includes('コワーキング'); | ||
|
|
||
| // Build a specific query based on the original request type and clarification | ||
| let specificQuery = ''; | ||
|
|
||
| if (originalContext.requestType === 'hours') { | ||
| if (isAboutSaino) { | ||
| specificQuery = 'saino カフェ 営業時間'; | ||
| } else { | ||
| specificQuery = 'エンジニアカフェ 営業時間'; | ||
| } | ||
| } else if (originalContext.requestType === 'price') { | ||
| if (isAboutSaino) { | ||
| specificQuery = 'saino カフェ 料金 価格'; | ||
| } else { | ||
| specificQuery = 'エンジニアカフェ 利用料金'; | ||
| } | ||
| } else { | ||
| // General query combining original question and clarification | ||
| specificQuery = `${originalContext.originalQuestion} ${clarificationAnswer}`; | ||
| } | ||
|
|
||
| // Search for the specific information | ||
| const context = await this.searchKnowledgeBase(specificQuery, language); | ||
|
|
||
| // Build a focused response | ||
| const prompt = language === 'ja' | ||
| ? `ユーザーは「${originalContext.originalQuestion}」について尋ね、「${clarificationAnswer}」と明確にしました。${originalContext.requestType ? `${this.getRequestTypeInJapanese(originalContext.requestType)}のみ` : '質問された情報のみ'}を簡潔に答えてください。\n\n参考情報: ${context}` | ||
| : `The user asked about "${originalContext.originalQuestion}" and clarified with "${clarificationAnswer}". Provide only the ${originalContext.requestType || 'requested information'} concisely.\n\nContext: ${context}`; | ||
|
|
||
| const response = await this.generate([ | ||
| { role: 'user', content: prompt } | ||
| ]); | ||
|
|
||
| // Store the conversation | ||
| if (this.sharedMemory) { | ||
| await this.sharedMemory.addMessage('user', clarificationAnswer, { | ||
| agentName: 'EnhancedQAAgent', | ||
| requestType: originalContext.requestType, | ||
| isContextualResponse: true | ||
| }); | ||
| await this.sharedMemory.addMessage('assistant', response.text, { | ||
| agentName: 'EnhancedQAAgent' | ||
| }); | ||
| } | ||
|
|
||
| return EmotionTagParser.enhanceAgentResponse(response.text, 'qa', language); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
processContextualResponseメソッドの責任分離
このメソッドは複数の責任を持っており(コンテキスト判定、クエリ構築、検索実行、応答生成)、単一責任原則に違反しています。より小さな関数に分割することを推奨します。
+ private buildContextualQuery(originalContext: any, clarificationAnswer: string): string {
+ // クエリ構築ロジック
+ }
+
+ private async executeContextualSearch(query: string, language: SupportedLanguage): Promise<string> {
+ // 検索実行ロジック
+ }
+
+ private async generateContextualResponse(originalContext: any, clarificationAnswer: string, context: string, language: SupportedLanguage): Promise<string> {
+ // 応答生成ロジック
+ }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/mastra/agents/enhanced-qa-agent.ts around lines 1230 to 1296, the
processContextualResponse method handles multiple responsibilities including
context determination, query construction, knowledge base searching, and
response generation, violating the single responsibility principle. Refactor by
extracting distinct parts into smaller helper functions such as one for
determining clarification context (isAboutSaino, isAboutEngineerCafe), another
for building the specific query based on request type and clarification, and
possibly one for constructing the prompt. Then call these helpers from
processContextualResponse to keep it concise and focused.
| // Extract the specific request type from the previous conversation | ||
| const originalSpecificRequest = this.extractPreviousSpecificRequest(memoryContext.recentMessages); | ||
|
|
||
| if (originalSpecificRequest) { | ||
| // Get the specific information type that was requested | ||
| const requestTypePrompt = originalSpecificRequest === 'hours' | ||
| ? (language === 'en' ? 'operating hours' : '営業時間') | ||
| : originalSpecificRequest === 'price' | ||
| ? (language === 'en' ? 'pricing information' : '料金情報') | ||
| : originalSpecificRequest === 'location' | ||
| ? (language === 'en' ? 'location information' : '場所情報') | ||
| : originalSpecificRequest === 'booking' | ||
| ? (language === 'en' ? 'reservation/booking information' : '予約情報') | ||
| : originalSpecificRequest === 'facility' | ||
| ? (language === 'en' ? 'facility/equipment information' : '設備情報') | ||
| : originalSpecificRequest === 'access' | ||
| ? (language === 'en' ? 'access/directions' : 'アクセス方法') | ||
| : (language === 'en' ? 'requested information' : '要求された情報'); | ||
|
|
||
| // Use a focused prompt that specifically asks for the original request type | ||
| prompt = language === 'en' | ||
| ? `The user originally asked about ${requestTypePrompt} and is now clarifying which place they meant. Give ONLY the ${requestTypePrompt} for: ${question}\nContext: ${fullContext}\n\nIMPORTANT: Answer with ONLY the ${requestTypePrompt}. Do not include any other information about the place. Maximum 1 sentence.` | ||
| : `ユーザーは最初に${requestTypePrompt}について尋ね、今どの場所について聞いているか明確にしています。次の場所の${requestTypePrompt}のみを答えてください: ${question}\n文脈: ${fullContext}\n\n重要:${requestTypePrompt}のみを答えてください。その場所の他の情報は含めないでください。最大1文。`; | ||
| } else { | ||
| // Fallback to general contextual response if no specific request was found | ||
| prompt = language === 'en' | ||
| ? `The user is responding to a clarification question. Look at the conversation history to understand what they originally asked, then provide ONLY the specific information they originally requested: ${question}\nConversation History: ${conversationContext}\nContext: ${fullContext}\n\nIMPORTANT: Focus only on answering their original question. Do not provide general information about the place.` | ||
| : `ユーザーは明確化の質問に答えています。会話履歴から元の質問を理解し、最初に要求された特定の情報のみを提供してください: ${question}\n会話履歴: ${conversationContext}\n文脈: ${fullContext}\n\n重要:元の質問に答えることだけに焦点を当ててください。その場所の一般的な情報は提供しないでください。`; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
プロンプト構築ロジックのリファクタリング
プロンプト構築ロジックは包括的ですが、コードが冗長で保守性に課題があります。共通パターンをヘルパーメソッドに抽出することを推奨します。
+ private buildRequestTypePrompt(requestType: string, language: SupportedLanguage): string {
+ const typeMapping = {
+ 'hours': language === 'en' ? 'operating hours' : '営業時間',
+ 'price': language === 'en' ? 'pricing information' : '料金情報',
+ 'location': language === 'en' ? 'location information' : '場所情報',
+ // ... 他のマッピング
+ };
+ return typeMapping[requestType] || (language === 'en' ? 'requested information' : '要求された情報');
+ }Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/mastra/agents/enhanced-qa-agent.ts around lines 212 to 240, the prompt
construction logic is repetitive and hard to maintain due to multiple nested
ternary operators and duplicated language checks. Refactor by extracting the
mapping of originalSpecificRequest to requestTypePrompt into a helper method
that returns the correct prompt string based on the request type and language.
Also, create a helper function to build the final prompt string using parameters
like language, requestTypePrompt, question, and context to avoid duplication and
improve readability.
| // Post-process response to ensure it doesn't contain knowledge base tags | ||
| let cleanedResponse = response.text; | ||
|
|
||
| // Remove any square bracket tags that might have leaked through | ||
| cleanedResponse = cleanedResponse.replace(/\[[^\]]+\]\s*/g, ''); | ||
|
|
||
| // If this was a specific request, ensure the response is focused | ||
| if (isSpecificRequest && cleanedResponse.length > 150) { | ||
| // If response is too long for a specific request, extract the key information | ||
| const extractPrompt = language === 'en' | ||
| ? `Extract ONLY the specific answer from this text. Keep it to 1 sentence maximum: ${cleanedResponse}` | ||
| : `このテキストから特定の答えのみを抽出してください。最大1文にしてください: ${cleanedResponse}`; | ||
|
|
||
| const extractedResponse = await this.generate([ | ||
| { role: 'user', content: extractPrompt } | ||
| ]); | ||
|
|
||
| cleanedResponse = extractedResponse.text; | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
応答後処理のエラーハンドリング強化
応答のクリーニングと要約処理は適切ですが、generateメソッド呼び出し時のエラーハンドリングを追加してください。
if (isSpecificRequest && cleanedResponse.length > 150) {
const extractPrompt = language === 'en'
? `Extract ONLY the specific answer from this text. Keep it to 1 sentence maximum: ${cleanedResponse}`
: `このテキストから特定の答えのみを抽出してください。最大1文にしてください: ${cleanedResponse}`;
+ try {
const extractedResponse = await this.generate([
{ role: 'user', content: extractPrompt }
]);
cleanedResponse = extractedResponse.text;
+ } catch (error) {
+ console.error('[EnhancedQAAgent] Error extracting response:', error);
+ // Keep original response if extraction fails
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Post-process response to ensure it doesn't contain knowledge base tags | |
| let cleanedResponse = response.text; | |
| // Remove any square bracket tags that might have leaked through | |
| cleanedResponse = cleanedResponse.replace(/\[[^\]]+\]\s*/g, ''); | |
| // If this was a specific request, ensure the response is focused | |
| if (isSpecificRequest && cleanedResponse.length > 150) { | |
| // If response is too long for a specific request, extract the key information | |
| const extractPrompt = language === 'en' | |
| ? `Extract ONLY the specific answer from this text. Keep it to 1 sentence maximum: ${cleanedResponse}` | |
| : `このテキストから特定の答えのみを抽出してください。最大1文にしてください: ${cleanedResponse}`; | |
| const extractedResponse = await this.generate([ | |
| { role: 'user', content: extractPrompt } | |
| ]); | |
| cleanedResponse = extractedResponse.text; | |
| } | |
| // Post-process response to ensure it doesn't contain knowledge base tags | |
| let cleanedResponse = response.text; | |
| // Remove any square bracket tags that might have leaked through | |
| cleanedResponse = cleanedResponse.replace(/\[[^\]]+\]\s*/g, ''); | |
| // If this was a specific request, ensure the response is focused | |
| if (isSpecificRequest && cleanedResponse.length > 150) { | |
| // If response is too long for a specific request, extract the key information | |
| const extractPrompt = language === 'en' | |
| ? `Extract ONLY the specific answer from this text. Keep it to 1 sentence maximum: ${cleanedResponse}` | |
| : `このテキストから特定の答えのみを抽出してください。最大1文にしてください: ${cleanedResponse}`; | |
| try { | |
| const extractedResponse = await this.generate([ | |
| { role: 'user', content: extractPrompt } | |
| ]); | |
| cleanedResponse = extractedResponse.text; | |
| } catch (error) { | |
| console.error('[EnhancedQAAgent] Error extracting response:', error); | |
| // Keep original response if extraction fails | |
| } | |
| } |
🤖 Prompt for AI Agents
In src/mastra/agents/enhanced-qa-agent.ts around lines 296 to 314, the call to
this.generate for extracting a specific answer lacks error handling. Wrap the
await this.generate call in a try-catch block to catch any errors during
generation. In the catch block, log the error or handle it appropriately to
prevent unhandled promise rejections and ensure the method fails gracefully.
| // Get conversation context from shared memory if available, fallback to local memory | ||
| console.log(`[EnhancedQAAgent] Getting memory context for question: "${question}", language: ${language}`); | ||
|
|
||
| let memoryContext; | ||
| if (this.sharedMemory) { | ||
| // Use shared memory for better conversation continuity | ||
| // Get more messages to ensure we have the full conversation context | ||
| memoryContext = await this.sharedMemory.getContext(question, { | ||
| includeKnowledgeBase: false, | ||
| language: language | ||
| }); | ||
| console.log(`[EnhancedQAAgent] Using shared memory context`); | ||
| } else { | ||
| // Fallback to local memory | ||
| memoryContext = await this.simplifiedMemory.getContext(question, { | ||
| includeKnowledgeBase: false, | ||
| language: language | ||
| }); | ||
| console.log(`[EnhancedQAAgent] Using local memory context (shared memory not available)`); | ||
| } | ||
|
|
||
| console.log(`[EnhancedQAAgent] Memory context result:`, { | ||
| recentMessagesCount: memoryContext.recentMessages.length, | ||
| hasContext: !!memoryContext.contextString, | ||
| firstMessage: memoryContext.recentMessages[0] | ||
| }); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
メモリコンテキスト取得のエラーハンドリング強化
共有メモリとローカルメモリのフォールバック実装は適切ですが、getContextメソッド呼び出し時のエラーハンドリングを追加することを推奨します。
+ try {
if (this.sharedMemory) {
memoryContext = await this.sharedMemory.getContext(question, {
includeKnowledgeBase: false,
language: language
});
console.log(`[EnhancedQAAgent] Using shared memory context`);
} else {
memoryContext = await this.simplifiedMemory.getContext(question, {
includeKnowledgeBase: false,
language: language
});
console.log(`[EnhancedQAAgent] Using local memory context (shared memory not available)`);
}
+ } catch (error) {
+ console.error('[EnhancedQAAgent] Error getting memory context:', error);
+ memoryContext = { recentMessages: [], contextString: '' };
+ }🤖 Prompt for AI Agents
In src/mastra/agents/enhanced-qa-agent.ts around lines 61 to 86, the calls to
getContext on sharedMemory and simplifiedMemory lack error handling. Wrap each
getContext call in try-catch blocks to catch potential errors, log the error
details for debugging, and ensure the method gracefully falls back or handles
failures without crashing.
Summary by CodeRabbit
新機能
改善
ドキュメント
テスト
その他