bada-terminal / src /dev-preference-tracker.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
9.09 kB
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();