const fs = require('fs'); const path = require('path'); const db = require('../knowledge-db'); const ctx = require('./context'); const configManager = require('./config-manager'); const preferenceModel = require('./services/workflow-preference-model'); const cliPaths = require('./config/cli-paths'); class DevPreferenceTracker { /** * Detect developer preferences from chat/session logs. * @param {string} projectId * @param {string} sessionLog */ async detectPreference(projectId, sessionLog, {run} = {}) { // 설명 문서: docs/specs/workflow-preference-learning.md v1.0.0 const assertActive=()=>preferenceModel.assertOwner(projectId,run);assertActive(); if (!sessionLog) return; const scope={workDir:run.workDir,wikiRoot:run.journal.getAbsWikiPath(),rulesSpec:{...(cliPaths.getCliPaths().rules||{filename:'.clauderules'})},assertActive}; let detected = []; let llmSuccess = false; // 1. Try LLM extraction try { const prompt = `개발자의 대화 세션 로그를 분석하여 코딩 스타일, 네이밍 규칙, 선호하는 라이브러리, 또는 에이전트에 대한 수정 및 피드백 명령을 분석하고 학습하십시오. 대화 로그: "${String(sessionLog).slice(0,65536)}" 반드시 다음 JSON 배열 형식으로만 응답하십시오. 설명이나 감탄사 없이 오직 JSON만 출력해야 합니다: [ { "category": "naming|style|pattern|library|prompt_rule", "preference_key": "선호도 키 (예: async_style)", "preference_value": "선호도 값 (예: async_await)", "confidence": 0.8, "source": "auto_inferred" } ]`; const messages = [{ role: 'user', content: prompt }]; const response = await preferenceModel.call(projectId,run,messages); if (response.success && response.text) { const jsonMatch = response.text.match(/\[\s*\{[\s\S]*\}\s*\]/); if (jsonMatch) { const values=JSON.parse(jsonMatch[0]); if(!Array.isArray(values)||values.length>64||values.some(p=>!p||!['naming','style','pattern','library','prompt_rule'].includes(p.category)||typeof p.preference_key!=='string'||!p.preference_key.trim()||p.preference_key.length>160||typeof p.preference_value!=='string'||!p.preference_value.trim()||p.preference_value.length>2000||typeof p.confidence!=='number'||!Number.isFinite(p.confidence)||p.confidence<0||p.confidence>1))throw Error('Invalid preference extraction'); detected = values.map(p=>({category:p.category,preference_key:p.preference_key,preference_value:p.preference_value,confidence:p.confidence,source:'auto_inferred'})); llmSuccess = true; } } } catch (e) { assertActive(); if(e.code)throw e; console.warn('[DevPreferenceTracker] 선호 응답을 확인하지 못해 로컬 패턴을 사용합니다.'); } // 2. Fallback to pattern matching if (!llmSuccess || detected.length === 0) { const lowerLog = sessionLog.toLowerCase(); if (lowerLog.includes('async/await') || lowerLog.includes('async-await')) { detected.push({ category: 'pattern', preference_key: 'async_style', preference_value: 'async_await', confidence: 0.8, source: 'auto_inferred' }); } if (lowerLog.includes('camelcase') || lowerLog.includes('카멜케이스')) { detected.push({ category: 'naming', preference_key: 'variable_naming_convention', preference_value: 'camelCase', confidence: 0.9, source: 'auto_inferred' }); } if (lowerLog.includes('error handling') || lowerLog.includes('예외 처리')) { detected.push({ category: 'pattern', preference_key: 'error_handling', preference_value: 'mandatory', confidence: 0.7, source: 'auto_inferred' }); } } // 3. Save to DB for (const pref of detected) { assertActive(); await db.saveDevPreference(projectId, pref); } // 4. Sync files assertActive();await this.syncToWiki(projectId,scope); assertActive();const synced=await this.syncToClaudeRules(projectId,scope); if(synced?.success===false)throw Object.assign(Error('학습 규칙 파일 동기화를 확인해주세요.'),{code:'PREFERENCE_SYNC_FAILED'}); assertActive(); } /** * 프로젝트의 CLI 네이티브 규칙과 레거시 호환 구역에 선호를 반영한다. * @param {string} projectId */ async syncToClaudeRules(projectId, {workDir,assertActive=()=>{},rulesSpec=cliPaths.getCliPaths().rules||{filename:'.clauderules'}} = {}) { const targets = [...new Set([rulesSpec.filename, rulesSpec.legacyFilename].filter(Boolean))]; try { // Find project path from registration let projectPath=workDir; if(!projectPath){const prefs=await db.getDevPreferences('global','project_config'),p=prefs.find(p=>p.preference_key===`project_${projectId}`);if(!p)return;projectPath=JSON.parse(p.preference_value).path;} assertActive(); if (!fs.existsSync(projectPath)) return; const projectPrefs = await db.getDevPreferences(projectId); assertActive(); const highConfPrefs = projectPrefs.filter(p => p.confidence >= 0.7); if (highConfPrefs.length === 0) { require('./utils/managed-rule-files').apply(projectPath, targets, null, { kind: 'preferences' }); return { success: true, cleared: true }; } let rulesText = `# BADA Terminal Auto-Learned Coding Rules\n\n`; rulesText += `> [!NOTE]\n> 이 규칙들은 개발자의 코딩 선호도를 바탕으로 BADA Terminal에 의해 자동 학습된 규칙입니다.\n\n`; const categories = ['naming', 'style', 'pattern', 'library', 'prompt_rule']; categories.forEach(cat => { const catPrefs = highConfPrefs.filter(p => p.category === cat); if (catPrefs.length > 0) { rulesText += `## ${cat.toUpperCase()}\n`; catPrefs.forEach(p => { rulesText += `- **${p.preference_key}**: \`${p.preference_value}\` (신뢰도: ${p.confidence})\n`; }); rulesText += `\n`; } }); const paths = require('./utils/managed-rule-files').apply(projectPath, targets, rulesText, { kind: 'preferences' }); // 프로젝트에서 추론한 선호로 다른 프로젝트가 공유하는 전역 Gemini 규칙을 바꾸지 않는다. return { success: true, path: paths[0], paths }; } catch (e) { console.error('[DevPreferenceTracker] Failed to sync learned rules:', e.message); return { success: false, error: e.message }; } } /** * Generate/update developer preferences wiki page. * @param {string} projectId */ async syncToWiki(projectId, {workDir,wikiRoot,assertActive=()=>{}} = {}) { try { const kConfig = configManager.getKnowledgeConfig(); const wikiPath = kConfig.wikiPath || 'wiki'; const absWikiPath = wikiRoot || (path.isAbsolute(wikiPath) ? wikiPath : path.resolve(workDir || ctx.currentCwd || process.cwd(), wikiPath)); const filePath = path.join(absWikiPath, 'developer_preferences.md'); const projectPrefs = await db.getDevPreferences(projectId); assertActive(); let content = `--- title: "개발자 코딩 선호 지식" description: "개발 과정에서 BADA Terminal이 학습한 스타일 및 코딩 패턴" tags: ["developer-preference", "coding-standard"] --- # 🧬 개발자 코딩 선호 지식베이스 이 문서는 개발자의 피드백과 코드 교정 로그로부터 자동으로 도출된 코딩 스타일과 패턴 규칙 선호도 데이터입니다. ## 📋 학습된 선호 규칙 목록 | 카테고리 | 선호도 Key | 선호도 Value | 신뢰도 | 추출 소스 | 마지막 학습 시간 | |---|---|---|---|---|---| `; projectPrefs.forEach(p => { content += `| ${p.category.toUpperCase()} | \`${p.preference_key}\` | \`${p.preference_value}\` | ${p.confidence} | \`${p.source}\` | ${p.updated_at || p.created_at} |\n`; }); fs.mkdirSync(absWikiPath,{recursive:true});fs.writeFileSync(filePath, content, 'utf-8'); // Update parent index.md const parentIndexPath = path.join(absWikiPath, 'index.md'); if (fs.existsSync(parentIndexPath)) { let parentIndex = fs.readFileSync(parentIndexPath, 'utf-8'); const linkMarker = `[🧬 BADA 개발자 코딩 선호 지식]`; if (!parentIndex.includes(linkMarker)) { parentIndex += `\n- ${linkMarker}(developer_preferences.md) - 에이전트가 학습한 개발자 코딩 규칙 선호도 모음\n`; fs.writeFileSync(parentIndexPath, parentIndex, 'utf-8'); } } } catch (e) { console.error('[DevPreferenceTracker] Failed to sync preferences to wiki:', e); if(workDir||wikiRoot)throw Object.assign(Error('학습 Wiki 파일 동기화를 확인해주세요.'),{code:'PREFERENCE_SYNC_FAILED'}); } } } module.exports = new DevPreferenceTracker();