@triflux/core 10.1.0 → 10.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/hooks/agent-route-guard.mjs +14 -10
  2. package/hooks/cross-review-tracker.mjs +21 -8
  3. package/hooks/error-context.mjs +20 -8
  4. package/hooks/hook-adaptive-collector.mjs +18 -16
  5. package/hooks/hook-manager.mjs +93 -32
  6. package/hooks/hook-orchestrator.mjs +267 -35
  7. package/hooks/hook-registry.json +343 -256
  8. package/hooks/hooks.json +49 -1
  9. package/hooks/keyword-rules.json +191 -31
  10. package/hooks/lib/resolve-root.mjs +1 -1
  11. package/hooks/mcp-config-watcher.mjs +6 -2
  12. package/hooks/permission-safe-allow.mjs +233 -0
  13. package/hooks/pipeline-stop.mjs +369 -22
  14. package/hooks/post-tool-tips.mjs +306 -0
  15. package/hooks/pre-compact-snapshot.mjs +181 -0
  16. package/hooks/safety-guard.mjs +262 -34
  17. package/hooks/session-end-cleanup.mjs +345 -0
  18. package/hooks/session-start-fast.mjs +214 -0
  19. package/hooks/subagent-tracker.mjs +267 -0
  20. package/hooks/subagent-verifier.mjs +9 -4
  21. package/hub/account-broker.mjs +1036 -66
  22. package/hub/adaptive-diagnostic.mjs +75 -48
  23. package/hub/adaptive-inject.mjs +96 -58
  24. package/hub/adaptive-memory.mjs +156 -42
  25. package/hub/adaptive.mjs +60 -31
  26. package/hub/assign-callbacks.mjs +163 -126
  27. package/hub/bridge.mjs +1051 -290
  28. package/hub/cli-adapter-base.mjs +321 -97
  29. package/hub/codex-adapter.mjs +179 -93
  30. package/hub/codex-compat.mjs +4 -4
  31. package/hub/codex-preflight.mjs +113 -37
  32. package/hub/delegator/contracts.mjs +22 -21
  33. package/hub/delegator/index.mjs +14 -14
  34. package/hub/delegator/schema/delegator-tools.schema.json +1 -1
  35. package/hub/delegator/service.mjs +93 -64
  36. package/hub/delegator/tool-definitions.mjs +35 -35
  37. package/hub/dynamic-routing-engine.mjs +511 -0
  38. package/hub/fullcycle.mjs +34 -18
  39. package/hub/gemini-adapter.mjs +82 -108
  40. package/hub/hitl.mjs +202 -143
  41. package/hub/intent.mjs +167 -38
  42. package/hub/lib/bash-path.mjs +73 -0
  43. package/hub/lib/cache-guard.mjs +43 -17
  44. package/hub/lib/env-detect.mjs +145 -0
  45. package/hub/lib/hosts-compat.mjs +319 -0
  46. package/hub/lib/mcp-response-cache.mjs +239 -0
  47. package/hub/lib/memory-store.mjs +285 -111
  48. package/hub/lib/path-utils.mjs +165 -0
  49. package/hub/lib/phase-manager.mjs +493 -0
  50. package/hub/lib/process-utils.mjs +797 -104
  51. package/hub/lib/prompt-tmp.mjs +33 -0
  52. package/hub/lib/risk-tier.mjs +53 -0
  53. package/hub/lib/spawn-trace.mjs +561 -0
  54. package/hub/lib/ssh-command.mjs +44 -24
  55. package/hub/lib/ssh-retry.mjs +5 -1
  56. package/hub/lib/staged-file-detect.mjs +43 -0
  57. package/hub/lib/state-snapshot.mjs +293 -0
  58. package/hub/lib/tfx-route-args.mjs +309 -0
  59. package/hub/lib/timeline-adapter.mjs +190 -0
  60. package/hub/lib/trace-recorder.mjs +153 -0
  61. package/hub/lib/uuidv7.mjs +4 -3
  62. package/hub/memory-doctor.mjs +266 -106
  63. package/hub/middleware/quota-middleware.mjs +70 -0
  64. package/hub/middleware/request-logger.mjs +61 -34
  65. package/hub/paths.mjs +9 -9
  66. package/hub/pipeline/gates/confidence.mjs +34 -15
  67. package/hub/pipeline/gates/consensus.mjs +27 -15
  68. package/hub/pipeline/gates/index.mjs +7 -3
  69. package/hub/pipeline/gates/selfcheck.mjs +57 -19
  70. package/hub/pipeline/index.mjs +77 -42
  71. package/hub/pipeline/state.mjs +10 -10
  72. package/hub/pipeline/transitions.mjs +40 -23
  73. package/hub/platform.mjs +65 -48
  74. package/hub/quality/deslop.mjs +70 -49
  75. package/hub/reflexion.mjs +87 -13
  76. package/hub/research.mjs +33 -25
  77. package/hub/router.mjs +941 -791
  78. package/hub/routing/complexity.mjs +132 -29
  79. package/hub/routing/index.mjs +17 -12
  80. package/hub/routing/q-learning.mjs +78 -30
  81. package/hub/routing-snapshot.mjs +261 -0
  82. package/hub/session-fingerprint.mjs +127 -61
  83. package/hub/state.mjs +86 -44
  84. package/hub/team/claude-daemon-control.mjs +1130 -0
  85. package/hub/team/retry-state-machine.mjs +336 -0
  86. package/hub/token-mode.mjs +72 -71
  87. package/hub/workers/worker-utils.mjs +23 -17
  88. package/hud/colors.mjs +27 -9
  89. package/hud/constants.mjs +190 -27
  90. package/hud/context-monitor.mjs +133 -44
  91. package/hud/hud-qos-status.mjs +157 -50
  92. package/hud/mission-board.mjs +56 -0
  93. package/hud/providers/claude.mjs +398 -114
  94. package/hud/providers/codex.mjs +96 -21
  95. package/hud/providers/gemini.mjs +210 -52
  96. package/hud/renderers.mjs +440 -127
  97. package/hud/terminal.mjs +101 -31
  98. package/hud/utils.mjs +81 -39
  99. package/mesh/index.mjs +69 -0
  100. package/mesh/mesh-budget.mjs +137 -0
  101. package/mesh/mesh-heartbeat.mjs +100 -0
  102. package/mesh/mesh-protocol.mjs +96 -0
  103. package/mesh/mesh-queue.mjs +163 -0
  104. package/mesh/mesh-registry.mjs +78 -0
  105. package/mesh/mesh-router.mjs +77 -0
  106. package/package.json +5 -1
  107. package/scripts/lib/agent-json.mjs +27 -0
  108. package/scripts/lib/async.mjs +174 -0
  109. package/scripts/lib/claudemd-scanner.mjs +6 -1
  110. package/scripts/lib/cli-agy.mjs +62 -0
  111. package/scripts/lib/cli-claude.mjs +78 -0
  112. package/scripts/lib/cli-codex.mjs +199 -0
  113. package/scripts/lib/cli-gemini.mjs +37 -0
  114. package/scripts/lib/codex-recovery.sh +50 -0
  115. package/scripts/lib/context.mjs +3 -3
  116. package/scripts/lib/cross-review-utils.mjs +13 -5
  117. package/scripts/lib/doctor-env-checks.mjs +121 -0
  118. package/scripts/lib/dynamic-route-cli.mjs +107 -0
  119. package/scripts/lib/env-probe.mjs +58 -30
  120. package/scripts/lib/env.mjs +14 -0
  121. package/scripts/lib/gemini-profiles.mjs +44 -10
  122. package/scripts/lib/handoff.mjs +33 -17
  123. package/scripts/lib/hook-utils.mjs +8 -6
  124. package/scripts/lib/hub.mjs +48 -0
  125. package/scripts/lib/keyword-rules.mjs +49 -20
  126. package/scripts/lib/logger.mjs +24 -24
  127. package/scripts/lib/mcp-filter.mjs +391 -247
  128. package/scripts/lib/mcp-gateway-health-check.mjs +159 -0
  129. package/scripts/lib/mcp-gateway-servers.mjs +70 -0
  130. package/scripts/lib/mcp-gateway-wrapper-check.mjs +35 -0
  131. package/scripts/lib/mcp-guard-engine.mjs +1281 -115
  132. package/scripts/lib/mcp-health.mjs +773 -0
  133. package/scripts/lib/mcp-manifest.mjs +24 -14
  134. package/scripts/lib/mcp-server-catalog.mjs +355 -118
  135. package/scripts/lib/pid.mjs +63 -0
  136. package/scripts/lib/process-utils.mjs +26 -0
  137. package/scripts/lib/psmux-info.mjs +117 -12
  138. package/scripts/lib/quota.mjs +47 -0
  139. package/scripts/lib/remote-spawn-transfer.mjs +44 -14
  140. package/scripts/lib/skill-state.mjs +220 -0
  141. package/scripts/lib/skill-template.mjs +32 -7
  142. package/scripts/lib/team.mjs +75 -0
  143. package/scripts/lib/timeout.mjs +66 -0
  144. package/scripts/lib/tmp.mjs +26 -0
  145. package/scripts/lib/toml.mjs +113 -0
@@ -3,57 +3,59 @@
3
3
  * AI 생성 코드에서 불필요한 요소를 자동 탐지/제거하는 정적 분석 모듈
4
4
  */
5
5
 
6
- import { readdir, readFile, writeFile, stat } from 'node:fs/promises';
7
- import { join, } from 'node:path';
6
+ import { readdir, readFile, stat, writeFile } from "node:fs/promises";
7
+ import { join } from "node:path";
8
8
 
9
9
  /** @type {ReadonlyArray<{type: string, pattern: RegExp, severity: string, autoFixable: boolean, multiline: boolean}>} */
10
10
  export const SLOP_PATTERNS = Object.freeze([
11
11
  {
12
- type: 'trivial_comment',
12
+ type: "trivial_comment",
13
13
  pattern: /^\s*\/\/\s*(import|define|set|get|return|export)\s/i,
14
- severity: 'low',
14
+ severity: "low",
15
15
  autoFixable: true,
16
16
  multiline: false,
17
17
  },
18
18
  {
19
- type: 'empty_catch',
19
+ type: "empty_catch",
20
20
  pattern: /catch\s*\([^)]*\)\s*\{\s*\}/,
21
- severity: 'med',
21
+ severity: "med",
22
22
  autoFixable: false,
23
23
  multiline: true,
24
24
  },
25
25
  {
26
- type: 'console_debug',
26
+ type: "console_debug",
27
27
  pattern: /^\s*console\.(log|debug|info)\(/,
28
- severity: 'low',
28
+ severity: "low",
29
29
  autoFixable: true,
30
30
  multiline: false,
31
31
  },
32
32
  {
33
- type: 'useless_jsdoc',
33
+ type: "useless_jsdoc",
34
34
  pattern: /\/\*\*\s*\n\s*\*\s*\n\s*\*\//,
35
- severity: 'low',
35
+ severity: "low",
36
36
  autoFixable: true,
37
37
  multiline: true,
38
38
  },
39
39
  {
40
- type: 'rethrow_only',
40
+ type: "rethrow_only",
41
41
  pattern: /catch\s*\((\w+)\)\s*\{\s*throw\s+\1\s*;?\s*\}/,
42
- severity: 'med',
42
+ severity: "med",
43
43
  autoFixable: false,
44
44
  multiline: true,
45
45
  },
46
46
  {
47
- type: 'redundant_type',
48
- pattern: /:\s*(string|number|boolean)\s*=\s*('[^']*'|"[^"]*"|\d+|true|false)/,
49
- severity: 'low',
47
+ type: "redundant_type",
48
+ pattern:
49
+ /:\s*(string|number|boolean)\s*=\s*('[^']*'|"[^"]*"|\d+|true|false)/,
50
+ severity: "low",
50
51
  autoFixable: false,
51
52
  multiline: false,
52
53
  },
53
54
  {
54
- type: 'commented_code',
55
- pattern: /^\s*\/\/\s*(const |let |var |function |class |if\s*\(|for\s*\(|while\s*\(|return |await )/,
56
- severity: 'low',
55
+ type: "commented_code",
56
+ pattern:
57
+ /^\s*\/\/\s*(const |let |var |function |class |if\s*\(|for\s*\(|while\s*\(|return |await )/,
58
+ severity: "low",
57
59
  autoFixable: true,
58
60
  multiline: false,
59
61
  },
@@ -67,8 +69,8 @@ const SEVERITY_WEIGHT = { low: 2, med: 5 };
67
69
  * @param {string} [filePath] - 파일 경로 (보고용)
68
70
  * @returns {{ issues: Array<{line: number, type: string, severity: string, suggestion: string, text: string, autoFixable: boolean}>, score: number }}
69
71
  */
70
- export function detectSlop(content, filePath = '') {
71
- const lines = content.split('\n');
72
+ export function detectSlop(content, filePath = "") {
73
+ const lines = content.split("\n");
72
74
  const issues = [];
73
75
 
74
76
  for (const sp of SLOP_PATTERNS) {
@@ -90,16 +92,19 @@ export function detectSlop(content, filePath = '') {
90
92
 
91
93
  for (const sp of SLOP_PATTERNS) {
92
94
  if (!sp.multiline) continue;
93
- const regex = new RegExp(sp.pattern.source, sp.pattern.flags.replace('g', '') + 'g');
95
+ const regex = new RegExp(
96
+ sp.pattern.source,
97
+ sp.pattern.flags.replace("g", "") + "g",
98
+ );
94
99
  let match;
95
100
  while ((match = regex.exec(content)) !== null) {
96
- const line = content.substring(0, match.index).split('\n').length;
101
+ const line = content.substring(0, match.index).split("\n").length;
97
102
  issues.push({
98
103
  line,
99
104
  type: sp.type,
100
105
  severity: sp.severity,
101
106
  suggestion: `${sp.type} 패턴 감지`,
102
- text: match[0].split('\n')[0].trim(),
107
+ text: match[0].split("\n")[0].trim(),
103
108
  autoFixable: sp.autoFixable,
104
109
  file: filePath,
105
110
  });
@@ -108,7 +113,10 @@ export function detectSlop(content, filePath = '') {
108
113
 
109
114
  issues.sort((a, b) => a.line - b.line);
110
115
 
111
- const totalPenalty = issues.reduce((sum, i) => sum + (SEVERITY_WEIGHT[i.severity] || 2), 0);
116
+ const totalPenalty = issues.reduce(
117
+ (sum, i) => sum + (SEVERITY_WEIGHT[i.severity] || 2),
118
+ 0,
119
+ );
112
120
  const score = Math.max(0, 100 - totalPenalty);
113
121
 
114
122
  return { issues, score };
@@ -121,9 +129,10 @@ export function detectSlop(content, filePath = '') {
121
129
  * @returns {{ fixed: string, applied: number, skipped: number }}
122
130
  */
123
131
  export function autoFixSlop(content, issues) {
124
- if (!issues || issues.length === 0) return { fixed: content, applied: 0, skipped: 0 };
132
+ if (!issues || issues.length === 0)
133
+ return { fixed: content, applied: 0, skipped: 0 };
125
134
 
126
- const fixable = issues.filter(i => i.autoFixable);
135
+ const fixable = issues.filter((i) => i.autoFixable);
127
136
  const skipped = issues.length - fixable.length;
128
137
 
129
138
  if (fixable.length === 0) return { fixed: content, applied: 0, skipped };
@@ -132,10 +141,10 @@ export function autoFixSlop(content, issues) {
132
141
  let applied = 0;
133
142
 
134
143
  // Multi-line: useless_jsdoc 제거
135
- if (fixable.some(i => i.type === 'useless_jsdoc')) {
144
+ if (fixable.some((i) => i.type === "useless_jsdoc")) {
136
145
  const matches = fixed.match(/\/\*\*\s*\n\s*\*\s*\n\s*\*\/\n?/g);
137
146
  if (matches) {
138
- fixed = fixed.replace(/\/\*\*\s*\n\s*\*\s*\n\s*\*\/\n?/g, '');
147
+ fixed = fixed.replace(/\/\*\*\s*\n\s*\*\s*\n\s*\*\/\n?/g, "");
139
148
  applied += matches.length;
140
149
  }
141
150
  }
@@ -143,13 +152,15 @@ export function autoFixSlop(content, issues) {
143
152
  // Line-level: trivial_comment, console_debug, commented_code 제거
144
153
  const lineTypes = new Set(
145
154
  fixable
146
- .filter(i => ['trivial_comment', 'console_debug', 'commented_code'].includes(i.type))
147
- .map(i => i.type),
155
+ .filter((i) =>
156
+ ["trivial_comment", "console_debug", "commented_code"].includes(i.type),
157
+ )
158
+ .map((i) => i.type),
148
159
  );
149
160
 
150
161
  if (lineTypes.size > 0) {
151
- const linePatterns = SLOP_PATTERNS.filter(p => lineTypes.has(p.type));
152
- const lines = fixed.split('\n');
162
+ const linePatterns = SLOP_PATTERNS.filter((p) => lineTypes.has(p.type));
163
+ const lines = fixed.split("\n");
153
164
  const result = [];
154
165
  for (const line of lines) {
155
166
  let remove = false;
@@ -162,23 +173,23 @@ export function autoFixSlop(content, issues) {
162
173
  }
163
174
  if (!remove) result.push(line);
164
175
  }
165
- fixed = result.join('\n');
176
+ fixed = result.join("\n");
166
177
  }
167
178
 
168
179
  return { fixed, applied, skipped };
169
180
  }
170
181
 
171
182
  function matchesGlob(filePath, pattern) {
172
- const normalized = '/' + filePath.replace(/\\/g, '/');
183
+ const normalized = "/" + filePath.replace(/\\/g, "/");
173
184
 
174
185
  // **/*.ext → 확장자 매칭
175
- if (pattern.startsWith('**/*.')) {
186
+ if (pattern.startsWith("**/*.")) {
176
187
  const ext = pattern.slice(4);
177
188
  return normalized.endsWith(ext);
178
189
  }
179
190
 
180
191
  // *.ext → 확장자 매칭 (디렉토리 무관)
181
- if (pattern.startsWith('*.') && !pattern.includes('/')) {
192
+ if (pattern.startsWith("*.") && !pattern.includes("/")) {
182
193
  const ext = pattern.slice(1);
183
194
  return normalized.endsWith(ext);
184
195
  }
@@ -186,7 +197,7 @@ function matchesGlob(filePath, pattern) {
186
197
  // **/dir/** → 디렉토리 포함 여부
187
198
  const dirMatch = pattern.match(/^\*\*\/([^*]+)\/\*\*$/);
188
199
  if (dirMatch) {
189
- return normalized.includes('/' + dirMatch[1] + '/');
200
+ return normalized.includes("/" + dirMatch[1] + "/");
190
201
  }
191
202
 
192
203
  return false;
@@ -203,8 +214,8 @@ function matchesGlob(filePath, pattern) {
203
214
  */
204
215
  export async function scanDirectory(dirPath, opts = {}) {
205
216
  const {
206
- include = ['**/*.mjs', '**/*.js', '**/*.ts'],
207
- exclude = ['**/node_modules/**', '**/dist/**', '**/.git/**'],
217
+ include = ["**/*.mjs", "**/*.js", "**/*.ts"],
218
+ exclude = ["**/node_modules/**", "**/dist/**", "**/.git/**"],
208
219
  autoFix = false,
209
220
  } = opts;
210
221
 
@@ -212,32 +223,37 @@ export async function scanDirectory(dirPath, opts = {}) {
212
223
  const files = [];
213
224
 
214
225
  for (const entry of entries) {
215
- const normalized = entry.replace(/\\/g, '/');
226
+ const normalized = entry.replace(/\\/g, "/");
216
227
  const fullPath = join(dirPath, entry);
217
228
 
218
229
  let st;
219
- try { st = await stat(fullPath); } catch { continue; }
230
+ try {
231
+ st = await stat(fullPath);
232
+ } catch {
233
+ continue;
234
+ }
220
235
  if (!st.isFile()) continue;
221
236
 
222
- const included = include.some(p => matchesGlob(normalized, p));
223
- const excluded = exclude.some(p => matchesGlob(normalized, p));
237
+ const included = include.some((p) => matchesGlob(normalized, p));
238
+ const excluded = exclude.some((p) => matchesGlob(normalized, p));
224
239
  if (!included || excluded) continue;
225
240
 
226
- const fileContent = await readFile(fullPath, 'utf-8');
241
+ const fileContent = await readFile(fullPath, "utf-8");
227
242
  const { issues, score } = detectSlop(fileContent, normalized);
228
243
 
229
244
  if (autoFix && issues.length > 0) {
230
245
  const { fixed, applied } = autoFixSlop(fileContent, issues);
231
- if (applied > 0) await writeFile(fullPath, fixed, 'utf-8');
246
+ if (applied > 0) await writeFile(fullPath, fixed, "utf-8");
232
247
  }
233
248
 
234
249
  files.push({ path: normalized, issues, score });
235
250
  }
236
251
 
237
252
  const totalIssues = files.reduce((sum, f) => sum + f.issues.length, 0);
238
- const avgScore = files.length > 0
239
- ? Math.round(files.reduce((sum, f) => sum + f.score, 0) / files.length)
240
- : 100;
253
+ const avgScore =
254
+ files.length > 0
255
+ ? Math.round(files.reduce((sum, f) => sum + f.score, 0) / files.length)
256
+ : 100;
241
257
 
242
258
  const byType = {};
243
259
  for (const f of files) {
@@ -248,6 +264,11 @@ export async function scanDirectory(dirPath, opts = {}) {
248
264
 
249
265
  return {
250
266
  files,
251
- summary: { totalFiles: files.length, totalIssues, averageScore: avgScore, byType },
267
+ summary: {
268
+ totalFiles: files.length,
269
+ totalIssues,
270
+ averageScore: avgScore,
271
+ byType,
272
+ },
252
273
  };
253
274
  }
package/hub/reflexion.mjs CHANGED
@@ -8,7 +8,7 @@ const ACTIVE_RULE_CONFIDENCE = 0.5;
8
8
  const ADAPTIVE_PROMOTION_STEP = 0.1;
9
9
  const ADAPTIVE_DECAY_STEP = 0.1;
10
10
  /** @deprecated 세션 기반 decay에서 시간 기반으로 변경됨. 미사용. */
11
- const ADAPTIVE_DECAY_WINDOW = 5;
11
+ const _ADAPTIVE_DECAY_WINDOW = 5;
12
12
  const ADAPTIVE_DELETE_THRESHOLD = 0.3;
13
13
 
14
14
  function clampConfidence(value) {
@@ -129,7 +129,7 @@ function getAdaptiveState(rule = {}) {
129
129
  }
130
130
 
131
131
  /** @deprecated reflexion_entries 기반. adaptive_rules에서는 미사용. 세션 인식 복원 시 재활용 예정. */
132
- function mergeAdaptiveState(rule, errorContext = {}) {
132
+ function _mergeAdaptiveState(rule, errorContext = {}) {
133
133
  const current = getAdaptiveState(rule);
134
134
  const sessionId = pickSessionId(errorContext);
135
135
  const sessionCount = pickSessionCount(
@@ -163,6 +163,63 @@ function filterEntriesByType(entries, type) {
163
163
  );
164
164
  }
165
165
 
166
+ function parseAdaptiveRuleId(ruleId, projectSlug = "") {
167
+ const value = pickString(ruleId);
168
+ if (!value) return null;
169
+ const nulSeparator = value.indexOf("\u0000");
170
+ if (nulSeparator > 0) {
171
+ return {
172
+ project_slug: value.slice(0, nulSeparator),
173
+ pattern: value.slice(nulSeparator + 1),
174
+ };
175
+ }
176
+ if (projectSlug && value.startsWith(`${projectSlug}:`)) {
177
+ return {
178
+ project_slug: projectSlug,
179
+ pattern: value.slice(projectSlug.length + 1),
180
+ };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ function resolveAdaptiveRuleIdentity(
186
+ ruleIdOrProjectSlug,
187
+ patternOrErrorContext,
188
+ ) {
189
+ if (typeof patternOrErrorContext === "string") {
190
+ return {
191
+ project_slug: pickString(ruleIdOrProjectSlug),
192
+ pattern: pickString(patternOrErrorContext),
193
+ };
194
+ }
195
+
196
+ const errorContext =
197
+ patternOrErrorContext && typeof patternOrErrorContext === "object"
198
+ ? patternOrErrorContext
199
+ : {};
200
+ const projectSlug = pickString(pickProjectSlug(errorContext));
201
+ const fromRuleId = parseAdaptiveRuleId(ruleIdOrProjectSlug, projectSlug);
202
+ const errorText = pickString(
203
+ errorContext.error_pattern,
204
+ errorContext.pattern,
205
+ errorContext.error,
206
+ errorContext.errorText,
207
+ errorContext.errorMessage,
208
+ buildErrorText(errorContext),
209
+ );
210
+ const pattern = pickString(normalizeError(errorText), fromRuleId?.pattern);
211
+ return {
212
+ project_slug: pickString(projectSlug, fromRuleId?.project_slug),
213
+ pattern,
214
+ };
215
+ }
216
+
217
+ function listAdaptiveRulesFromStore(store, projectSlug) {
218
+ if (!store?.listAdaptiveRules) return [];
219
+ const rules = store.listAdaptiveRules(projectSlug);
220
+ return Array.isArray(rules) ? rules : [];
221
+ }
222
+
166
223
  /**
167
224
  * 에러 메시지를 정규화된 패턴 시그니처로 변환
168
225
  * 파일 경로, 줄 번호, 타임스탬프, UUID, 숫자 리터럴을 플레이스홀더로 치환
@@ -287,17 +344,28 @@ export function adaptiveRuleFromError(errorContext = {}) {
287
344
 
288
345
  /**
289
346
  * 동일 패턴이 여러 세션에서 재발하면 adaptive rule confidence를 승격
347
+ * 현재 (projectSlug, pattern)과 구형 (ruleId, errorContext) 시그니처를 모두 지원한다.
290
348
  * @param {object} store — store-adapter 인스턴스 (findAdaptiveRule, updateRuleConfidence 필요)
291
- * @param {string} projectSlug
292
- * @param {string} pattern
349
+ * @param {string} ruleIdOrProjectSlug
350
+ * @param {object|string} patternOrErrorContext
293
351
  * @returns {object|null}
294
352
  */
295
- export function promoteRule(store, projectSlug, pattern) {
353
+ export function promoteRule(store, ruleIdOrProjectSlug, patternOrErrorContext) {
296
354
  if (!store.findAdaptiveRule || !store.updateRuleConfidence) return null;
297
- const rule = store.findAdaptiveRule(projectSlug, pattern);
355
+ const identity = resolveAdaptiveRuleIdentity(
356
+ ruleIdOrProjectSlug,
357
+ patternOrErrorContext,
358
+ );
359
+ if (!identity.project_slug || !identity.pattern) return null;
360
+ const rule = store.findAdaptiveRule(identity.project_slug, identity.pattern);
298
361
  if (!rule) return null;
299
362
  const promoted = clampConfidence(rule.confidence + ADAPTIVE_PROMOTION_STEP);
300
- return store.updateRuleConfidence(projectSlug, pattern, promoted, { hit_count_increment: 1 });
363
+ return store.updateRuleConfidence(
364
+ identity.project_slug,
365
+ identity.pattern,
366
+ promoted,
367
+ { hit_count_increment: 1 },
368
+ );
301
369
  }
302
370
 
303
371
  /**
@@ -310,10 +378,11 @@ export function promoteRule(store, projectSlug, pattern) {
310
378
  export function decayRules(store, _sessionCount, projectSlug) {
311
379
  if (!store.listAdaptiveRules) return { updated: [], deleted: [] };
312
380
  const result = { updated: [], deleted: [] };
313
- const rules = store.listAdaptiveRules(projectSlug);
381
+ const rules = listAdaptiveRulesFromStore(store, projectSlug);
314
382
  for (const rule of rules) {
315
383
  // 7일 이상 미관측된 규칙만 decay 대상
316
- const ageDays = (Date.now() - (rule.last_seen_ms || 0)) / (24 * 3600 * 1000);
384
+ const ageDays =
385
+ (Date.now() - (rule.last_seen_ms || 0)) / (24 * 3600 * 1000);
317
386
  if (ageDays < 7) continue;
318
387
  const decayed = clampConfidence(rule.confidence - ADAPTIVE_DECAY_STEP);
319
388
  if (decayed <= ADAPTIVE_DELETE_THRESHOLD) {
@@ -323,7 +392,12 @@ export function decayRules(store, _sessionCount, projectSlug) {
323
392
  continue;
324
393
  }
325
394
  if (decayed < rule.confidence) {
326
- const updated = store.updateRuleConfidence(rule.project_slug, rule.pattern, decayed, { hit_count_increment: 0 });
395
+ const updated = store.updateRuleConfidence(
396
+ rule.project_slug,
397
+ rule.pattern,
398
+ decayed,
399
+ { hit_count_increment: 0 },
400
+ );
327
401
  if (updated) result.updated.push(updated);
328
402
  }
329
403
  }
@@ -337,9 +411,9 @@ export function decayRules(store, _sessionCount, projectSlug) {
337
411
  * @returns {Array}
338
412
  */
339
413
  export function getActiveAdaptiveRules(store, projectSlug) {
340
- if (!store.listAdaptiveRules) return [];
341
- return store.listAdaptiveRules(projectSlug)
342
- .filter((rule) => rule.confidence >= ACTIVE_RULE_CONFIDENCE);
414
+ return listAdaptiveRulesFromStore(store, projectSlug).filter(
415
+ (rule) => rule.confidence >= ACTIVE_RULE_CONFIDENCE,
416
+ );
343
417
  }
344
418
 
345
419
  /**
package/hub/research.mjs CHANGED
@@ -1,11 +1,12 @@
1
1
  // hub/research.mjs — 자율 웹 리서치 엔진 코어
2
2
  // 검색 쿼리 생성 → 결과 정규화 → 보고서 빌드 → 저장
3
3
 
4
- import { mkdirSync, writeFileSync } from 'node:fs';
5
- import { join, resolve } from 'node:path';
6
- import { TFX_REPORTS_DIR } from './paths.mjs';
4
+ import { mkdirSync, writeFileSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { TFX_REPORTS_DIR } from "./paths.mjs";
7
7
 
8
8
  /**
9
+ * @experimental 런타임 미연결 — 향후 통합 예정
9
10
  * @experimental
10
11
  * 주제에서 검색 쿼리 3-5개를 자동 생성한다.
11
12
  * 한국어 주제 → 한국어 + 영어 혼합, 영어 주제 → 영어 쿼리.
@@ -13,13 +14,13 @@ import { TFX_REPORTS_DIR } from './paths.mjs';
13
14
  * @param {'ko'|'en'|'auto'} [lang='auto'] - 언어 힌트
14
15
  * @returns {string[]} 검색 쿼리 배열
15
16
  */
16
- export function generateQueries(topic, lang = 'auto') {
17
- if (!topic || typeof topic !== 'string' || !topic.trim()) return [];
17
+ export function generateQueries(topic, lang = "auto") {
18
+ if (!topic || typeof topic !== "string" || !topic.trim()) return [];
18
19
 
19
20
  const t = topic.trim();
20
- const detectedLang = lang === 'auto' ? detectLang(t) : lang;
21
+ const detectedLang = lang === "auto" ? detectLang(t) : lang;
21
22
 
22
- if (detectedLang === 'ko') {
23
+ if (detectedLang === "ko") {
23
24
  return [
24
25
  `${t} 정리`,
25
26
  `${t} 비교 분석`,
@@ -49,10 +50,10 @@ export function normalizeResults(rawResults) {
49
50
  const out = [];
50
51
 
51
52
  for (const r of rawResults) {
52
- if (!r || typeof r !== 'object') continue;
53
- const url = (r.url || r.link || '').trim();
54
- const title = (r.title || r.name || '').trim();
55
- const snippet = (r.snippet || r.description || r.content || '').trim();
53
+ if (!r || typeof r !== "object") continue;
54
+ const url = (r.url || r.link || "").trim();
55
+ const title = (r.title || r.name || "").trim();
56
+ const snippet = (r.snippet || r.description || r.content || "").trim();
56
57
 
57
58
  if (!url || seen.has(url)) continue;
58
59
  seen.add(url);
@@ -70,13 +71,16 @@ export function normalizeResults(rawResults) {
70
71
  * @returns {string} 마크다운 문자열
71
72
  */
72
73
  export function buildReport(topic, findings, sources) {
73
- const date = new Date().toISOString().split('T')[0];
74
+ const date = new Date().toISOString().split("T")[0];
74
75
  const findingsSection = (findings || [])
75
76
  .map((f, i) => `${i + 1}. ${f}`)
76
- .join('\n');
77
+ .join("\n");
77
78
  const sourcesSection = (sources || [])
78
- .map((s) => `- [${s.title || s.url}](${s.url})${s.snippet ? ` — ${s.snippet}` : ''}`)
79
- .join('\n');
79
+ .map(
80
+ (s) =>
81
+ `- [${s.title || s.url}](${s.url})${s.snippet ? ` — ${s.snippet}` : ""}`,
82
+ )
83
+ .join("\n");
80
84
 
81
85
  return `# Research: ${topic}
82
86
  Date: ${date}
@@ -85,13 +89,13 @@ Date: ${date}
85
89
  ${topic}에 대한 자동 리서치 결과입니다.
86
90
 
87
91
  ## Key Findings
88
- ${findingsSection || '_발견 없음_'}
92
+ ${findingsSection || "_발견 없음_"}
89
93
 
90
94
  ## Actionable Recommendations
91
95
  리서치 결과를 바탕으로 다음 단계를 검토하세요.
92
96
 
93
97
  ## Sources
94
- ${sourcesSection || '_출처 없음_'}
98
+ ${sourcesSection || "_출처 없음_"}
95
99
  `;
96
100
  }
97
101
 
@@ -107,20 +111,24 @@ export function saveReport(topic, content, baseDir = process.cwd()) {
107
111
  const resolvedDir = resolve(dir);
108
112
  const expectedBase = resolve(baseDir || TFX_REPORTS_DIR);
109
113
  if (!resolvedDir.startsWith(expectedBase)) {
110
- throw new Error('Invalid report directory: path traversal detected');
114
+ throw new Error("Invalid report directory: path traversal detected");
111
115
  }
112
116
  mkdirSync(dir, { recursive: true });
113
117
 
114
- const ts = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, 19);
115
- const slug = (topic || 'untitled')
116
- .replace(/[^a-zA-Z0-9가-힣\s-]/g, '')
117
- .replace(/\s+/g, '-')
118
+ const ts = new Date()
119
+ .toISOString()
120
+ .replace(/[:.]/g, "-")
121
+ .replace("T", "_")
122
+ .slice(0, 19);
123
+ const slug = (topic || "untitled")
124
+ .replace(/[^a-zA-Z0-9가-힣\s-]/g, "")
125
+ .replace(/\s+/g, "-")
118
126
  .slice(0, 40)
119
127
  .toLowerCase();
120
128
  const filename = `research-${ts}-${slug}.md`;
121
129
  const filepath = join(dir, filename);
122
130
 
123
- writeFileSync(filepath, content, 'utf-8');
131
+ writeFileSync(filepath, content, "utf-8");
124
132
  return filepath;
125
133
  }
126
134
 
@@ -132,7 +140,7 @@ export function saveReport(topic, content, baseDir = process.cwd()) {
132
140
  * @returns {'ko'|'en'}
133
141
  */
134
142
  function detectLang(text) {
135
- return /[가-힣]/.test(text) ? 'ko' : 'en';
143
+ return /[가-힣]/.test(text) ? "ko" : "en";
136
144
  }
137
145
 
138
146
  /**
@@ -142,6 +150,6 @@ function detectLang(text) {
142
150
  * @returns {string}
143
151
  */
144
152
  function toEnglishQuery(text) {
145
- const eng = text.replace(/[가-힣\s]+/g, ' ').trim();
153
+ const eng = text.replace(/[가-힣\s]+/g, " ").trim();
146
154
  return eng || text;
147
155
  }