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();