File size: 9,094 Bytes
d739b1b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | 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();
|