@nahisaho/musubix-neural-search 2.1.1 → 2.2.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.
- package/dist/EnhancedNeuralSearchManager.d.ts +215 -0
- package/dist/EnhancedNeuralSearchManager.d.ts.map +1 -0
- package/dist/EnhancedNeuralSearchManager.js +307 -0
- package/dist/EnhancedNeuralSearchManager.js.map +1 -0
- package/dist/cache/EmbeddingCache.d.ts +93 -0
- package/dist/cache/EmbeddingCache.d.ts.map +1 -0
- package/dist/cache/EmbeddingCache.js +208 -0
- package/dist/cache/EmbeddingCache.js.map +1 -0
- package/dist/cache/index.d.ts +7 -0
- package/dist/cache/index.d.ts.map +1 -0
- package/dist/cache/index.js +6 -0
- package/dist/cache/index.js.map +1 -0
- package/dist/fusion/ModalFusion.d.ts +111 -0
- package/dist/fusion/ModalFusion.d.ts.map +1 -0
- package/dist/fusion/ModalFusion.js +127 -0
- package/dist/fusion/ModalFusion.js.map +1 -0
- package/dist/fusion/index.d.ts +6 -0
- package/dist/fusion/index.d.ts.map +1 -0
- package/dist/fusion/index.js +6 -0
- package/dist/fusion/index.js.map +1 -0
- package/dist/index.d.ts +14 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/learning/OnlineModelUpdater.d.ts +195 -0
- package/dist/learning/OnlineModelUpdater.d.ts.map +1 -0
- package/dist/learning/OnlineModelUpdater.js +231 -0
- package/dist/learning/OnlineModelUpdater.js.map +1 -0
- package/dist/learning/__tests__/OnlineModelUpdater.test.d.ts +9 -0
- package/dist/learning/__tests__/OnlineModelUpdater.test.d.ts.map +1 -0
- package/dist/learning/__tests__/OnlineModelUpdater.test.js +174 -0
- package/dist/learning/__tests__/OnlineModelUpdater.test.js.map +1 -0
- package/dist/learning/index.d.ts +2 -0
- package/dist/learning/index.d.ts.map +1 -1
- package/dist/learning/index.js +2 -0
- package/dist/learning/index.js.map +1 -1
- package/dist/logging/TrajectoryLogger.d.ts +115 -0
- package/dist/logging/TrajectoryLogger.d.ts.map +1 -0
- package/dist/logging/TrajectoryLogger.js +128 -0
- package/dist/logging/TrajectoryLogger.js.map +1 -0
- package/dist/logging/index.d.ts +9 -0
- package/dist/logging/index.d.ts.map +1 -0
- package/dist/logging/index.js +8 -0
- package/dist/logging/index.js.map +1 -0
- package/dist/pruning/LearnedPruningPolicy.d.ts +129 -0
- package/dist/pruning/LearnedPruningPolicy.d.ts.map +1 -0
- package/dist/pruning/LearnedPruningPolicy.js +332 -0
- package/dist/pruning/LearnedPruningPolicy.js.map +1 -0
- package/dist/pruning/index.d.ts +6 -0
- package/dist/pruning/index.d.ts.map +1 -0
- package/dist/pruning/index.js +6 -0
- package/dist/pruning/index.js.map +1 -0
- package/dist/scorer/ContextAwareScorer.d.ts +126 -0
- package/dist/scorer/ContextAwareScorer.d.ts.map +1 -0
- package/dist/scorer/ContextAwareScorer.js +281 -0
- package/dist/scorer/ContextAwareScorer.js.map +1 -0
- package/dist/scorer/index.d.ts +2 -0
- package/dist/scorer/index.d.ts.map +1 -1
- package/dist/scorer/index.js +2 -0
- package/dist/scorer/index.js.map +1 -1
- package/dist/search/AdaptiveBeamSearch.d.ts +98 -0
- package/dist/search/AdaptiveBeamSearch.d.ts.map +1 -0
- package/dist/search/AdaptiveBeamSearch.js +240 -0
- package/dist/search/AdaptiveBeamSearch.js.map +1 -0
- package/dist/search/index.d.ts +2 -0
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +2 -0
- package/dist/search/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ContextAwareScorer - Project Context-Aware Branch Scoring
|
|
3
|
+
* @module @nahisaho/musubix-neural-search
|
|
4
|
+
* @see TSK-NS-103
|
|
5
|
+
* @see DES-NS-103
|
|
6
|
+
* @see REQ-NS-103
|
|
7
|
+
*
|
|
8
|
+
* プロジェクトコンテキストを30%以上の重みで反映するスコアラー
|
|
9
|
+
* - プロジェクトパターンの検出
|
|
10
|
+
* - コードベース埋め込みとの類似度
|
|
11
|
+
* - 詳細なスコア内訳の提供
|
|
12
|
+
*/
|
|
13
|
+
import { BranchScorer } from './BranchScorer.js';
|
|
14
|
+
// =============================================================================
|
|
15
|
+
// Implementation
|
|
16
|
+
// =============================================================================
|
|
17
|
+
/**
|
|
18
|
+
* Default ContextAwareScorer implementation
|
|
19
|
+
*/
|
|
20
|
+
export class DefaultContextAwareScorer {
|
|
21
|
+
config;
|
|
22
|
+
baseScorer;
|
|
23
|
+
projectContext = null;
|
|
24
|
+
feedbackHistory = new Map();
|
|
25
|
+
// Statistics
|
|
26
|
+
totalScored = 0;
|
|
27
|
+
scoreSum = 0;
|
|
28
|
+
confidenceSum = 0;
|
|
29
|
+
contextContributionSum = 0;
|
|
30
|
+
// Cache for breakdowns
|
|
31
|
+
breakdownCache = new WeakMap();
|
|
32
|
+
constructor(config = {}) {
|
|
33
|
+
// Ensure context weight is at least 30%
|
|
34
|
+
const contextWeight = Math.max(config.contextWeight ?? 0.3, 0.3);
|
|
35
|
+
this.config = {
|
|
36
|
+
contextWeight,
|
|
37
|
+
enableProjectContext: config.enableProjectContext ?? true,
|
|
38
|
+
baseWeights: config.baseWeights ?? {},
|
|
39
|
+
patternMatchBonus: config.patternMatchBonus ?? 0.1,
|
|
40
|
+
};
|
|
41
|
+
this.baseScorer = new BranchScorer(undefined, this.config.baseWeights);
|
|
42
|
+
}
|
|
43
|
+
// =========================================================================
|
|
44
|
+
// IBranchScorer Implementation
|
|
45
|
+
// =========================================================================
|
|
46
|
+
async score(branch, context) {
|
|
47
|
+
// Get base score
|
|
48
|
+
const baseResult = await this.baseScorer.score(branch, context);
|
|
49
|
+
const baseScore = baseResult.score;
|
|
50
|
+
// Compute context score
|
|
51
|
+
const contextScore = this.computeContextScore(branch, context);
|
|
52
|
+
// Combine scores
|
|
53
|
+
const effectiveContextWeight = this.config.enableProjectContext
|
|
54
|
+
? this.config.contextWeight
|
|
55
|
+
: 0;
|
|
56
|
+
const finalScore = baseScore * (1 - effectiveContextWeight) +
|
|
57
|
+
contextScore * effectiveContextWeight;
|
|
58
|
+
// Update statistics
|
|
59
|
+
this.updateStatistics(finalScore, baseResult.confidence, contextScore * effectiveContextWeight);
|
|
60
|
+
// Create result
|
|
61
|
+
const result = {
|
|
62
|
+
branch,
|
|
63
|
+
score: finalScore,
|
|
64
|
+
confidence: baseResult.confidence,
|
|
65
|
+
components: baseResult.components,
|
|
66
|
+
_contextScore: contextScore,
|
|
67
|
+
_baseScore: baseScore,
|
|
68
|
+
};
|
|
69
|
+
// Cache breakdown
|
|
70
|
+
this.breakdownCache.set(result, {
|
|
71
|
+
baseScore,
|
|
72
|
+
contextScore,
|
|
73
|
+
contextWeight: effectiveContextWeight,
|
|
74
|
+
finalScore,
|
|
75
|
+
patternMatches: this.findPatternMatches(branch),
|
|
76
|
+
});
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
async scoreBatch(branches, context) {
|
|
80
|
+
return Promise.all(branches.map((branch) => this.score(branch, context)));
|
|
81
|
+
}
|
|
82
|
+
update(feedback) {
|
|
83
|
+
const history = this.feedbackHistory.get(feedback.branchId) ?? [];
|
|
84
|
+
history.push(feedback);
|
|
85
|
+
this.feedbackHistory.set(feedback.branchId, history);
|
|
86
|
+
// Also update base scorer
|
|
87
|
+
this.baseScorer.update(feedback);
|
|
88
|
+
}
|
|
89
|
+
// =========================================================================
|
|
90
|
+
// Project Context
|
|
91
|
+
// =========================================================================
|
|
92
|
+
setProjectContext(context) {
|
|
93
|
+
this.projectContext = context;
|
|
94
|
+
}
|
|
95
|
+
// =========================================================================
|
|
96
|
+
// Score Breakdown
|
|
97
|
+
// =========================================================================
|
|
98
|
+
getScoreBreakdown(score) {
|
|
99
|
+
// Check cache
|
|
100
|
+
const cached = this.breakdownCache.get(score);
|
|
101
|
+
if (cached) {
|
|
102
|
+
return cached;
|
|
103
|
+
}
|
|
104
|
+
// Reconstruct breakdown if not cached
|
|
105
|
+
const extendedScore = score;
|
|
106
|
+
const baseScore = extendedScore._baseScore ?? score.score;
|
|
107
|
+
const contextScore = extendedScore._contextScore ?? 0;
|
|
108
|
+
const contextWeight = this.config.enableProjectContext
|
|
109
|
+
? this.config.contextWeight
|
|
110
|
+
: 0;
|
|
111
|
+
return {
|
|
112
|
+
baseScore,
|
|
113
|
+
contextScore,
|
|
114
|
+
contextWeight,
|
|
115
|
+
finalScore: score.score,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
// =========================================================================
|
|
119
|
+
// Statistics
|
|
120
|
+
// =========================================================================
|
|
121
|
+
getStatistics() {
|
|
122
|
+
return {
|
|
123
|
+
totalScored: this.totalScored,
|
|
124
|
+
averageScore: this.totalScored > 0 ? this.scoreSum / this.totalScored : 0,
|
|
125
|
+
averageConfidence: this.totalScored > 0 ? this.confidenceSum / this.totalScored : 0,
|
|
126
|
+
averageContextContribution: this.totalScored > 0
|
|
127
|
+
? this.contextContributionSum / this.totalScored
|
|
128
|
+
: 0,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
resetStatistics() {
|
|
132
|
+
this.totalScored = 0;
|
|
133
|
+
this.scoreSum = 0;
|
|
134
|
+
this.confidenceSum = 0;
|
|
135
|
+
this.contextContributionSum = 0;
|
|
136
|
+
}
|
|
137
|
+
// =========================================================================
|
|
138
|
+
// Serialization
|
|
139
|
+
// =========================================================================
|
|
140
|
+
toJSON() {
|
|
141
|
+
return JSON.stringify({
|
|
142
|
+
config: {
|
|
143
|
+
contextWeight: this.config.contextWeight,
|
|
144
|
+
enableProjectContext: this.config.enableProjectContext,
|
|
145
|
+
patternMatchBonus: this.config.patternMatchBonus,
|
|
146
|
+
},
|
|
147
|
+
statistics: this.getStatistics(),
|
|
148
|
+
projectContext: this.projectContext
|
|
149
|
+
? {
|
|
150
|
+
projectName: this.projectContext.projectName,
|
|
151
|
+
language: this.projectContext.language,
|
|
152
|
+
patterns: this.projectContext.patterns,
|
|
153
|
+
}
|
|
154
|
+
: null,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
fromJSON(json) {
|
|
158
|
+
const data = JSON.parse(json);
|
|
159
|
+
if (data.config) {
|
|
160
|
+
if (data.config.contextWeight !== undefined) {
|
|
161
|
+
this.config.contextWeight = Math.max(data.config.contextWeight, 0.3);
|
|
162
|
+
}
|
|
163
|
+
if (data.config.enableProjectContext !== undefined) {
|
|
164
|
+
this.config.enableProjectContext = data.config.enableProjectContext;
|
|
165
|
+
}
|
|
166
|
+
if (data.config.patternMatchBonus !== undefined) {
|
|
167
|
+
this.config.patternMatchBonus = data.config.patternMatchBonus;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (data.statistics) {
|
|
171
|
+
this.totalScored = data.statistics.totalScored ?? 0;
|
|
172
|
+
this.scoreSum =
|
|
173
|
+
(data.statistics.averageScore ?? 0) * this.totalScored;
|
|
174
|
+
this.confidenceSum =
|
|
175
|
+
(data.statistics.averageConfidence ?? 0) * this.totalScored;
|
|
176
|
+
this.contextContributionSum =
|
|
177
|
+
(data.statistics.averageContextContribution ?? 0) * this.totalScored;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
// =========================================================================
|
|
181
|
+
// Private Methods
|
|
182
|
+
// =========================================================================
|
|
183
|
+
computeContextScore(branch, context) {
|
|
184
|
+
if (!this.config.enableProjectContext || !this.projectContext) {
|
|
185
|
+
return 0.5; // Neutral score when no context
|
|
186
|
+
}
|
|
187
|
+
let score = 0.5; // Base
|
|
188
|
+
// Pattern matching bonus
|
|
189
|
+
const patternMatches = this.findPatternMatches(branch);
|
|
190
|
+
if (patternMatches.length > 0) {
|
|
191
|
+
score += this.config.patternMatchBonus * patternMatches.length;
|
|
192
|
+
}
|
|
193
|
+
// Codebase embedding similarity
|
|
194
|
+
if (this.projectContext.codebaseEmbedding) {
|
|
195
|
+
const similarity = this.cosineSimilarity(branch.features.codeEmbedding, this.projectContext.codebaseEmbedding);
|
|
196
|
+
score += similarity * 0.2;
|
|
197
|
+
}
|
|
198
|
+
// Language alignment
|
|
199
|
+
if (this.isLanguageAligned(branch, context)) {
|
|
200
|
+
score += 0.1;
|
|
201
|
+
}
|
|
202
|
+
// Domain keyword matching
|
|
203
|
+
if (this.projectContext.domainKeywords) {
|
|
204
|
+
const keywordScore = this.computeKeywordScore(branch, context);
|
|
205
|
+
score += keywordScore * 0.1;
|
|
206
|
+
}
|
|
207
|
+
// Clamp to [0, 1]
|
|
208
|
+
return Math.max(0, Math.min(1, score));
|
|
209
|
+
}
|
|
210
|
+
findPatternMatches(branch) {
|
|
211
|
+
if (!this.projectContext) {
|
|
212
|
+
return [];
|
|
213
|
+
}
|
|
214
|
+
const matches = [];
|
|
215
|
+
const action = branch.action.toLowerCase();
|
|
216
|
+
for (const pattern of this.projectContext.patterns) {
|
|
217
|
+
if (action.includes(pattern.toLowerCase()) ||
|
|
218
|
+
pattern.toLowerCase().includes(action)) {
|
|
219
|
+
matches.push(pattern);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return matches;
|
|
223
|
+
}
|
|
224
|
+
cosineSimilarity(a, b) {
|
|
225
|
+
if (a.length !== b.length || a.length === 0) {
|
|
226
|
+
return 0;
|
|
227
|
+
}
|
|
228
|
+
let dotProduct = 0;
|
|
229
|
+
let normA = 0;
|
|
230
|
+
let normB = 0;
|
|
231
|
+
for (let i = 0; i < a.length; i++) {
|
|
232
|
+
dotProduct += a[i] * b[i];
|
|
233
|
+
normA += a[i] * a[i];
|
|
234
|
+
normB += b[i] * b[i];
|
|
235
|
+
}
|
|
236
|
+
const denominator = Math.sqrt(normA) * Math.sqrt(normB);
|
|
237
|
+
if (denominator === 0) {
|
|
238
|
+
return 0;
|
|
239
|
+
}
|
|
240
|
+
return dotProduct / denominator;
|
|
241
|
+
}
|
|
242
|
+
isLanguageAligned(_branch, _context) {
|
|
243
|
+
if (!this.projectContext) {
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
// Simple heuristic: assume TypeScript/JavaScript projects
|
|
247
|
+
const lang = this.projectContext.language.toLowerCase();
|
|
248
|
+
return lang === 'typescript' || lang === 'javascript';
|
|
249
|
+
}
|
|
250
|
+
computeKeywordScore(branch, _context) {
|
|
251
|
+
if (!this.projectContext?.domainKeywords) {
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
const code = branch.to.code.toLowerCase();
|
|
255
|
+
let matches = 0;
|
|
256
|
+
for (const keyword of this.projectContext.domainKeywords) {
|
|
257
|
+
if (code.includes(keyword.toLowerCase())) {
|
|
258
|
+
matches++;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return Math.min(1, matches / Math.max(1, this.projectContext.domainKeywords.length));
|
|
262
|
+
}
|
|
263
|
+
updateStatistics(score, confidence, contextContribution) {
|
|
264
|
+
this.totalScored++;
|
|
265
|
+
this.scoreSum += score;
|
|
266
|
+
this.confidenceSum += confidence;
|
|
267
|
+
this.contextContributionSum += contextContribution;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// =============================================================================
|
|
271
|
+
// Factory Function
|
|
272
|
+
// =============================================================================
|
|
273
|
+
/**
|
|
274
|
+
* Create a ContextAwareScorer instance
|
|
275
|
+
* @param config - Optional configuration
|
|
276
|
+
* @returns ContextAwareScorer instance
|
|
277
|
+
*/
|
|
278
|
+
export function createContextAwareScorer(config = {}) {
|
|
279
|
+
return new DefaultContextAwareScorer(config);
|
|
280
|
+
}
|
|
281
|
+
//# sourceMappingURL=ContextAwareScorer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ContextAwareScorer.js","sourceRoot":"","sources":["../../src/scorer/ContextAwareScorer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAUH,OAAO,EAAE,YAAY,EAAqB,MAAM,mBAAmB,CAAC;AA8FpE,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEhF;;GAEG;AACH,MAAM,O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
|
|
7
7
|
export type { ScoreWeights } from './BranchScorer.js';
|
|
8
8
|
export { ContextEncoder } from './ContextEncoder.js';
|
|
9
|
+
export { createContextAwareScorer, DefaultContextAwareScorer, } from './ContextAwareScorer.js';
|
|
10
|
+
export type { ContextAwareScorer, ContextAwareScorerConfig, ProjectContext, ScoreBreakdown, ScoringStatistics, } from './ContextAwareScorer.js';
|
|
9
11
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scorer/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scorer/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,YAAY,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGrD,OAAO,EACL,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC;AACjC,YAAY,EACV,kBAAkB,EAClB,wBAAwB,EACxB,cAAc,EACd,cAAc,EACd,iBAAiB,GAClB,MAAM,yBAAyB,CAAC"}
|
package/dist/scorer/index.js
CHANGED
|
@@ -5,4 +5,6 @@
|
|
|
5
5
|
export { EmbeddingModel } from './EmbeddingModel.js';
|
|
6
6
|
export { BranchScorer } from './BranchScorer.js';
|
|
7
7
|
export { ContextEncoder } from './ContextEncoder.js';
|
|
8
|
+
// v2.2.0 NEW!
|
|
9
|
+
export { createContextAwareScorer, DefaultContextAwareScorer, } from './ContextAwareScorer.js';
|
|
8
10
|
//# sourceMappingURL=index.js.map
|
package/dist/scorer/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/scorer/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/scorer/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,cAAc;AACd,OAAO,EACL,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,yBAAyB,CAAC"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AdaptiveBeamSearch - Adaptive Beam Width Search
|
|
3
|
+
*
|
|
4
|
+
* Extends BeamSearch with dynamic beam width adjustment based on
|
|
5
|
+
* search progress. When stagnation is detected (no improvement for
|
|
6
|
+
* N iterations), beam width is increased up to a maximum.
|
|
7
|
+
*
|
|
8
|
+
* @module @nahisaho/musubix-neural-search
|
|
9
|
+
* @see TSK-NS-102
|
|
10
|
+
* @see DES-NS-102
|
|
11
|
+
* @see REQ-NS-102
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { AdaptiveBeamSearch } from './AdaptiveBeamSearch.js';
|
|
16
|
+
*
|
|
17
|
+
* const search = new AdaptiveBeamSearch({
|
|
18
|
+
* initialBeamWidth: 5,
|
|
19
|
+
* maxBeamWidth: 100,
|
|
20
|
+
* stagnationThreshold: 10,
|
|
21
|
+
* });
|
|
22
|
+
* const results = await search.search(initial, expand, scorer, context, config);
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
import type { Branch, IBranchScorer, IBeamSearch, SearchConfig, SearchContext, SearchResult, SearchState, SearchStatistics } from '../types.js';
|
|
26
|
+
/**
|
|
27
|
+
* Configuration for adaptive beam search
|
|
28
|
+
*/
|
|
29
|
+
export interface AdaptiveBeamConfig {
|
|
30
|
+
/** Initial beam width (default: 5) */
|
|
31
|
+
initialBeamWidth: number;
|
|
32
|
+
/** Maximum beam width allowed (default: 100) */
|
|
33
|
+
maxBeamWidth: number;
|
|
34
|
+
/** Iterations without improvement before adaptation (default: 10) */
|
|
35
|
+
stagnationThreshold: number;
|
|
36
|
+
/** Fraction to increase beam width on stagnation (default: 0.5 = 50%) */
|
|
37
|
+
beamWidthIncrease: number;
|
|
38
|
+
/** Minimum score improvement to not count as stagnation */
|
|
39
|
+
improvementThreshold: number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Adaptive search statistics
|
|
43
|
+
*/
|
|
44
|
+
export interface AdaptiveStatistics {
|
|
45
|
+
/** Current beam width */
|
|
46
|
+
currentBeamWidth: number;
|
|
47
|
+
/** Number of beam width adjustments made */
|
|
48
|
+
beamWidthAdjustments: number;
|
|
49
|
+
/** Current stagnation counter */
|
|
50
|
+
stagnationCount: number;
|
|
51
|
+
/** Best score seen */
|
|
52
|
+
bestScore: number;
|
|
53
|
+
/** Iterations since last improvement */
|
|
54
|
+
iterationsSinceImprovement: number;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Adaptive Beam Search implementation with dynamic beam width adjustment
|
|
58
|
+
*/
|
|
59
|
+
export declare class AdaptiveBeamSearch implements IBeamSearch {
|
|
60
|
+
private readonly adaptiveConfig;
|
|
61
|
+
private currentBeam;
|
|
62
|
+
private statistics;
|
|
63
|
+
private currentBeamWidth;
|
|
64
|
+
private beamWidthAdjustments;
|
|
65
|
+
private stagnationCount;
|
|
66
|
+
private bestScore;
|
|
67
|
+
private iterationsSinceImprovement;
|
|
68
|
+
constructor(config?: Partial<AdaptiveBeamConfig>);
|
|
69
|
+
/**
|
|
70
|
+
* Execute adaptive beam search
|
|
71
|
+
*/
|
|
72
|
+
search(initial: SearchState, expand: (state: SearchState) => Promise<Branch[]>, scorer: IBranchScorer, context: SearchContext, config: SearchConfig): Promise<SearchResult[]>;
|
|
73
|
+
/**
|
|
74
|
+
* Get current beam
|
|
75
|
+
*/
|
|
76
|
+
getCurrentBeam(): SearchState[];
|
|
77
|
+
/**
|
|
78
|
+
* Get search statistics
|
|
79
|
+
*/
|
|
80
|
+
getStatistics(): SearchStatistics;
|
|
81
|
+
/**
|
|
82
|
+
* Get adaptive-specific statistics
|
|
83
|
+
*/
|
|
84
|
+
getAdaptiveStatistics(): AdaptiveStatistics;
|
|
85
|
+
/**
|
|
86
|
+
* Reset adaptive state
|
|
87
|
+
*/
|
|
88
|
+
reset(): void;
|
|
89
|
+
/**
|
|
90
|
+
* Adjust beam width when stagnation detected
|
|
91
|
+
*/
|
|
92
|
+
private adjustBeamWidth;
|
|
93
|
+
/**
|
|
94
|
+
* Build path from state to root
|
|
95
|
+
*/
|
|
96
|
+
private buildPath;
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=AdaptiveBeamSearch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AdaptiveBeamSearch.d.ts","sourceRoot":"","sources":["../../src/search/AdaptiveBeamSearch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,KAAK,EACV,MAAM,EACN,aAAa,EACb,WAAW,EACX,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,WAAW,EACX,gBAAgB,EACjB,MAAM,aAAa,CAAC;AAOrB;;GAEG;AAC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G;IACH,qBAAqB,IAAI,kBAAkB;IAU3C;;OAEG;IACH,KAAK,IAAI,IAAI;IAoBb;;OAEG;IACH,OAAO,CAAC,eAAe;IAevB;;OAEG;IACH,OAAO,CAAC,SAAS;CAYlB"}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AdaptiveBeamSearch - Adaptive Beam Width Search
|
|
3
|
+
*
|
|
4
|
+
* Extends BeamSearch with dynamic beam width adjustment based on
|
|
5
|
+
* search progress. When stagnation is detected (no improvement for
|
|
6
|
+
* N iterations), beam width is increased up to a maximum.
|
|
7
|
+
*
|
|
8
|
+
* @module @nahisaho/musubix-neural-search
|
|
9
|
+
* @see TSK-NS-102
|
|
10
|
+
* @see DES-NS-102
|
|
11
|
+
* @see REQ-NS-102
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { AdaptiveBeamSearch } from './AdaptiveBeamSearch.js';
|
|
16
|
+
*
|
|
17
|
+
* const search = new AdaptiveBeamSearch({
|
|
18
|
+
* initialBeamWidth: 5,
|
|
19
|
+
* maxBeamWidth: 100,
|
|
20
|
+
* stagnationThreshold: 10,
|
|
21
|
+
* });
|
|
22
|
+
* const results = await search.search(initial, expand, scorer, context, config);
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
import { SearchTimeoutError } from '../errors.js';
|
|
26
|
+
// =============================================================================
|
|
27
|
+
// Default Configuration
|
|
28
|
+
// =============================================================================
|
|
29
|
+
const DEFAULT_CONFIG = {
|
|
30
|
+
initialBeamWidth: 5,
|
|
31
|
+
maxBeamWidth: 100,
|
|
32
|
+
stagnationThreshold: 10,
|
|
33
|
+
beamWidthIncrease: 0.5,
|
|
34
|
+
improvementThreshold: 0.001,
|
|
35
|
+
};
|
|
36
|
+
// =============================================================================
|
|
37
|
+
// Implementation
|
|
38
|
+
// =============================================================================
|
|
39
|
+
/**
|
|
40
|
+
* Adaptive Beam Search implementation with dynamic beam width adjustment
|
|
41
|
+
*/
|
|
42
|
+
export class AdaptiveBeamSearch {
|
|
43
|
+
adaptiveConfig;
|
|
44
|
+
currentBeam;
|
|
45
|
+
statistics;
|
|
46
|
+
// Adaptive state
|
|
47
|
+
currentBeamWidth;
|
|
48
|
+
beamWidthAdjustments = 0;
|
|
49
|
+
stagnationCount = 0;
|
|
50
|
+
bestScore = -Infinity;
|
|
51
|
+
iterationsSinceImprovement = 0;
|
|
52
|
+
constructor(config = {}) {
|
|
53
|
+
this.adaptiveConfig = { ...DEFAULT_CONFIG, ...config };
|
|
54
|
+
this.currentBeamWidth = this.adaptiveConfig.initialBeamWidth;
|
|
55
|
+
this.currentBeam = [];
|
|
56
|
+
this.statistics = {
|
|
57
|
+
totalExpanded: 0,
|
|
58
|
+
totalPruned: 0,
|
|
59
|
+
maxDepthReached: 0,
|
|
60
|
+
averageScore: 0,
|
|
61
|
+
timeElapsed: 0,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Execute adaptive beam search
|
|
66
|
+
*/
|
|
67
|
+
async search(initial, expand, scorer, context, config) {
|
|
68
|
+
const startTime = Date.now();
|
|
69
|
+
// Use config beam width or adaptive width
|
|
70
|
+
this.currentBeamWidth = config.beamWidth ?? this.adaptiveConfig.initialBeamWidth;
|
|
71
|
+
this.currentBeam = [initial];
|
|
72
|
+
const allResults = [];
|
|
73
|
+
let iteration = 0;
|
|
74
|
+
let totalPruned = 0;
|
|
75
|
+
let totalExpanded = 0;
|
|
76
|
+
let maxDepth = 0;
|
|
77
|
+
const scores = [];
|
|
78
|
+
// Reset adaptive state
|
|
79
|
+
this.bestScore = -Infinity;
|
|
80
|
+
this.iterationsSinceImprovement = 0;
|
|
81
|
+
while (iteration < config.maxIterations && this.currentBeam.length > 0) {
|
|
82
|
+
// Check timeout
|
|
83
|
+
if (Date.now() - startTime > config.timeout) {
|
|
84
|
+
throw new SearchTimeoutError(config.timeout);
|
|
85
|
+
}
|
|
86
|
+
// Check depth
|
|
87
|
+
const maxBeamDepth = Math.max(...this.currentBeam.map((s) => s.depth));
|
|
88
|
+
maxDepth = Math.max(maxDepth, maxBeamDepth);
|
|
89
|
+
if (maxBeamDepth >= config.maxDepth) {
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
// Expand all states in beam
|
|
93
|
+
const candidates = [];
|
|
94
|
+
for (const state of this.currentBeam) {
|
|
95
|
+
const branches = await expand(state);
|
|
96
|
+
totalExpanded += branches.length;
|
|
97
|
+
// Score all branches
|
|
98
|
+
const scored = await scorer.scoreBatch(branches, context);
|
|
99
|
+
for (const branchScore of scored) {
|
|
100
|
+
// Apply pruning threshold
|
|
101
|
+
if (config.pruneThreshold !== undefined &&
|
|
102
|
+
branchScore.score < config.pruneThreshold) {
|
|
103
|
+
totalPruned++;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const path = this.buildPath(branchScore.branch.to, context.history);
|
|
107
|
+
candidates.push({
|
|
108
|
+
state: branchScore.branch.to,
|
|
109
|
+
score: branchScore.score,
|
|
110
|
+
path,
|
|
111
|
+
});
|
|
112
|
+
scores.push(branchScore.score);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
// Sort by score and keep top beamWidth
|
|
116
|
+
candidates.sort((a, b) => b.score - a.score);
|
|
117
|
+
const nextBeam = candidates.slice(0, this.currentBeamWidth);
|
|
118
|
+
// Track best score and check for improvement
|
|
119
|
+
const iterationBestScore = nextBeam.length > 0 ? nextBeam[0].score : -Infinity;
|
|
120
|
+
const improved = iterationBestScore > this.bestScore + this.adaptiveConfig.improvementThreshold;
|
|
121
|
+
if (improved) {
|
|
122
|
+
this.bestScore = iterationBestScore;
|
|
123
|
+
this.iterationsSinceImprovement = 0;
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
this.iterationsSinceImprovement++;
|
|
127
|
+
}
|
|
128
|
+
// Check for stagnation and adapt
|
|
129
|
+
if (this.iterationsSinceImprovement >= this.adaptiveConfig.stagnationThreshold) {
|
|
130
|
+
this.adjustBeamWidth();
|
|
131
|
+
this.iterationsSinceImprovement = 0;
|
|
132
|
+
this.stagnationCount++;
|
|
133
|
+
}
|
|
134
|
+
// Add to results
|
|
135
|
+
for (const candidate of nextBeam) {
|
|
136
|
+
allResults.push({
|
|
137
|
+
state: candidate.state,
|
|
138
|
+
score: candidate.score,
|
|
139
|
+
path: candidate.path,
|
|
140
|
+
iterations: iteration + 1,
|
|
141
|
+
pruned: totalPruned,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
// Update beam
|
|
145
|
+
this.currentBeam = nextBeam.map((c) => c.state);
|
|
146
|
+
iteration++;
|
|
147
|
+
}
|
|
148
|
+
// Update statistics
|
|
149
|
+
this.statistics = {
|
|
150
|
+
totalExpanded,
|
|
151
|
+
totalPruned,
|
|
152
|
+
maxDepthReached: maxDepth,
|
|
153
|
+
averageScore: scores.length > 0
|
|
154
|
+
? scores.reduce((a, b) => a + b, 0) / scores.length
|
|
155
|
+
: 0,
|
|
156
|
+
timeElapsed: Date.now() - startTime,
|
|
157
|
+
};
|
|
158
|
+
// Return best results (deduplicated)
|
|
159
|
+
const seen = new Set();
|
|
160
|
+
return allResults
|
|
161
|
+
.filter((r) => {
|
|
162
|
+
if (seen.has(r.state.id))
|
|
163
|
+
return false;
|
|
164
|
+
seen.add(r.state.id);
|
|
165
|
+
return true;
|
|
166
|
+
})
|
|
167
|
+
.sort((a, b) => b.score - a.score)
|
|
168
|
+
.slice(0, this.currentBeamWidth);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Get current beam
|
|
172
|
+
*/
|
|
173
|
+
getCurrentBeam() {
|
|
174
|
+
return [...this.currentBeam];
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Get search statistics
|
|
178
|
+
*/
|
|
179
|
+
getStatistics() {
|
|
180
|
+
return { ...this.statistics };
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Get adaptive-specific statistics
|
|
184
|
+
*/
|
|
185
|
+
getAdaptiveStatistics() {
|
|
186
|
+
return {
|
|
187
|
+
currentBeamWidth: this.currentBeamWidth,
|
|
188
|
+
beamWidthAdjustments: this.beamWidthAdjustments,
|
|
189
|
+
stagnationCount: this.stagnationCount,
|
|
190
|
+
bestScore: this.bestScore,
|
|
191
|
+
iterationsSinceImprovement: this.iterationsSinceImprovement,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Reset adaptive state
|
|
196
|
+
*/
|
|
197
|
+
reset() {
|
|
198
|
+
this.currentBeamWidth = this.adaptiveConfig.initialBeamWidth;
|
|
199
|
+
this.beamWidthAdjustments = 0;
|
|
200
|
+
this.stagnationCount = 0;
|
|
201
|
+
this.bestScore = -Infinity;
|
|
202
|
+
this.iterationsSinceImprovement = 0;
|
|
203
|
+
this.currentBeam = [];
|
|
204
|
+
this.statistics = {
|
|
205
|
+
totalExpanded: 0,
|
|
206
|
+
totalPruned: 0,
|
|
207
|
+
maxDepthReached: 0,
|
|
208
|
+
averageScore: 0,
|
|
209
|
+
timeElapsed: 0,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
// ===========================================================================
|
|
213
|
+
// Private Methods
|
|
214
|
+
// ===========================================================================
|
|
215
|
+
/**
|
|
216
|
+
* Adjust beam width when stagnation detected
|
|
217
|
+
*/
|
|
218
|
+
adjustBeamWidth() {
|
|
219
|
+
const increase = Math.ceil(this.currentBeamWidth * this.adaptiveConfig.beamWidthIncrease);
|
|
220
|
+
const newWidth = Math.min(this.currentBeamWidth + increase, this.adaptiveConfig.maxBeamWidth);
|
|
221
|
+
if (newWidth > this.currentBeamWidth) {
|
|
222
|
+
this.currentBeamWidth = newWidth;
|
|
223
|
+
this.beamWidthAdjustments++;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Build path from state to root
|
|
228
|
+
*/
|
|
229
|
+
buildPath(state, history) {
|
|
230
|
+
const path = [state];
|
|
231
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
232
|
+
if (history[i].id === state.parent) {
|
|
233
|
+
path.unshift(history[i]);
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return path;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
//# sourceMappingURL=AdaptiveBeamSearch.js.map
|