@triflux/core 10.0.3 → 10.25.1

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 (143) 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 +47 -7
  4. package/hooks/hook-adaptive-collector.mjs +18 -16
  5. package/hooks/hook-manager.mjs +93 -32
  6. package/hooks/hook-orchestrator.mjs +279 -33
  7. package/hooks/hook-registry.json +104 -7
  8. package/hooks/hooks.json +49 -1
  9. package/hooks/keyword-rules.json +183 -23
  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 +308 -18
  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 +832 -291
  28. package/hub/cli-adapter-base.mjs +321 -97
  29. package/hub/codex-adapter.mjs +179 -93
  30. package/hub/codex-compat.mjs +4 -3
  31. package/hub/codex-preflight.mjs +113 -37
  32. package/hub/delegator/contracts.mjs +19 -23
  33. package/hub/delegator/index.mjs +14 -14
  34. package/hub/delegator/service.mjs +88 -64
  35. package/hub/delegator/tool-definitions.mjs +35 -35
  36. package/hub/dynamic-routing-engine.mjs +511 -0
  37. package/hub/fullcycle.mjs +34 -17
  38. package/hub/gemini-adapter.mjs +77 -95
  39. package/hub/hitl.mjs +202 -143
  40. package/hub/intent.mjs +171 -39
  41. package/hub/lib/bash-path.mjs +73 -0
  42. package/hub/lib/cache-guard.mjs +43 -17
  43. package/hub/lib/env-detect.mjs +145 -0
  44. package/hub/lib/hosts-compat.mjs +319 -0
  45. package/hub/lib/mcp-response-cache.mjs +239 -0
  46. package/hub/lib/memory-store.mjs +303 -107
  47. package/hub/lib/path-utils.mjs +165 -0
  48. package/hub/lib/phase-manager.mjs +493 -0
  49. package/hub/lib/process-utils.mjs +797 -104
  50. package/hub/lib/prompt-tmp.mjs +33 -0
  51. package/hub/lib/risk-tier.mjs +53 -0
  52. package/hub/lib/spawn-trace.mjs +561 -0
  53. package/hub/lib/ssh-command.mjs +44 -24
  54. package/hub/lib/ssh-retry.mjs +5 -1
  55. package/hub/lib/staged-file-detect.mjs +43 -0
  56. package/hub/lib/state-snapshot.mjs +293 -0
  57. package/hub/lib/tfx-route-args.mjs +309 -0
  58. package/hub/lib/timeline-adapter.mjs +190 -0
  59. package/hub/lib/trace-recorder.mjs +153 -0
  60. package/hub/lib/uuidv7.mjs +4 -3
  61. package/hub/memory-doctor.mjs +266 -106
  62. package/hub/middleware/quota-middleware.mjs +70 -0
  63. package/hub/middleware/request-logger.mjs +61 -34
  64. package/hub/paths.mjs +9 -9
  65. package/hub/pipeline/gates/confidence.mjs +34 -15
  66. package/hub/pipeline/gates/consensus.mjs +27 -15
  67. package/hub/pipeline/gates/index.mjs +7 -3
  68. package/hub/pipeline/gates/selfcheck.mjs +57 -19
  69. package/hub/pipeline/index.mjs +77 -42
  70. package/hub/pipeline/state.mjs +10 -10
  71. package/hub/pipeline/transitions.mjs +40 -23
  72. package/hub/platform.mjs +65 -48
  73. package/hub/quality/deslop.mjs +70 -49
  74. package/hub/reflexion.mjs +116 -58
  75. package/hub/research.mjs +34 -25
  76. package/hub/router.mjs +941 -791
  77. package/hub/routing/complexity.mjs +132 -29
  78. package/hub/routing/index.mjs +17 -12
  79. package/hub/routing/q-learning.mjs +76 -28
  80. package/hub/routing-snapshot.mjs +261 -0
  81. package/hub/session-fingerprint.mjs +129 -63
  82. package/hub/state.mjs +86 -44
  83. package/hub/team/retry-state-machine.mjs +267 -0
  84. package/hub/token-mode.mjs +76 -72
  85. package/hub/workers/worker-utils.mjs +22 -16
  86. package/hud/colors.mjs +27 -9
  87. package/hud/constants.mjs +184 -27
  88. package/hud/context-monitor.mjs +133 -44
  89. package/hud/hud-qos-status.mjs +153 -50
  90. package/hud/mission-board.mjs +56 -0
  91. package/hud/providers/claude.mjs +398 -114
  92. package/hud/providers/codex.mjs +96 -21
  93. package/hud/providers/gemini.mjs +184 -51
  94. package/hud/renderers.mjs +413 -123
  95. package/hud/terminal.mjs +101 -31
  96. package/hud/utils.mjs +81 -39
  97. package/mesh/index.mjs +69 -0
  98. package/mesh/mesh-budget.mjs +137 -0
  99. package/mesh/mesh-heartbeat.mjs +100 -0
  100. package/mesh/mesh-protocol.mjs +96 -0
  101. package/mesh/mesh-queue.mjs +163 -0
  102. package/mesh/mesh-registry.mjs +78 -0
  103. package/mesh/mesh-router.mjs +77 -0
  104. package/package.json +5 -1
  105. package/scripts/lib/agent-json.mjs +27 -0
  106. package/scripts/lib/async.mjs +174 -0
  107. package/scripts/lib/claudemd-scanner.mjs +6 -1
  108. package/scripts/lib/cli-agy.mjs +62 -0
  109. package/scripts/lib/cli-claude.mjs +78 -0
  110. package/scripts/lib/cli-codex.mjs +199 -0
  111. package/scripts/lib/cli-gemini.mjs +67 -0
  112. package/scripts/lib/codex-recovery.sh +50 -0
  113. package/scripts/lib/context.mjs +3 -3
  114. package/scripts/lib/cross-review-utils.mjs +13 -5
  115. package/scripts/lib/doctor-env-checks.mjs +121 -0
  116. package/scripts/lib/dynamic-route-cli.mjs +107 -0
  117. package/scripts/lib/env-probe.mjs +58 -30
  118. package/scripts/lib/env.mjs +14 -0
  119. package/scripts/lib/gemini-profiles.mjs +44 -10
  120. package/scripts/lib/handoff.mjs +33 -17
  121. package/scripts/lib/hook-utils.mjs +8 -6
  122. package/scripts/lib/hub.mjs +48 -0
  123. package/scripts/lib/keyword-rules.mjs +48 -19
  124. package/scripts/lib/logger.mjs +24 -24
  125. package/scripts/lib/mcp-filter.mjs +393 -249
  126. package/scripts/lib/mcp-gateway-health-check.mjs +159 -0
  127. package/scripts/lib/mcp-gateway-servers.mjs +70 -0
  128. package/scripts/lib/mcp-gateway-wrapper-check.mjs +35 -0
  129. package/scripts/lib/mcp-guard-engine.mjs +1282 -116
  130. package/scripts/lib/mcp-health.mjs +773 -0
  131. package/scripts/lib/mcp-manifest.mjs +24 -14
  132. package/scripts/lib/mcp-server-catalog.mjs +355 -118
  133. package/scripts/lib/pid.mjs +63 -0
  134. package/scripts/lib/process-utils.mjs +26 -0
  135. package/scripts/lib/psmux-info.mjs +72 -12
  136. package/scripts/lib/quota.mjs +47 -0
  137. package/scripts/lib/remote-spawn-transfer.mjs +44 -14
  138. package/scripts/lib/skill-state.mjs +220 -0
  139. package/scripts/lib/skill-template.mjs +36 -11
  140. package/scripts/lib/team.mjs +75 -0
  141. package/scripts/lib/timeout.mjs +66 -0
  142. package/scripts/lib/tmp.mjs +26 -0
  143. 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, relative } 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
@@ -7,7 +7,8 @@ const DEFAULT_CONFIDENCE = 0.5;
7
7
  const ACTIVE_RULE_CONFIDENCE = 0.5;
8
8
  const ADAPTIVE_PROMOTION_STEP = 0.1;
9
9
  const ADAPTIVE_DECAY_STEP = 0.1;
10
- const ADAPTIVE_DECAY_WINDOW = 5;
10
+ /** @deprecated 세션 기반 decay에서 시간 기반으로 변경됨. 미사용. */
11
+ const _ADAPTIVE_DECAY_WINDOW = 5;
11
12
  const ADAPTIVE_DELETE_THRESHOLD = 0.3;
12
13
 
13
14
  function clampConfidence(value) {
@@ -31,6 +32,7 @@ function pickString(...values) {
31
32
  );
32
33
  }
33
34
 
35
+ /** @deprecated 세션 기반 decay 제거로 미사용. 세션 인식 복원 시 재활용 예정. */
34
36
  function pickSessionCount(...values) {
35
37
  const raw = values.find((value) => Number.isFinite(Number(value)));
36
38
  return raw == null ? 0 : Math.max(0, Math.trunc(Number(raw)));
@@ -109,6 +111,7 @@ function normalizeSessionIds(sessionIds) {
109
111
  ];
110
112
  }
111
113
 
114
+ /** @deprecated reflexion_entries 기반. adaptive_rules에서는 미사용. 세션 인식 복원 시 재활용 예정. */
112
115
  function getAdaptiveState(rule = {}) {
113
116
  const state = rule.adaptive_state || {};
114
117
  const session_ids = normalizeSessionIds(state.session_ids);
@@ -125,7 +128,8 @@ function getAdaptiveState(rule = {}) {
125
128
  };
126
129
  }
127
130
 
128
- function mergeAdaptiveState(rule, errorContext = {}) {
131
+ /** @deprecated reflexion_entries 기반. adaptive_rules에서는 미사용. 세션 인식 복원 시 재활용 예정. */
132
+ function _mergeAdaptiveState(rule, errorContext = {}) {
129
133
  const current = getAdaptiveState(rule);
130
134
  const sessionId = pickSessionId(errorContext);
131
135
  const sessionCount = pickSessionCount(
@@ -159,6 +163,63 @@ function filterEntriesByType(entries, type) {
159
163
  );
160
164
  }
161
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
+
162
223
  /**
163
224
  * 에러 메시지를 정규화된 패턴 시그니처로 변환
164
225
  * 파일 경로, 줄 번호, 타임스탬프, UUID, 숫자 리터럴을 플레이스홀더로 치환
@@ -185,6 +246,7 @@ export function normalizeError(errorMessage) {
185
246
 
186
247
  /**
187
248
  * 에러에 대한 기존 솔루션 검색
249
+ * @deprecated reflexion_entries 기반. adaptive_rules로 통합 예정. 현재 런타임 호출 없음.
188
250
  * @param {object} store - createStore() 반환 객체
189
251
  * @param {string} errorMessage - 원본 에러 메시지
190
252
  * @param {object} [context={}] - { file, function, cli, agent }
@@ -200,6 +262,7 @@ export function lookupSolution(store, errorMessage, context = {}) {
200
262
 
201
263
  /**
202
264
  * 에러 해결 후 학습 저장
265
+ * @deprecated reflexion_entries 기반. adaptive_rules로 통합 예정. 현재 런타임 호출 없음.
203
266
  * 동일 패턴이 존재하면 hit 업데이트, 없으면 새로 생성
204
267
  * @param {object} store
205
268
  * @param {{ error: string, solution: string, context?: object, success?: boolean }} opts
@@ -233,6 +296,7 @@ export function learnFromError(
233
296
 
234
297
  /**
235
298
  * 솔루션 적용 결과 피드백
299
+ * @deprecated reflexion_entries 기반. adaptive_rules로 통합 예정. 현재 런타임 호출 없음.
236
300
  * @param {object} store
237
301
  * @param {string} entryId
238
302
  * @param {boolean} success
@@ -280,82 +344,76 @@ export function adaptiveRuleFromError(errorContext = {}) {
280
344
 
281
345
  /**
282
346
  * 동일 패턴이 여러 세션에서 재발하면 adaptive rule confidence를 승격
283
- * @param {object} store
284
- * @param {string} ruleId
285
- * @param {object} [errorContext={}]
347
+ * 현재 (projectSlug, pattern)과 구형 (ruleId, errorContext) 시그니처를 모두 지원한다.
348
+ * @param {object} store — store-adapter 인스턴스 (findAdaptiveRule, updateRuleConfidence 필요)
349
+ * @param {string} ruleIdOrProjectSlug
350
+ * @param {object|string} patternOrErrorContext
286
351
  * @returns {object|null}
287
352
  */
288
- export function promoteRule(store, ruleId, errorContext = {}) {
289
- const rule = store.getReflexion(ruleId);
290
- if (!rule || rule.type !== ADAPTIVE_RULE_TYPE || !store.patchReflexion)
291
- return null;
292
- const current = getAdaptiveState(rule);
293
- const next = mergeAdaptiveState(rule, errorContext);
294
- const newSession = next.session_occurrences > current.session_occurrences;
295
- const promoted =
296
- newSession && next.session_occurrences >= 2
297
- ? clampConfidence(rule.confidence + ADAPTIVE_PROMOTION_STEP)
298
- : rule.confidence;
299
- return store.patchReflexion(ruleId, {
300
- adaptive_state: next,
301
- confidence: promoted,
302
- hit_count: (rule.hit_count || 0) + 1,
303
- last_hit_ms: Date.now(),
304
- });
353
+ export function promoteRule(store, ruleIdOrProjectSlug, patternOrErrorContext) {
354
+ if (!store.findAdaptiveRule || !store.updateRuleConfidence) return null;
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);
361
+ if (!rule) return null;
362
+ const promoted = clampConfidence(rule.confidence + ADAPTIVE_PROMOTION_STEP);
363
+ return store.updateRuleConfidence(
364
+ identity.project_slug,
365
+ identity.pattern,
366
+ promoted,
367
+ { hit_count_increment: 1 },
368
+ );
305
369
  }
306
370
 
307
371
  /**
308
- * 지정 세션 수만큼 관측되지 않은 adaptive rules confidence 감소
309
- * @param {object} store
310
- * @param {number} sessionCount
372
+ * 7일 이상 미관측된 adaptive rules의 confidence를 -0.1 감소, 임계값 이하면 삭제
373
+ * @param {object} store — store-adapter 인스턴스 (listAdaptiveRules, updateRuleConfidence, deleteAdaptiveRule 필요)
374
+ * @param {number} _sessionCount — 하위 호환용 (현재 미사용)
375
+ * @param {string} [projectSlug] — 특정 프로젝트만 대상. 미지정 시 전체 스캔
311
376
  * @returns {{ updated: Array, deleted: string[] }}
312
377
  */
313
- export function decayRules(store, sessionCount) {
314
- const currentSession = pickSessionCount(sessionCount);
315
- if (!store.listReflexion || !store.patchReflexion || !store.deleteReflexion) {
316
- return { updated: [], deleted: [] };
317
- }
378
+ export function decayRules(store, _sessionCount, projectSlug) {
379
+ if (!store.listAdaptiveRules) return { updated: [], deleted: [] };
318
380
  const result = { updated: [], deleted: [] };
319
- for (const rule of store.listReflexion({ type: ADAPTIVE_RULE_TYPE })) {
320
- const state = getAdaptiveState(rule);
321
- const baseline = Math.max(
322
- state.last_seen_session,
323
- state.last_decay_session,
324
- );
325
- const decaySteps = Math.floor(
326
- (currentSession - baseline) / ADAPTIVE_DECAY_WINDOW,
327
- );
328
- if (decaySteps <= 0) continue;
329
- const confidence = clampConfidence(
330
- rule.confidence - decaySteps * ADAPTIVE_DECAY_STEP,
331
- );
332
- if (confidence <= ADAPTIVE_DELETE_THRESHOLD) {
333
- if (store.deleteReflexion(rule.id)) result.deleted.push(rule.id);
381
+ const rules = listAdaptiveRulesFromStore(store, projectSlug);
382
+ for (const rule of rules) {
383
+ // 7일 이상 미관측된 규칙만 decay 대상
384
+ const ageDays =
385
+ (Date.now() - (rule.last_seen_ms || 0)) / (24 * 3600 * 1000);
386
+ if (ageDays < 7) continue;
387
+ const decayed = clampConfidence(rule.confidence - ADAPTIVE_DECAY_STEP);
388
+ if (decayed <= ADAPTIVE_DELETE_THRESHOLD) {
389
+ if (store.deleteAdaptiveRule(rule.project_slug, rule.pattern)) {
390
+ result.deleted.push(`${rule.project_slug}:${rule.pattern}`);
391
+ }
334
392
  continue;
335
393
  }
336
- const updated = store.patchReflexion(rule.id, {
337
- confidence,
338
- adaptive_state: {
339
- ...state,
340
- last_decay_session: baseline + decaySteps * ADAPTIVE_DECAY_WINDOW,
341
- },
342
- });
343
- if (updated) result.updated.push(updated);
394
+ if (decayed < rule.confidence) {
395
+ const updated = store.updateRuleConfidence(
396
+ rule.project_slug,
397
+ rule.pattern,
398
+ decayed,
399
+ { hit_count_increment: 0 },
400
+ );
401
+ if (updated) result.updated.push(updated);
402
+ }
344
403
  }
345
404
  return result;
346
405
  }
347
406
 
348
407
  /**
349
408
  * 현재 활성화된 adaptive rules 조회
350
- * @param {object} store
409
+ * @param {object} store — store-adapter 인스턴스 (listAdaptiveRules 필요)
351
410
  * @param {string} projectSlug
352
411
  * @returns {Array}
353
412
  */
354
413
  export function getActiveAdaptiveRules(store, projectSlug) {
355
- if (!store.listReflexion) return [];
356
- return store
357
- .listReflexion({ type: ADAPTIVE_RULE_TYPE, projectSlug })
358
- .filter((rule) => rule.confidence > ACTIVE_RULE_CONFIDENCE);
414
+ return listAdaptiveRulesFromStore(store, projectSlug).filter(
415
+ (rule) => rule.confidence >= ACTIVE_RULE_CONFIDENCE,
416
+ );
359
417
  }
360
418
 
361
419
  /**
package/hub/research.mjs CHANGED
@@ -1,24 +1,26 @@
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 런타임 미연결 — 향후 통합 예정
10
+ * @experimental
9
11
  * 주제에서 검색 쿼리 3-5개를 자동 생성한다.
10
12
  * 한국어 주제 → 한국어 + 영어 혼합, 영어 주제 → 영어 쿼리.
11
13
  * @param {string} topic - 리서치 주제
12
14
  * @param {'ko'|'en'|'auto'} [lang='auto'] - 언어 힌트
13
15
  * @returns {string[]} 검색 쿼리 배열
14
16
  */
15
- export function generateQueries(topic, lang = 'auto') {
16
- if (!topic || typeof topic !== 'string' || !topic.trim()) return [];
17
+ export function generateQueries(topic, lang = "auto") {
18
+ if (!topic || typeof topic !== "string" || !topic.trim()) return [];
17
19
 
18
20
  const t = topic.trim();
19
- const detectedLang = lang === 'auto' ? detectLang(t) : lang;
21
+ const detectedLang = lang === "auto" ? detectLang(t) : lang;
20
22
 
21
- if (detectedLang === 'ko') {
23
+ if (detectedLang === "ko") {
22
24
  return [
23
25
  `${t} 정리`,
24
26
  `${t} 비교 분석`,
@@ -48,10 +50,10 @@ export function normalizeResults(rawResults) {
48
50
  const out = [];
49
51
 
50
52
  for (const r of rawResults) {
51
- if (!r || typeof r !== 'object') continue;
52
- const url = (r.url || r.link || '').trim();
53
- const title = (r.title || r.name || '').trim();
54
- 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();
55
57
 
56
58
  if (!url || seen.has(url)) continue;
57
59
  seen.add(url);
@@ -69,13 +71,16 @@ export function normalizeResults(rawResults) {
69
71
  * @returns {string} 마크다운 문자열
70
72
  */
71
73
  export function buildReport(topic, findings, sources) {
72
- const date = new Date().toISOString().split('T')[0];
74
+ const date = new Date().toISOString().split("T")[0];
73
75
  const findingsSection = (findings || [])
74
76
  .map((f, i) => `${i + 1}. ${f}`)
75
- .join('\n');
77
+ .join("\n");
76
78
  const sourcesSection = (sources || [])
77
- .map((s) => `- [${s.title || s.url}](${s.url})${s.snippet ? ` — ${s.snippet}` : ''}`)
78
- .join('\n');
79
+ .map(
80
+ (s) =>
81
+ `- [${s.title || s.url}](${s.url})${s.snippet ? ` — ${s.snippet}` : ""}`,
82
+ )
83
+ .join("\n");
79
84
 
80
85
  return `# Research: ${topic}
81
86
  Date: ${date}
@@ -84,13 +89,13 @@ Date: ${date}
84
89
  ${topic}에 대한 자동 리서치 결과입니다.
85
90
 
86
91
  ## Key Findings
87
- ${findingsSection || '_발견 없음_'}
92
+ ${findingsSection || "_발견 없음_"}
88
93
 
89
94
  ## Actionable Recommendations
90
95
  리서치 결과를 바탕으로 다음 단계를 검토하세요.
91
96
 
92
97
  ## Sources
93
- ${sourcesSection || '_출처 없음_'}
98
+ ${sourcesSection || "_출처 없음_"}
94
99
  `;
95
100
  }
96
101
 
@@ -106,20 +111,24 @@ export function saveReport(topic, content, baseDir = process.cwd()) {
106
111
  const resolvedDir = resolve(dir);
107
112
  const expectedBase = resolve(baseDir || TFX_REPORTS_DIR);
108
113
  if (!resolvedDir.startsWith(expectedBase)) {
109
- throw new Error('Invalid report directory: path traversal detected');
114
+ throw new Error("Invalid report directory: path traversal detected");
110
115
  }
111
116
  mkdirSync(dir, { recursive: true });
112
117
 
113
- const ts = new Date().toISOString().replace(/[:.]/g, '-').replace('T', '_').slice(0, 19);
114
- const slug = (topic || 'untitled')
115
- .replace(/[^a-zA-Z0-9가-힣\s-]/g, '')
116
- .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, "-")
117
126
  .slice(0, 40)
118
127
  .toLowerCase();
119
128
  const filename = `research-${ts}-${slug}.md`;
120
129
  const filepath = join(dir, filename);
121
130
 
122
- writeFileSync(filepath, content, 'utf-8');
131
+ writeFileSync(filepath, content, "utf-8");
123
132
  return filepath;
124
133
  }
125
134
 
@@ -131,7 +140,7 @@ export function saveReport(topic, content, baseDir = process.cwd()) {
131
140
  * @returns {'ko'|'en'}
132
141
  */
133
142
  function detectLang(text) {
134
- return /[가-힣]/.test(text) ? 'ko' : 'en';
143
+ return /[가-힣]/.test(text) ? "ko" : "en";
135
144
  }
136
145
 
137
146
  /**
@@ -141,6 +150,6 @@ function detectLang(text) {
141
150
  * @returns {string}
142
151
  */
143
152
  function toEnglishQuery(text) {
144
- const eng = text.replace(/[가-힣\s]+/g, ' ').trim();
153
+ const eng = text.replace(/[가-힣\s]+/g, " ").trim();
145
154
  return eng || text;
146
155
  }