@bonginkan/maria 3.0.6 → 3.0.9
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/README.md +242 -229
- package/dist/bin/maria.cjs +30669 -43358
- package/dist/bin/maria.cjs.map +1 -1
- package/dist/cli.cjs +14975 -32982
- package/dist/cli.cjs.map +1 -1
- package/dist/index.js +817 -795
- package/dist/index.js.map +1 -1
- package/package.json +46 -6
package/dist/index.js
CHANGED
|
@@ -24,32 +24,32 @@ var NaturalLanguageProcessor = class {
|
|
|
24
24
|
}
|
|
25
25
|
this.initialized = true;
|
|
26
26
|
}
|
|
27
|
-
async process(input2,
|
|
28
|
-
const normalized = this.normalize(input2,
|
|
29
|
-
const tokens = this.tokenize(normalized,
|
|
30
|
-
const stems = this.stem(tokens,
|
|
27
|
+
async process(input2, language = "en") {
|
|
28
|
+
const normalized = this.normalize(input2, language);
|
|
29
|
+
const tokens = this.tokenize(normalized, language);
|
|
30
|
+
const stems = this.stem(tokens, language);
|
|
31
31
|
const entities = this.extractEntities(input2);
|
|
32
|
-
const
|
|
32
|
+
const _keywords = this.extractKeywords(tokens, language);
|
|
33
33
|
return {
|
|
34
34
|
original: input2,
|
|
35
35
|
normalized,
|
|
36
36
|
tokens,
|
|
37
37
|
stems,
|
|
38
38
|
entities,
|
|
39
|
-
language
|
|
40
|
-
|
|
39
|
+
language,
|
|
40
|
+
_keywords
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
|
-
normalize(text,
|
|
43
|
+
normalize(text, language) {
|
|
44
44
|
let normalized = text.toLowerCase().trim();
|
|
45
|
-
if (
|
|
45
|
+
if (language === "en") {
|
|
46
46
|
this.contractionMap.forEach((expanded, contraction) => {
|
|
47
|
-
const
|
|
48
|
-
normalized = normalized.replace(
|
|
47
|
+
const _regex = new RegExp(`\\b${contraction}\\b`, "gi");
|
|
48
|
+
normalized = normalized.replace(_regex, expanded);
|
|
49
49
|
});
|
|
50
50
|
}
|
|
51
51
|
normalized = normalized.replace(/\s+/g, " ");
|
|
52
|
-
switch (
|
|
52
|
+
switch (language) {
|
|
53
53
|
case "ja":
|
|
54
54
|
normalized = this.normalizeJapanese(normalized);
|
|
55
55
|
break;
|
|
@@ -65,8 +65,8 @@ var NaturalLanguageProcessor = class {
|
|
|
65
65
|
}
|
|
66
66
|
return normalized;
|
|
67
67
|
}
|
|
68
|
-
tokenize(text,
|
|
69
|
-
switch (
|
|
68
|
+
tokenize(text, language) {
|
|
69
|
+
switch (language) {
|
|
70
70
|
case "ja":
|
|
71
71
|
return this.tokenizeJapanese(text);
|
|
72
72
|
case "cn":
|
|
@@ -85,8 +85,8 @@ var NaturalLanguageProcessor = class {
|
|
|
85
85
|
tokenizeJapanese(text) {
|
|
86
86
|
const tokens = [];
|
|
87
87
|
patterns.forEach((pattern2) => {
|
|
88
|
-
text.match(pattern2);
|
|
89
|
-
if (
|
|
88
|
+
const _matches = text.match(pattern2);
|
|
89
|
+
if (_matches) {
|
|
90
90
|
tokens.push(...matches);
|
|
91
91
|
}
|
|
92
92
|
});
|
|
@@ -94,11 +94,11 @@ var NaturalLanguageProcessor = class {
|
|
|
94
94
|
}
|
|
95
95
|
tokenizeChinese(text) {
|
|
96
96
|
const tokens = [];
|
|
97
|
-
for (const
|
|
98
|
-
if (/[\u4e00-\u9faf]/.test(
|
|
99
|
-
tokens.push(
|
|
100
|
-
} else if (/[a-zA-Z0-9]+/.test(
|
|
101
|
-
tokens.push(
|
|
97
|
+
for (const char of text) {
|
|
98
|
+
if (/[\u4e00-\u9faf]/.test(char)) {
|
|
99
|
+
tokens.push(char);
|
|
100
|
+
} else if (/[a-zA-Z0-9]+/.test(char)) {
|
|
101
|
+
tokens.push(char);
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
104
|
return tokens;
|
|
@@ -106,15 +106,15 @@ var NaturalLanguageProcessor = class {
|
|
|
106
106
|
tokenizeKorean(text) {
|
|
107
107
|
const tokens = [];
|
|
108
108
|
patterns.forEach((pattern2) => {
|
|
109
|
-
text.match(pattern2);
|
|
110
|
-
if (
|
|
109
|
+
const _matches = text.match(pattern2);
|
|
110
|
+
if (_matches) {
|
|
111
111
|
tokens.push(...matches);
|
|
112
112
|
}
|
|
113
113
|
});
|
|
114
114
|
return tokens;
|
|
115
115
|
}
|
|
116
|
-
stem(tokens,
|
|
117
|
-
if (
|
|
116
|
+
stem(tokens, language) {
|
|
117
|
+
if (language !== "en") {
|
|
118
118
|
return tokens;
|
|
119
119
|
}
|
|
120
120
|
return tokens.map((token) => {
|
|
@@ -135,40 +135,41 @@ var NaturalLanguageProcessor = class {
|
|
|
135
135
|
}
|
|
136
136
|
extractEntities(text) {
|
|
137
137
|
const entities = [];
|
|
138
|
-
const
|
|
139
|
-
const fileMatches = text.match(
|
|
138
|
+
const filePattern = /(?:\/[\w.-]+)+(?:\.\w+)?|(?:[a-zA-Z]:[\\/][\w\\/.-]+)/g;
|
|
139
|
+
const fileMatches = text.match(filePattern);
|
|
140
140
|
if (fileMatches) {
|
|
141
|
-
fileMatches.forEach((
|
|
141
|
+
fileMatches.forEach((match) => {
|
|
142
142
|
entities.push({
|
|
143
|
-
text:
|
|
143
|
+
text: match,
|
|
144
144
|
type: "file",
|
|
145
|
-
value:
|
|
146
|
-
position: text.indexOf(
|
|
145
|
+
value: match,
|
|
146
|
+
position: text.indexOf(match)
|
|
147
147
|
});
|
|
148
148
|
});
|
|
149
149
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
150
|
+
const _urlPattern = /https?:\/\/[^\s]+/g;
|
|
151
|
+
const _urlMatches = text.match(_urlPattern);
|
|
152
|
+
if (_urlMatches) {
|
|
153
|
+
urlMatches.forEach((match) => {
|
|
153
154
|
entities.push({
|
|
154
|
-
text:
|
|
155
|
+
text: match,
|
|
155
156
|
type: "url",
|
|
156
|
-
value:
|
|
157
|
-
position: text.indexOf(
|
|
157
|
+
value: match,
|
|
158
|
+
position: text.indexOf(match)
|
|
158
159
|
});
|
|
159
160
|
});
|
|
160
161
|
}
|
|
161
162
|
languages.forEach((lang) => {
|
|
162
|
-
lang.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
163
|
-
new RegExp(`\\b${
|
|
164
|
-
text.match(
|
|
165
|
-
if (
|
|
166
|
-
matches.forEach((
|
|
163
|
+
const _escapedLang = lang.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
164
|
+
const _regex = new RegExp(`\\b${_escapedLang}\\b`, "gi");
|
|
165
|
+
const _matches = text.match(_regex);
|
|
166
|
+
if (_matches) {
|
|
167
|
+
matches.forEach((match) => {
|
|
167
168
|
entities.push({
|
|
168
|
-
text:
|
|
169
|
+
text: match,
|
|
169
170
|
type: "language",
|
|
170
171
|
value: lang,
|
|
171
|
-
position: text.indexOf(
|
|
172
|
+
position: text.indexOf(match)
|
|
172
173
|
});
|
|
173
174
|
});
|
|
174
175
|
}
|
|
@@ -184,36 +185,36 @@ var NaturalLanguageProcessor = class {
|
|
|
184
185
|
"rails",
|
|
185
186
|
"spring"
|
|
186
187
|
];
|
|
187
|
-
frameworks.forEach((
|
|
188
|
-
const
|
|
189
|
-
const
|
|
190
|
-
if (
|
|
191
|
-
|
|
188
|
+
frameworks.forEach((framework) => {
|
|
189
|
+
const _regex = new RegExp(`\\b${framework}\\b`, "gi");
|
|
190
|
+
const _matches = text.match(_regex);
|
|
191
|
+
if (_matches) {
|
|
192
|
+
matches.forEach((match) => {
|
|
192
193
|
entities.push({
|
|
193
|
-
text:
|
|
194
|
+
text: match,
|
|
194
195
|
type: "framework",
|
|
195
|
-
value:
|
|
196
|
-
position: text.indexOf(
|
|
196
|
+
value: framework,
|
|
197
|
+
position: text.indexOf(match)
|
|
197
198
|
});
|
|
198
199
|
});
|
|
199
200
|
}
|
|
200
201
|
});
|
|
201
202
|
return entities;
|
|
202
203
|
}
|
|
203
|
-
extractKeywords(tokens,
|
|
204
|
-
const stopWords = this.stopWords.get(
|
|
205
|
-
|
|
204
|
+
extractKeywords(tokens, language) {
|
|
205
|
+
const stopWords = this.stopWords.get(language) ?? /* @__PURE__ */ new Set();
|
|
206
|
+
tokens.filter((token) => {
|
|
206
207
|
return token.length > 2 && !stopWords.has(token.toLowerCase());
|
|
207
208
|
});
|
|
208
|
-
const
|
|
209
|
-
|
|
210
|
-
|
|
209
|
+
const frequency = /* @__PURE__ */ new Map();
|
|
210
|
+
keywords.forEach((keyword) => {
|
|
211
|
+
frequency.set(keyword, (frequency.get(keyword) ?? 0) + 1);
|
|
211
212
|
});
|
|
212
|
-
return Array.from(
|
|
213
|
+
return Array.from(frequency.entries()).sort((a2, b) => b[1] - a2[1]).slice(0, 10).map(([keyword]) => keyword);
|
|
213
214
|
}
|
|
214
215
|
normalizeJapanese(text) {
|
|
215
|
-
return text.replace(/[A-Za-z0-9]/g, (
|
|
216
|
-
return String.fromCharCode(
|
|
216
|
+
return text.replace(/[A-Za-z0-9]/g, (char) => {
|
|
217
|
+
return String.fromCharCode(char.charCodeAt(0) - 65248);
|
|
217
218
|
});
|
|
218
219
|
}
|
|
219
220
|
normalizeChinese(text) {
|
|
@@ -431,20 +432,20 @@ var NaturalLanguageProcessor = class {
|
|
|
431
432
|
}
|
|
432
433
|
async detectIntent(processedInput) {
|
|
433
434
|
const intents = [];
|
|
434
|
-
`${processedInput.keywords.join(" ")} ${processedInput.normalized}`;
|
|
435
|
-
if (/\b(write|create|generate|implement|build|code|program|develop)\b/i.test(
|
|
435
|
+
const _keywords = `${processedInput.keywords.join(" ")} ${processedInput.normalized}`;
|
|
436
|
+
if (/\b(write|create|generate|implement|build|code|program|develop)\b/i.test(_keywords)) {
|
|
436
437
|
intents.push("code_generation");
|
|
437
438
|
}
|
|
438
|
-
if (/\b(image|picture|photo|draw|illustrate|visual|graphic)\b/i.test(
|
|
439
|
+
if (/\b(image|picture|photo|draw|illustrate|visual|graphic)\b/i.test(_keywords)) {
|
|
439
440
|
intents.push("image_generation");
|
|
440
441
|
}
|
|
441
|
-
if (/\b(video|movie|animation|clip|film)\b/i.test(
|
|
442
|
+
if (/\b(video|movie|animation|clip|film)\b/i.test(_keywords)) {
|
|
442
443
|
intents.push("video_generation");
|
|
443
444
|
}
|
|
444
|
-
if (/\b(test|testing|unit test|integration test|e2e)\b/i.test(
|
|
445
|
+
if (/\b(test|testing|unit test|integration test|e2e)\b/i.test(_keywords)) {
|
|
445
446
|
intents.push("test_generation");
|
|
446
447
|
}
|
|
447
|
-
if (/\b(review|check|analyze|improve|refactor|optimize)\b/i.test(
|
|
448
|
+
if (/\b(review|check|analyze|improve|refactor|optimize)\b/i.test(_keywords)) {
|
|
448
449
|
intents.push("code_review");
|
|
449
450
|
}
|
|
450
451
|
return intents;
|
|
@@ -479,7 +480,7 @@ var IntentRecognizer = class {
|
|
|
479
480
|
this.initialized = true;
|
|
480
481
|
}
|
|
481
482
|
async recognize(input2) {
|
|
482
|
-
const
|
|
483
|
+
const startTime = performance.now();
|
|
483
484
|
this.metrics.totalCalls++;
|
|
484
485
|
if ((input2.normalized?.length ?? 0) > 8192) {
|
|
485
486
|
this.metrics.nullReturns++;
|
|
@@ -500,7 +501,7 @@ var IntentRecognizer = class {
|
|
|
500
501
|
const candidates = Array.from(scores.entries()).sort((a2, b) => b[1] - a2[1]).slice(0, this.config.maxAlternatives + 1);
|
|
501
502
|
if (candidates.length === 0) {
|
|
502
503
|
this.metrics.nullReturns++;
|
|
503
|
-
const elapsed2 = performance.now() -
|
|
504
|
+
const elapsed2 = performance.now() - startTime;
|
|
504
505
|
this.metrics.responseTimes.push(elapsed2);
|
|
505
506
|
return null;
|
|
506
507
|
}
|
|
@@ -513,7 +514,7 @@ var IntentRecognizer = class {
|
|
|
513
514
|
const minConfidence = 0.35;
|
|
514
515
|
if (normalizedCandidates[0]?.confidence < minConfidence) {
|
|
515
516
|
this.metrics.nullReturns++;
|
|
516
|
-
const elapsed2 = performance.now() -
|
|
517
|
+
const elapsed2 = performance.now() - startTime;
|
|
517
518
|
this.metrics.responseTimes.push(elapsed2);
|
|
518
519
|
return null;
|
|
519
520
|
}
|
|
@@ -522,7 +523,7 @@ var IntentRecognizer = class {
|
|
|
522
523
|
throw new Error("No candidates found for intent recognition");
|
|
523
524
|
}
|
|
524
525
|
const alternatives = normalizedCandidates.slice(1);
|
|
525
|
-
const elapsed = performance.now() -
|
|
526
|
+
const elapsed = performance.now() - startTime;
|
|
526
527
|
this.metrics.responseTimes.push(elapsed);
|
|
527
528
|
return {
|
|
528
529
|
command: topCandidate.command,
|
|
@@ -568,7 +569,7 @@ var IntentRecognizer = class {
|
|
|
568
569
|
}
|
|
569
570
|
});
|
|
570
571
|
}
|
|
571
|
-
calculateContextScores(
|
|
572
|
+
calculateContextScores(_input, scores) {
|
|
572
573
|
if (this.commandHistory.length > 0) {
|
|
573
574
|
const lastCommand = this.commandHistory[this.commandHistory.length - 1];
|
|
574
575
|
const relatedCommands = this.getRelatedCommands(lastCommand ?? "");
|
|
@@ -611,7 +612,7 @@ var IntentRecognizer = class {
|
|
|
611
612
|
}
|
|
612
613
|
});
|
|
613
614
|
}
|
|
614
|
-
calculateHistoricalScores(
|
|
615
|
+
calculateHistoricalScores(_input, scores) {
|
|
615
616
|
if (this.commandHistory.length === 0) {
|
|
616
617
|
return;
|
|
617
618
|
}
|
|
@@ -644,7 +645,7 @@ var IntentRecognizer = class {
|
|
|
644
645
|
};
|
|
645
646
|
return relationships[command2] ?? [];
|
|
646
647
|
}
|
|
647
|
-
generateReasoning(input2,
|
|
648
|
+
generateReasoning(input2, _command) {
|
|
648
649
|
const reasons = [];
|
|
649
650
|
if (input2.keywords.length > 0) {
|
|
650
651
|
reasons.push(`Keywords detected: ${input2.keywords.slice(0, 3).join(", ")}`);
|
|
@@ -655,7 +656,7 @@ var IntentRecognizer = class {
|
|
|
655
656
|
}
|
|
656
657
|
return reasons.join("; ");
|
|
657
658
|
}
|
|
658
|
-
async updateModel(
|
|
659
|
+
async updateModel(_input, correctCommand, _wasCorrect) {
|
|
659
660
|
this.commandHistory.push(correctCommand);
|
|
660
661
|
if (this.commandHistory.length > 100) {
|
|
661
662
|
this.commandHistory.shift();
|
|
@@ -1104,10 +1105,10 @@ var IntentRecognizer = class {
|
|
|
1104
1105
|
const knownCommands = this.dependencies.knownCommands;
|
|
1105
1106
|
const inputText = input2.normalized.trim();
|
|
1106
1107
|
knownCommands.forEach((command2) => {
|
|
1107
|
-
const
|
|
1108
|
+
const distance = this.calculateEditDistance(inputText, command2);
|
|
1108
1109
|
const commandWithoutSlash = command2.substring(1);
|
|
1109
1110
|
const distanceWithoutSlash = this.calculateEditDistance(inputText, commandWithoutSlash);
|
|
1110
|
-
const bestDistance = Math.min(
|
|
1111
|
+
const bestDistance = Math.min(distance, distanceWithoutSlash);
|
|
1111
1112
|
if (bestDistance <= 1) {
|
|
1112
1113
|
const fuzzyScore = 5;
|
|
1113
1114
|
const currentScore = scores.get(command2) ?? 0;
|
|
@@ -1143,26 +1144,26 @@ var IntentRecognizer = class {
|
|
|
1143
1144
|
|
|
1144
1145
|
// src/services/intelligent-router/analysis/ParameterExtractor.ts
|
|
1145
1146
|
var ParameterExtractor = class {
|
|
1146
|
-
async extract(input2, command2,
|
|
1147
|
+
async extract(input2, command2, language) {
|
|
1147
1148
|
switch (command2) {
|
|
1148
1149
|
case "/code":
|
|
1149
|
-
return this.extractCodeParameters(input2,
|
|
1150
|
+
return this.extractCodeParameters(input2, language);
|
|
1150
1151
|
case "/image":
|
|
1151
|
-
return this.extractImageParameters(input2,
|
|
1152
|
+
return this.extractImageParameters(input2, language);
|
|
1152
1153
|
case "/video":
|
|
1153
|
-
return this.extractVideoParameters(input2,
|
|
1154
|
+
return this.extractVideoParameters(input2, language);
|
|
1154
1155
|
case "/test":
|
|
1155
|
-
return this.extractTestParameters(input2,
|
|
1156
|
+
return this.extractTestParameters(input2, language);
|
|
1156
1157
|
case "/review":
|
|
1157
|
-
return this.extractReviewParameters(input2,
|
|
1158
|
+
return this.extractReviewParameters(input2, language);
|
|
1158
1159
|
case "/lang":
|
|
1159
|
-
return this.extractLanguageParameters(input2,
|
|
1160
|
+
return this.extractLanguageParameters(input2, language);
|
|
1160
1161
|
default:
|
|
1161
|
-
return this.extractGenericParameters(input2,
|
|
1162
|
+
return this.extractGenericParameters(input2, language);
|
|
1162
1163
|
}
|
|
1163
1164
|
}
|
|
1164
|
-
extractCodeParameters(_input,
|
|
1165
|
-
this.cleanDescription(input,
|
|
1165
|
+
extractCodeParameters(_input, language) {
|
|
1166
|
+
const _description = this.cleanDescription(input, language, [
|
|
1166
1167
|
"write",
|
|
1167
1168
|
"create",
|
|
1168
1169
|
"generate",
|
|
@@ -1192,23 +1193,14 @@ var ParameterExtractor = class {
|
|
|
1192
1193
|
"m\xE3",
|
|
1193
1194
|
"ch\u01B0\u01A1ng tr\xECnh"
|
|
1194
1195
|
]);
|
|
1195
|
-
_params.description =
|
|
1196
|
+
_params.description = _description;
|
|
1196
1197
|
this.detectProgrammingLanguage(input);
|
|
1197
|
-
if (progLang) {
|
|
1198
|
-
progLang;
|
|
1199
|
-
}
|
|
1200
1198
|
this.detectFramework(input);
|
|
1201
|
-
if (framework) {
|
|
1202
|
-
framework;
|
|
1203
|
-
}
|
|
1204
1199
|
this.extractFilePath(input);
|
|
1205
|
-
if (filePath) {
|
|
1206
|
-
filePath;
|
|
1207
|
-
}
|
|
1208
1200
|
return _params;
|
|
1209
1201
|
}
|
|
1210
|
-
extractImageParameters(_input,
|
|
1211
|
-
this.cleanDescription(input,
|
|
1202
|
+
extractImageParameters(_input, language) {
|
|
1203
|
+
const _prompt = this.cleanDescription(input, language, [
|
|
1212
1204
|
"create",
|
|
1213
1205
|
"generate",
|
|
1214
1206
|
"make",
|
|
@@ -1235,20 +1227,17 @@ var ParameterExtractor = class {
|
|
|
1235
1227
|
"h\xECnh \u1EA3nh",
|
|
1236
1228
|
"\u1EA3nh"
|
|
1237
1229
|
]);
|
|
1238
|
-
_params.prompt =
|
|
1230
|
+
_params.prompt = _prompt;
|
|
1239
1231
|
this.detectArtStyle(input);
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
}
|
|
1243
|
-
this.extractDimensions(input);
|
|
1244
|
-
if (dimensions) {
|
|
1232
|
+
const _dimensions = this.extractDimensions(input);
|
|
1233
|
+
if (_dimensions) {
|
|
1245
1234
|
dimensions.width;
|
|
1246
1235
|
_params.height = dimensions.height;
|
|
1247
1236
|
}
|
|
1248
1237
|
return _params;
|
|
1249
1238
|
}
|
|
1250
|
-
extractVideoParameters(_input,
|
|
1251
|
-
this.cleanDescription(input,
|
|
1239
|
+
extractVideoParameters(_input, language) {
|
|
1240
|
+
const _description = this.cleanDescription(input, language, [
|
|
1252
1241
|
"create",
|
|
1253
1242
|
"generate",
|
|
1254
1243
|
"make",
|
|
@@ -1272,19 +1261,13 @@ var ParameterExtractor = class {
|
|
|
1272
1261
|
"video",
|
|
1273
1262
|
"ho\u1EA1t h\xECnh"
|
|
1274
1263
|
]);
|
|
1275
|
-
_params.description =
|
|
1264
|
+
_params.description = _description;
|
|
1276
1265
|
this.extractDuration(input);
|
|
1277
|
-
if (duration) {
|
|
1278
|
-
duration;
|
|
1279
|
-
}
|
|
1280
1266
|
this.detectVideoFormat(input);
|
|
1281
|
-
if (format) {
|
|
1282
|
-
format;
|
|
1283
|
-
}
|
|
1284
1267
|
return _params;
|
|
1285
1268
|
}
|
|
1286
|
-
extractTestParameters(_input,
|
|
1287
|
-
this.cleanDescription(input,
|
|
1269
|
+
extractTestParameters(_input, language) {
|
|
1270
|
+
const _description = this.cleanDescription(input, language, [
|
|
1288
1271
|
"write",
|
|
1289
1272
|
"create",
|
|
1290
1273
|
"generate",
|
|
@@ -1304,19 +1287,13 @@ var ParameterExtractor = class {
|
|
|
1304
1287
|
"t\u1EA1o",
|
|
1305
1288
|
"ki\u1EC3m tra"
|
|
1306
1289
|
]);
|
|
1307
|
-
_params.description =
|
|
1290
|
+
_params.description = _description;
|
|
1308
1291
|
this.detectTestType(input);
|
|
1309
|
-
if (testType) {
|
|
1310
|
-
testType;
|
|
1311
|
-
}
|
|
1312
1292
|
this.extractFilePath(input);
|
|
1313
|
-
if (filePath) {
|
|
1314
|
-
filePath;
|
|
1315
|
-
}
|
|
1316
1293
|
return _params;
|
|
1317
1294
|
}
|
|
1318
|
-
extractReviewParameters(_input,
|
|
1319
|
-
this.cleanDescription(input,
|
|
1295
|
+
extractReviewParameters(_input, language) {
|
|
1296
|
+
const _description = this.cleanDescription(input, language, [
|
|
1320
1297
|
"review",
|
|
1321
1298
|
"check",
|
|
1322
1299
|
"analyze",
|
|
@@ -1339,34 +1316,26 @@ var ParameterExtractor = class {
|
|
|
1339
1316
|
"ph\xE2n t\xEDch",
|
|
1340
1317
|
"c\u1EA3i thi\u1EC7n"
|
|
1341
1318
|
]);
|
|
1342
|
-
_params.description =
|
|
1319
|
+
_params.description = _description;
|
|
1343
1320
|
this.extractFilePath(input);
|
|
1344
|
-
if (filePath) {
|
|
1345
|
-
filePath;
|
|
1346
|
-
}
|
|
1347
1321
|
this.detectReviewFocus(input);
|
|
1348
1322
|
return _params;
|
|
1349
1323
|
}
|
|
1350
|
-
extractLanguageParameters(_input,
|
|
1324
|
+
extractLanguageParameters(_input, language) {
|
|
1351
1325
|
this.extractTargetLanguage(input);
|
|
1352
|
-
if (targetLang) {
|
|
1353
|
-
targetLang;
|
|
1354
|
-
}
|
|
1355
1326
|
return _params;
|
|
1356
1327
|
}
|
|
1357
|
-
extractGenericParameters(_input,
|
|
1358
|
-
this.cleanDescription(input,
|
|
1359
|
-
_params.input =
|
|
1328
|
+
extractGenericParameters(_input, language) {
|
|
1329
|
+
const _cleanedInput = this.cleanDescription(input, language, []);
|
|
1330
|
+
_params.input = _cleanedInput;
|
|
1360
1331
|
this.extractFilePath(input);
|
|
1361
|
-
if (filePath) {
|
|
1362
|
-
filePath;
|
|
1363
|
-
}
|
|
1364
1332
|
return _params;
|
|
1365
1333
|
}
|
|
1366
|
-
cleanDescription(_input,
|
|
1334
|
+
cleanDescription(_input, _language2, keywords2) {
|
|
1367
1335
|
let cleaned = input.toLowerCase();
|
|
1368
1336
|
keywords2.forEach((keyword) => {
|
|
1369
|
-
|
|
1337
|
+
const _regex = new RegExp(`\\b${keyword}\\b`, "gi");
|
|
1338
|
+
cleaned = cleaned.replace(_regex, "");
|
|
1370
1339
|
});
|
|
1371
1340
|
cleaned = cleaned.replace(/\s+/g, " ").trim();
|
|
1372
1341
|
return cleaned;
|
|
@@ -1386,8 +1355,8 @@ var ParameterExtractor = class {
|
|
|
1386
1355
|
swift: /\b(swift)\b/i,
|
|
1387
1356
|
kotlin: /\b(kotlin)\b/i
|
|
1388
1357
|
};
|
|
1389
|
-
for (const [lang,
|
|
1390
|
-
if (
|
|
1358
|
+
for (const [lang, _pattern] of Object.entries(languages2)) {
|
|
1359
|
+
if (pattern.test(input2)) {
|
|
1391
1360
|
return lang;
|
|
1392
1361
|
}
|
|
1393
1362
|
}
|
|
@@ -1406,9 +1375,9 @@ var ParameterExtractor = class {
|
|
|
1406
1375
|
spring: /\b(spring)\b/i,
|
|
1407
1376
|
laravel: /\b(laravel)\b/i
|
|
1408
1377
|
};
|
|
1409
|
-
for (const [
|
|
1410
|
-
if (
|
|
1411
|
-
return
|
|
1378
|
+
for (const [_framework, _pattern] of Object.entries(frameworks)) {
|
|
1379
|
+
if (pattern.test(input2)) {
|
|
1380
|
+
return _framework;
|
|
1412
1381
|
}
|
|
1413
1382
|
}
|
|
1414
1383
|
return null;
|
|
@@ -1424,57 +1393,61 @@ var ParameterExtractor = class {
|
|
|
1424
1393
|
"3d": /\b(3d|three dimensional)\b/i,
|
|
1425
1394
|
pixel: /\b(pixel art|pixelated)\b/i
|
|
1426
1395
|
};
|
|
1427
|
-
for (const [
|
|
1428
|
-
if (
|
|
1429
|
-
return
|
|
1396
|
+
for (const [_style, _pattern] of Object.entries(styles)) {
|
|
1397
|
+
if (pattern.test(input2)) {
|
|
1398
|
+
return _style;
|
|
1430
1399
|
}
|
|
1431
1400
|
}
|
|
1432
1401
|
return null;
|
|
1433
1402
|
}
|
|
1434
1403
|
extractFilePath(input2) {
|
|
1435
|
-
|
|
1436
|
-
|
|
1404
|
+
const _filePattern = /(?:["'])?([/\w\-._]+\.\w+)(?:["'])?/;
|
|
1405
|
+
const _match = input2.match(_filePattern);
|
|
1406
|
+
return _match ? _match[1] : null;
|
|
1437
1407
|
}
|
|
1438
1408
|
extractDimensions(input2) {
|
|
1439
|
-
|
|
1440
|
-
|
|
1409
|
+
const _dimensionPattern = /(\d+)\s*[x×]\s*(\d+)/i;
|
|
1410
|
+
const _match = input2.match(_dimensionPattern);
|
|
1411
|
+
if (_match) {
|
|
1441
1412
|
return {
|
|
1442
|
-
width: parseInt(
|
|
1443
|
-
height: parseInt(
|
|
1413
|
+
width: parseInt(_match[1], 10),
|
|
1414
|
+
height: parseInt(_match[2], 10)
|
|
1444
1415
|
};
|
|
1445
1416
|
}
|
|
1446
1417
|
return null;
|
|
1447
1418
|
}
|
|
1448
1419
|
extractDuration(input2) {
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1420
|
+
const _durationPattern = /(\d+)\s*(seconds?|secs?|minutes?|mins?)/i;
|
|
1421
|
+
const _match = input2.match(_durationPattern);
|
|
1422
|
+
if (_match) {
|
|
1423
|
+
const _value = parseInt(_match[1], 10);
|
|
1424
|
+
_match[2].toLowerCase();
|
|
1453
1425
|
if (unit.startsWith("min")) {
|
|
1454
|
-
return
|
|
1426
|
+
return _value * 60;
|
|
1455
1427
|
}
|
|
1456
|
-
return
|
|
1428
|
+
return _value;
|
|
1457
1429
|
}
|
|
1458
1430
|
return null;
|
|
1459
1431
|
}
|
|
1460
1432
|
detectVideoFormat(input2) {
|
|
1461
|
-
|
|
1433
|
+
const _formats = ["mp4", "avi", "mov", "webm", "gif"];
|
|
1434
|
+
for (const _format of _formats) {
|
|
1462
1435
|
if (pattern.test(input2)) {
|
|
1463
|
-
return
|
|
1436
|
+
return _format;
|
|
1464
1437
|
}
|
|
1465
1438
|
}
|
|
1466
1439
|
return null;
|
|
1467
1440
|
}
|
|
1468
1441
|
detectTestType(input2) {
|
|
1469
1442
|
const types = {
|
|
1470
|
-
|
|
1443
|
+
_unit: /\b(_unit)\b/i,
|
|
1471
1444
|
integration: /\b(integration)\b/i,
|
|
1472
1445
|
e2e: /\b(e2e|end to end)\b/i,
|
|
1473
1446
|
performance: /\b(performance|perf)\b/i,
|
|
1474
1447
|
snapshot: /\b(snapshot)\b/i
|
|
1475
1448
|
};
|
|
1476
|
-
for (const [type2,
|
|
1477
|
-
if (
|
|
1449
|
+
for (const [type2, _pattern] of Object.entries(types)) {
|
|
1450
|
+
if (pattern.test(input2)) {
|
|
1478
1451
|
return type2;
|
|
1479
1452
|
}
|
|
1480
1453
|
}
|
|
@@ -1485,12 +1458,12 @@ var ParameterExtractor = class {
|
|
|
1485
1458
|
performance: /\b(performance|speed|optimization)\b/i,
|
|
1486
1459
|
security: /\b(security|vulnerability|safe)\b/i,
|
|
1487
1460
|
quality: /\b(quality|clean|maintainability)\b/i,
|
|
1488
|
-
|
|
1461
|
+
_style: /\b(_style|_format|convention)\b/i,
|
|
1489
1462
|
bugs: /\b(bugs?|errors?|issues?)\b/i
|
|
1490
1463
|
};
|
|
1491
|
-
for (const [
|
|
1492
|
-
if (
|
|
1493
|
-
return
|
|
1464
|
+
for (const [_focus, _pattern] of Object.entries(focuses)) {
|
|
1465
|
+
if (pattern.test(input2)) {
|
|
1466
|
+
return _focus;
|
|
1494
1467
|
}
|
|
1495
1468
|
}
|
|
1496
1469
|
return null;
|
|
@@ -1505,8 +1478,8 @@ var ParameterExtractor = class {
|
|
|
1505
1478
|
};
|
|
1506
1479
|
input2.toLowerCase();
|
|
1507
1480
|
for (const [code2, patterns2] of Object.entries(languageMap)) {
|
|
1508
|
-
for (const
|
|
1509
|
-
if (lowerInput.includes(
|
|
1481
|
+
for (const _pattern of patterns2) {
|
|
1482
|
+
if (lowerInput.includes(_pattern)) {
|
|
1510
1483
|
return code2;
|
|
1511
1484
|
}
|
|
1512
1485
|
}
|
|
@@ -1529,29 +1502,29 @@ var MultilingualDictionary = class {
|
|
|
1529
1502
|
this.loadTranslations();
|
|
1530
1503
|
this.initialized = true;
|
|
1531
1504
|
}
|
|
1532
|
-
getTranslation(_command,
|
|
1505
|
+
getTranslation(_command, _language2 = "en") {
|
|
1533
1506
|
return this.dictionary.get(command) ?? null;
|
|
1534
1507
|
}
|
|
1535
|
-
getExplanation(_command,
|
|
1536
|
-
this.dictionary.get(command);
|
|
1537
|
-
if (!
|
|
1508
|
+
getExplanation(_command, language = "en") {
|
|
1509
|
+
const _translation = this.dictionary.get(command);
|
|
1510
|
+
if (!_translation) {
|
|
1538
1511
|
return `Command ${command} not found`;
|
|
1539
1512
|
}
|
|
1540
|
-
return translation.description[
|
|
1513
|
+
return translation.description[language] ?? translation.description["en"] ?? "";
|
|
1541
1514
|
}
|
|
1542
|
-
getKeywords(_command,
|
|
1543
|
-
this.dictionary.get(command);
|
|
1544
|
-
if (!
|
|
1515
|
+
getKeywords(_command, language = "en") {
|
|
1516
|
+
const _translation = this.dictionary.get(command);
|
|
1517
|
+
if (!_translation) {
|
|
1545
1518
|
return [];
|
|
1546
1519
|
}
|
|
1547
|
-
return translation.keywords[
|
|
1520
|
+
return translation.keywords[language] ?? translation.keywords["en"] ?? [];
|
|
1548
1521
|
}
|
|
1549
|
-
getExamples(_command,
|
|
1550
|
-
this.dictionary.get(command);
|
|
1551
|
-
if (!
|
|
1522
|
+
getExamples(_command, language = "en") {
|
|
1523
|
+
const _translation = this.dictionary.get(command);
|
|
1524
|
+
if (!_translation) {
|
|
1552
1525
|
return [];
|
|
1553
1526
|
}
|
|
1554
|
-
return translation.examples[
|
|
1527
|
+
return translation.examples[language] ?? translation.examples["en"] ?? [];
|
|
1555
1528
|
}
|
|
1556
1529
|
getAllCommands() {
|
|
1557
1530
|
return Array.from(this.dictionary.keys());
|
|
@@ -1904,21 +1877,21 @@ var LanguageDetector = class {
|
|
|
1904
1877
|
{ language: "ko", score: 0 },
|
|
1905
1878
|
{ language: "vn", score: 0 }
|
|
1906
1879
|
];
|
|
1907
|
-
this.characterRanges.forEach((patterns2,
|
|
1880
|
+
this.characterRanges.forEach((patterns2, language) => {
|
|
1908
1881
|
patterns2.forEach((pattern2) => {
|
|
1909
1882
|
const matches2 = text.match(pattern2);
|
|
1910
1883
|
if (matches2) {
|
|
1911
|
-
const score = scores.find((s) => s.language ===
|
|
1884
|
+
const score = scores.find((s) => s.language === language);
|
|
1912
1885
|
if (score) {
|
|
1913
1886
|
score.score += matches2.length * 2;
|
|
1914
1887
|
}
|
|
1915
1888
|
}
|
|
1916
1889
|
});
|
|
1917
1890
|
});
|
|
1918
|
-
this.languagePatterns.forEach((patterns2,
|
|
1891
|
+
this.languagePatterns.forEach((patterns2, language) => {
|
|
1919
1892
|
patterns2.forEach((pattern2) => {
|
|
1920
1893
|
if (pattern2.test(text)) {
|
|
1921
|
-
const score = scores.find((s) => s.language ===
|
|
1894
|
+
const score = scores.find((s) => s.language === language);
|
|
1922
1895
|
if (score) {
|
|
1923
1896
|
score.score += 3;
|
|
1924
1897
|
}
|
|
@@ -2041,34 +2014,34 @@ var CommandMappings = class {
|
|
|
2041
2014
|
this.loadMappings();
|
|
2042
2015
|
this.initialized = true;
|
|
2043
2016
|
}
|
|
2044
|
-
async getSuggestions(_input,
|
|
2045
|
-
input.toLowerCase();
|
|
2046
|
-
const
|
|
2017
|
+
async getSuggestions(_input, language, maxResults = 5) {
|
|
2018
|
+
const _lowerInput = input.toLowerCase();
|
|
2019
|
+
const suggestions = [];
|
|
2047
2020
|
for (const mapping of this.mappings) {
|
|
2048
|
-
mapping.naturalPhrases.get(
|
|
2021
|
+
const _phrases = mapping.naturalPhrases.get(language) ?? mapping.naturalPhrases.get("en") ?? [];
|
|
2049
2022
|
let score = 0;
|
|
2050
|
-
for (const phrase2 of
|
|
2051
|
-
if (phrase2.toLowerCase().includes(
|
|
2023
|
+
for (const phrase2 of _phrases) {
|
|
2024
|
+
if (phrase2.toLowerCase().includes(_lowerInput)) {
|
|
2052
2025
|
score += 2;
|
|
2053
2026
|
}
|
|
2054
|
-
if (phrase2.toLowerCase().startsWith(
|
|
2027
|
+
if (phrase2.toLowerCase().startsWith(_lowerInput)) {
|
|
2055
2028
|
score += 3;
|
|
2056
2029
|
}
|
|
2057
2030
|
}
|
|
2058
|
-
if (mapping.command.toLowerCase().includes(
|
|
2031
|
+
if (mapping.command.toLowerCase().includes(_lowerInput)) {
|
|
2059
2032
|
score += 5;
|
|
2060
2033
|
}
|
|
2061
2034
|
if (score > 0) {
|
|
2062
|
-
|
|
2035
|
+
suggestions.push({ command: mapping.command, score: score * mapping.priority });
|
|
2063
2036
|
}
|
|
2064
2037
|
}
|
|
2065
|
-
return
|
|
2038
|
+
return suggestions.sort((a2, b) => b.score - a2.score).slice(0, maxResults).map((s) => s.command);
|
|
2066
2039
|
}
|
|
2067
|
-
getCommandForPhrase(_phrase,
|
|
2040
|
+
getCommandForPhrase(_phrase, language) {
|
|
2068
2041
|
phrase.toLowerCase();
|
|
2069
2042
|
for (const mapping of this.mappings) {
|
|
2070
|
-
mapping.naturalPhrases.get(
|
|
2071
|
-
for (const naturalPhrase of
|
|
2043
|
+
const _phrases = mapping.naturalPhrases.get(language) ?? mapping.naturalPhrases.get("en") ?? [];
|
|
2044
|
+
for (const naturalPhrase of _phrases) {
|
|
2072
2045
|
if (lowerPhrase.includes(naturalPhrase.toLowerCase())) {
|
|
2073
2046
|
return mapping.command;
|
|
2074
2047
|
}
|
|
@@ -2527,7 +2500,7 @@ var UserPatternAnalyzer = class {
|
|
|
2527
2500
|
this.initialized = true;
|
|
2528
2501
|
}
|
|
2529
2502
|
async recordPattern(_input, intent) {
|
|
2530
|
-
const
|
|
2503
|
+
const _pattern = {
|
|
2531
2504
|
input,
|
|
2532
2505
|
command: intent.command,
|
|
2533
2506
|
confidence: intent.confidence,
|
|
@@ -2535,15 +2508,15 @@ var UserPatternAnalyzer = class {
|
|
|
2535
2508
|
success: true
|
|
2536
2509
|
// Will be updated by feedback
|
|
2537
2510
|
};
|
|
2538
|
-
this.patterns.push(
|
|
2511
|
+
this.patterns.push(_pattern);
|
|
2539
2512
|
if (this.patterns.length > 1e3) {
|
|
2540
2513
|
this.patterns = this.patterns.slice(-1e3);
|
|
2541
2514
|
}
|
|
2542
2515
|
this.savePatterns();
|
|
2543
2516
|
}
|
|
2544
2517
|
async recordFeedback(_input, correctCommand, wasCorrect) {
|
|
2545
|
-
this.patterns.slice().reverse().find((p) => p.input === input);
|
|
2546
|
-
if (
|
|
2518
|
+
const _pattern = this.patterns.slice().reverse().find((p) => p.input === input);
|
|
2519
|
+
if (_pattern) {
|
|
2547
2520
|
pattern.success = wasCorrect;
|
|
2548
2521
|
if (!wasCorrect) {
|
|
2549
2522
|
this.patterns.push({
|
|
@@ -2559,9 +2532,9 @@ var UserPatternAnalyzer = class {
|
|
|
2559
2532
|
}
|
|
2560
2533
|
getPatternStats() {
|
|
2561
2534
|
const stats2 = {};
|
|
2562
|
-
this.patterns.forEach((
|
|
2563
|
-
if (
|
|
2564
|
-
stats2[
|
|
2535
|
+
this.patterns.forEach((_pattern) => {
|
|
2536
|
+
if (pattern.success) {
|
|
2537
|
+
stats2[pattern.command] = (stats2[pattern.command] ?? 0) + 1;
|
|
2565
2538
|
}
|
|
2566
2539
|
});
|
|
2567
2540
|
return stats2;
|
|
@@ -2587,13 +2560,13 @@ var UserPatternAnalyzer = class {
|
|
|
2587
2560
|
return mostCommon;
|
|
2588
2561
|
}
|
|
2589
2562
|
calculateSimilarity(_str1, str2) {
|
|
2590
|
-
str1.length > str2.length ? str1 : str2;
|
|
2591
|
-
str1.length > str2.length ? str2 : str1;
|
|
2563
|
+
const _longer = str1.length > str2.length ? str1 : str2;
|
|
2564
|
+
const _shorter = str1.length > str2.length ? str2 : str1;
|
|
2592
2565
|
if (longer.length === 0) {
|
|
2593
2566
|
return 1;
|
|
2594
2567
|
}
|
|
2595
|
-
this.levenshteinDistance(
|
|
2596
|
-
return (longer.length -
|
|
2568
|
+
const _distance = this.levenshteinDistance(_longer, _shorter);
|
|
2569
|
+
return (longer.length - _distance) / longer.length;
|
|
2597
2570
|
}
|
|
2598
2571
|
levenshteinDistance(_str1, str2) {
|
|
2599
2572
|
const matrix = [];
|
|
@@ -2695,38 +2668,39 @@ var IntelligentRouterService = class extends EventEmitter {
|
|
|
2695
2668
|
if (!this.isInitialized) {
|
|
2696
2669
|
await this.initialize();
|
|
2697
2670
|
}
|
|
2671
|
+
const _startTime = Date.now();
|
|
2698
2672
|
this.metrics.totalRequests++;
|
|
2699
2673
|
try {
|
|
2700
|
-
const
|
|
2701
|
-
if (!this.config.supportedLanguages.includes(
|
|
2674
|
+
const _language2 = await this.languageDetector.detect(input2);
|
|
2675
|
+
if (!this.config.supportedLanguages.includes(_language2)) {
|
|
2702
2676
|
}
|
|
2703
|
-
const processedInput = await this.nlpProcessor.process(input2,
|
|
2677
|
+
const processedInput = await this.nlpProcessor.process(input2, _language2);
|
|
2704
2678
|
const intent = await this.intentRecognizer.recognize(processedInput);
|
|
2705
2679
|
if (!intent || intent.confidence < this.config.confidenceThreshold) {
|
|
2706
2680
|
this.metrics.failedRoutes++;
|
|
2707
|
-
this.emit("route:failed", { input: input2,
|
|
2681
|
+
this.emit("route:failed", { input: input2, _language: _language2, confidence: intent?.confidence ?? 0 });
|
|
2708
2682
|
return null;
|
|
2709
2683
|
}
|
|
2710
|
-
const _parameters = await this.parameterExtractor.extract(input2, intent.command,
|
|
2684
|
+
const _parameters = await this.parameterExtractor.extract(input2, intent.command, _language2);
|
|
2711
2685
|
const commandIntent = {
|
|
2712
2686
|
command: intent.command,
|
|
2713
2687
|
confidence: intent.confidence,
|
|
2714
|
-
|
|
2688
|
+
_parameters,
|
|
2715
2689
|
originalInput: input2,
|
|
2716
|
-
|
|
2690
|
+
_language: _language2,
|
|
2717
2691
|
alternatives: intent.alternatives
|
|
2718
2692
|
};
|
|
2719
2693
|
if (this.config.enableLearning) {
|
|
2720
2694
|
await this.userPatternAnalyzer.recordPattern(input2, commandIntent);
|
|
2721
2695
|
}
|
|
2722
2696
|
this.metrics.successfulRoutes++;
|
|
2723
|
-
this.updateMetrics(intent.confidence, Date.now() -
|
|
2697
|
+
this.updateMetrics(intent.confidence, Date.now() - _startTime, intent.command);
|
|
2724
2698
|
this.emit("route:success", commandIntent);
|
|
2725
2699
|
return commandIntent;
|
|
2726
2700
|
} catch (_error) {
|
|
2727
2701
|
this.metrics.failedRoutes++;
|
|
2728
|
-
this.emit("route:
|
|
2729
|
-
console.error(chalk2.red("Routing
|
|
2702
|
+
this.emit("route:_error", { input: input2, _error });
|
|
2703
|
+
console.error(chalk2.red("Routing _error:"), _error);
|
|
2730
2704
|
return null;
|
|
2731
2705
|
}
|
|
2732
2706
|
}
|
|
@@ -2738,25 +2712,25 @@ var IntelligentRouterService = class extends EventEmitter {
|
|
|
2738
2712
|
const _language2 = await this.languageDetector.detect(partialInput);
|
|
2739
2713
|
const _suggestions = await this.commandMappings.getSuggestions(
|
|
2740
2714
|
partialInput,
|
|
2741
|
-
|
|
2715
|
+
_language2,
|
|
2742
2716
|
this.config.maxAlternatives
|
|
2743
2717
|
);
|
|
2744
|
-
return
|
|
2718
|
+
return _suggestions;
|
|
2745
2719
|
} catch (_error) {
|
|
2746
|
-
console.error("Failed to get
|
|
2720
|
+
console.error("Failed to get _suggestions:", _error);
|
|
2747
2721
|
return [];
|
|
2748
2722
|
}
|
|
2749
2723
|
}
|
|
2750
|
-
async getCommandExplanation(_command,
|
|
2751
|
-
return this.dictionary.getExplanation(command,
|
|
2724
|
+
async getCommandExplanation(_command, language = "en") {
|
|
2725
|
+
return this.dictionary.getExplanation(command, language);
|
|
2752
2726
|
}
|
|
2753
2727
|
async needsConfirmation(intent) {
|
|
2754
2728
|
if (!this.config.enableConfirmation) {
|
|
2755
2729
|
return false;
|
|
2756
2730
|
}
|
|
2757
|
-
destructiveCommands.includes(intent.command);
|
|
2758
|
-
intent.confidence < 0.9;
|
|
2759
|
-
return
|
|
2731
|
+
const _isDestructive = destructiveCommands.includes(intent.command);
|
|
2732
|
+
const _isLowConfidence = intent.confidence < 0.9;
|
|
2733
|
+
return _isDestructive || _isLowConfidence;
|
|
2760
2734
|
}
|
|
2761
2735
|
getMetrics() {
|
|
2762
2736
|
return { ...this.metrics };
|
|
@@ -2772,12 +2746,12 @@ var IntelligentRouterService = class extends EventEmitter {
|
|
|
2772
2746
|
};
|
|
2773
2747
|
}
|
|
2774
2748
|
updateMetrics(_confidence, responseTime, command2) {
|
|
2775
|
-
this.metrics.averageConfidence * (this.metrics.successfulRoutes - 1);
|
|
2776
|
-
this.metrics.averageConfidence = (
|
|
2777
|
-
this.metrics.averageResponseTime * (this.metrics.successfulRoutes - 1);
|
|
2778
|
-
this.metrics.averageResponseTime = (
|
|
2779
|
-
this.metrics.commandUsageStats.get(command2) ?? 0;
|
|
2780
|
-
this.metrics.commandUsageStats.set(command2,
|
|
2749
|
+
const _totalConfidence = this.metrics.averageConfidence * (this.metrics.successfulRoutes - 1);
|
|
2750
|
+
this.metrics.averageConfidence = (_totalConfidence + confidence) / this.metrics.successfulRoutes;
|
|
2751
|
+
const _totalResponseTime = this.metrics.averageResponseTime * (this.metrics.successfulRoutes - 1);
|
|
2752
|
+
this.metrics.averageResponseTime = (_totalResponseTime + responseTime) / this.metrics.successfulRoutes;
|
|
2753
|
+
const _currentCount = this.metrics.commandUsageStats.get(command2) ?? 0;
|
|
2754
|
+
this.metrics.commandUsageStats.set(command2, _currentCount + 1);
|
|
2781
2755
|
}
|
|
2782
2756
|
async trainOnFeedback(_input, correctCommand, wasCorrect) {
|
|
2783
2757
|
if (!this.config.enableLearning) {
|
|
@@ -2803,8 +2777,8 @@ var IntelligentRouterService = class extends EventEmitter {
|
|
|
2803
2777
|
getSupportedLanguages() {
|
|
2804
2778
|
return [...this.config.supportedLanguages];
|
|
2805
2779
|
}
|
|
2806
|
-
isLanguageSupported(
|
|
2807
|
-
return this.config.supportedLanguages.includes(
|
|
2780
|
+
isLanguageSupported(language) {
|
|
2781
|
+
return this.config.supportedLanguages.includes(language);
|
|
2808
2782
|
}
|
|
2809
2783
|
async exportLearningData() {
|
|
2810
2784
|
return this.userPatternAnalyzer.exportData();
|
|
@@ -2839,7 +2813,7 @@ var System1MemoryManager = class {
|
|
|
2839
2813
|
this.interactionHistory = {
|
|
2840
2814
|
sessions: [],
|
|
2841
2815
|
commands: [],
|
|
2842
|
-
|
|
2816
|
+
_patterns: []
|
|
2843
2817
|
};
|
|
2844
2818
|
this.patternLibrary = {
|
|
2845
2819
|
codePatterns: [],
|
|
@@ -2850,7 +2824,7 @@ var System1MemoryManager = class {
|
|
|
2850
2824
|
this.userPreferences = this.initializeDefaultPreferences();
|
|
2851
2825
|
}
|
|
2852
2826
|
get programmingConcepts() {
|
|
2853
|
-
return Array.from(this.knowledgeNodes.values()).filter((
|
|
2827
|
+
return Array.from(this.knowledgeNodes.values()).filter((_node) => ["function", "class", "module", "concept"].includes(node.type)).sort((a2, b) => b.confidence - a2.confidence);
|
|
2854
2828
|
}
|
|
2855
2829
|
get businessLogic() {
|
|
2856
2830
|
return this.conceptGraph;
|
|
@@ -2862,61 +2836,62 @@ var System1MemoryManager = class {
|
|
|
2862
2836
|
return this.patternLibrary;
|
|
2863
2837
|
}
|
|
2864
2838
|
// Knowledge Node Management
|
|
2865
|
-
async addKnowledgeNode(type2,
|
|
2866
|
-
const
|
|
2867
|
-
id: this.generateNodeId(type2,
|
|
2839
|
+
async addKnowledgeNode(type2, name, content, embedding, metadata = {}) {
|
|
2840
|
+
const _node = {
|
|
2841
|
+
id: this.generateNodeId(type2, name),
|
|
2868
2842
|
type: type2,
|
|
2869
|
-
name
|
|
2870
|
-
content
|
|
2843
|
+
name,
|
|
2844
|
+
content,
|
|
2871
2845
|
embedding,
|
|
2872
|
-
|
|
2846
|
+
_confidence: 0.8,
|
|
2873
2847
|
lastAccessed: /* @__PURE__ */ new Date(),
|
|
2874
2848
|
accessCount: 1,
|
|
2875
2849
|
metadata: {
|
|
2876
2850
|
complexity: "medium",
|
|
2877
|
-
|
|
2851
|
+
_quality: 0.8,
|
|
2878
2852
|
relevance: 0.8,
|
|
2879
2853
|
...metadata
|
|
2880
2854
|
}
|
|
2881
2855
|
};
|
|
2882
|
-
this.knowledgeNodes.set(
|
|
2883
|
-
this.conceptGraph.nodes.set(
|
|
2856
|
+
this.knowledgeNodes.set(node.id, _node);
|
|
2857
|
+
this.conceptGraph.nodes.set(node.id, _node);
|
|
2884
2858
|
if (this.knowledgeNodes.size > this.config.maxKnowledgeNodes) {
|
|
2885
2859
|
await this.cleanupLeastUsedNodes();
|
|
2886
2860
|
}
|
|
2887
|
-
return
|
|
2861
|
+
return _node;
|
|
2888
2862
|
}
|
|
2889
2863
|
async getKnowledgeNode(id2) {
|
|
2890
|
-
this.knowledgeNodes.get(id2);
|
|
2891
|
-
if (
|
|
2864
|
+
const _node = this.knowledgeNodes.get(id2);
|
|
2865
|
+
if (_node) {
|
|
2892
2866
|
node.lastAccessed = /* @__PURE__ */ new Date();
|
|
2893
2867
|
node.accessCount++;
|
|
2894
2868
|
this.lastAccessTimes.set(id2, /* @__PURE__ */ new Date());
|
|
2895
|
-
this.applyAccessDecay(
|
|
2869
|
+
this.applyAccessDecay(_node);
|
|
2896
2870
|
}
|
|
2897
|
-
return
|
|
2871
|
+
return _node || null;
|
|
2898
2872
|
}
|
|
2899
2873
|
async searchKnowledgeNodes(query, queryEmbedding, limit = 10) {
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2874
|
+
const _cacheKey = `search:${query}:${limit}`;
|
|
2875
|
+
const _cached = this.cache.get(_cacheKey);
|
|
2876
|
+
if (_cached) {
|
|
2877
|
+
return _cached;
|
|
2903
2878
|
}
|
|
2904
|
-
Array.from(this.knowledgeNodes.values()).map((node2) => ({
|
|
2879
|
+
const _results = Array.from(this.knowledgeNodes.values()).map((node2) => ({
|
|
2905
2880
|
node: node2,
|
|
2906
2881
|
similarity: this.calculateCosineSimilarity(queryEmbedding, node2.embedding)
|
|
2907
|
-
})).filter(({ similarity }) => similarity > 0.5).sort((a2, b) => b.similarity - a2.similarity).slice(0, limit).map(({
|
|
2908
|
-
this.cache.set(
|
|
2909
|
-
return
|
|
2882
|
+
})).filter(({ similarity }) => similarity > 0.5).sort((a2, b) => b.similarity - a2.similarity).slice(0, limit).map(({ _node }) => _node);
|
|
2883
|
+
this.cache.set(_cacheKey, _results);
|
|
2884
|
+
return _results;
|
|
2910
2885
|
}
|
|
2911
2886
|
async updateKnowledgeNode(_id, updates) {
|
|
2912
|
-
this.knowledgeNodes.get(id);
|
|
2913
|
-
if (!
|
|
2887
|
+
const _node = this.knowledgeNodes.get(id);
|
|
2888
|
+
if (!_node) {
|
|
2914
2889
|
return false;
|
|
2915
2890
|
}
|
|
2916
|
-
Object.assign(
|
|
2891
|
+
Object.assign(_node, updates);
|
|
2917
2892
|
node.lastAccessed = /* @__PURE__ */ new Date();
|
|
2918
|
-
this.conceptGraph.nodes.set(id,
|
|
2919
|
-
this.invalidateCache(`
|
|
2893
|
+
this.conceptGraph.nodes.set(id, _node);
|
|
2894
|
+
this.invalidateCache(`_node:${id}`);
|
|
2920
2895
|
return true;
|
|
2921
2896
|
}
|
|
2922
2897
|
// Concept Graph Management
|
|
@@ -2933,11 +2908,12 @@ var System1MemoryManager = class {
|
|
|
2933
2908
|
return edge;
|
|
2934
2909
|
}
|
|
2935
2910
|
async getRelatedConcepts(_nodeId, maxDepth = 2) {
|
|
2936
|
-
`
|
|
2937
|
-
this.cache.get(
|
|
2938
|
-
if (
|
|
2939
|
-
return
|
|
2911
|
+
const _cacheKey = `_related:${nodeId}:${maxDepth}`;
|
|
2912
|
+
const _cached = this.cache.get(_cacheKey);
|
|
2913
|
+
if (_cached) {
|
|
2914
|
+
return _cached;
|
|
2940
2915
|
}
|
|
2916
|
+
const _related = /* @__PURE__ */ new Set();
|
|
2941
2917
|
const queue = [{ id: nodeId, depth: 0 }];
|
|
2942
2918
|
while (queue.length > 0) {
|
|
2943
2919
|
const { id: id2, depth } = queue.shift();
|
|
@@ -2956,9 +2932,9 @@ var System1MemoryManager = class {
|
|
|
2956
2932
|
}
|
|
2957
2933
|
}
|
|
2958
2934
|
}
|
|
2959
|
-
Array.from(
|
|
2960
|
-
this.cache.set(
|
|
2961
|
-
return
|
|
2935
|
+
const _results = Array.from(_related).map((id2) => this.knowledgeNodes.get(id2)).filter((node2) => node2 !== void 0);
|
|
2936
|
+
this.cache.set(_cacheKey, _results);
|
|
2937
|
+
return _results;
|
|
2962
2938
|
}
|
|
2963
2939
|
// Pattern Management
|
|
2964
2940
|
async addCodePattern(_pattern) {
|
|
@@ -2969,34 +2945,36 @@ var System1MemoryManager = class {
|
|
|
2969
2945
|
this.patternLibrary.codePatterns.push(codePattern);
|
|
2970
2946
|
return codePattern;
|
|
2971
2947
|
}
|
|
2972
|
-
async findCodePatterns(
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2948
|
+
async findCodePatterns(language, framework, useCase, limit = 10) {
|
|
2949
|
+
const _cacheKey = `_patterns:${language}:${framework}:${useCase}:${limit}`;
|
|
2950
|
+
const _cached = this.cache.get(_cacheKey);
|
|
2951
|
+
if (_cached) {
|
|
2952
|
+
return _cached;
|
|
2976
2953
|
}
|
|
2977
|
-
let
|
|
2978
|
-
if (
|
|
2979
|
-
|
|
2954
|
+
let _patterns = this.patternLibrary.codePatterns;
|
|
2955
|
+
if (language) {
|
|
2956
|
+
_patterns = patterns.filter((p) => p.language === language);
|
|
2980
2957
|
}
|
|
2981
|
-
if (
|
|
2982
|
-
|
|
2958
|
+
if (framework) {
|
|
2959
|
+
_patterns = patterns.filter((p) => p.framework === framework);
|
|
2983
2960
|
}
|
|
2984
2961
|
if (useCase) {
|
|
2985
|
-
|
|
2962
|
+
_patterns = patterns.filter((p) => p.useCase.toLowerCase().includes(useCase.toLowerCase()));
|
|
2986
2963
|
}
|
|
2987
|
-
|
|
2988
|
-
|
|
2964
|
+
const _results = _patterns.sort((a2, b) => {
|
|
2965
|
+
const _complexityWeight = { beginner: 3, intermediate: 2, advanced: 1 };
|
|
2966
|
+
return (_complexityWeight[a2.complexity] || 0) - (_complexityWeight[b.complexity] || 0);
|
|
2989
2967
|
}).slice(0, limit);
|
|
2990
|
-
this.cache.set(
|
|
2991
|
-
return
|
|
2968
|
+
this.cache.set(_cacheKey, _results);
|
|
2969
|
+
return _results;
|
|
2992
2970
|
}
|
|
2993
2971
|
async addAntiPattern(_antiPattern) {
|
|
2994
|
-
const
|
|
2972
|
+
const _pattern = {
|
|
2995
2973
|
id: this.generatePatternId(antiPattern.name),
|
|
2996
2974
|
...antiPattern
|
|
2997
2975
|
};
|
|
2998
|
-
this.patternLibrary.antiPatterns.push(
|
|
2999
|
-
return
|
|
2976
|
+
this.patternLibrary.antiPatterns.push(_pattern);
|
|
2977
|
+
return _pattern;
|
|
3000
2978
|
}
|
|
3001
2979
|
async detectAntiPatterns(code2) {
|
|
3002
2980
|
const detected = [];
|
|
@@ -3009,12 +2987,13 @@ var System1MemoryManager = class {
|
|
|
3009
2987
|
break;
|
|
3010
2988
|
}
|
|
3011
2989
|
} catch (_error) {
|
|
3012
|
-
console.warn(`Invalid
|
|
2990
|
+
console.warn(`Invalid _regex _pattern: ${rule.pattern}`, _error);
|
|
3013
2991
|
}
|
|
3014
2992
|
}
|
|
3015
2993
|
}
|
|
3016
2994
|
return detected.sort((a2, b) => {
|
|
3017
|
-
|
|
2995
|
+
const _severityWeight = { critical: 4, high: 3, medium: 2, low: 1 };
|
|
2996
|
+
return (_severityWeight[b.severity] || 0) - (_severityWeight[a2.severity] || 0);
|
|
3018
2997
|
});
|
|
3019
2998
|
}
|
|
3020
2999
|
// Interaction History Management
|
|
@@ -3033,7 +3012,7 @@ var System1MemoryManager = class {
|
|
|
3033
3012
|
if (!commandHist) {
|
|
3034
3013
|
commandHist = {
|
|
3035
3014
|
command: command2,
|
|
3036
|
-
|
|
3015
|
+
_frequency: 0,
|
|
3037
3016
|
lastUsed: /* @__PURE__ */ new Date(),
|
|
3038
3017
|
successRate: 1,
|
|
3039
3018
|
averageExecutionTime: 0,
|
|
@@ -3076,35 +3055,36 @@ var System1MemoryManager = class {
|
|
|
3076
3055
|
// Performance Optimization
|
|
3077
3056
|
async cleanupLeastUsedNodes() {
|
|
3078
3057
|
Array.from(this.knowledgeNodes.entries());
|
|
3079
|
-
nodeEntries.sort((a2, b) => {
|
|
3080
|
-
this.calculateUsageScore(a2[1]);
|
|
3081
|
-
this.calculateUsageScore(b[1]);
|
|
3082
|
-
return
|
|
3058
|
+
const _sortedByUsage = nodeEntries.sort((a2, b) => {
|
|
3059
|
+
const _aScore = this.calculateUsageScore(a2[1]);
|
|
3060
|
+
const _bScore = this.calculateUsageScore(b[1]);
|
|
3061
|
+
return _aScore - _bScore;
|
|
3083
3062
|
});
|
|
3084
|
-
Math.floor(this.config.maxKnowledgeNodes * 0.1);
|
|
3085
|
-
for (let i = 0; i <
|
|
3086
|
-
|
|
3087
|
-
if (
|
|
3088
|
-
const [nodeId2] =
|
|
3063
|
+
const _removeCount = Math.floor(this.config.maxKnowledgeNodes * 0.1);
|
|
3064
|
+
for (let i = 0; i < _removeCount && i < sortedByUsage.length; i++) {
|
|
3065
|
+
const _entry = _sortedByUsage[i];
|
|
3066
|
+
if (_entry) {
|
|
3067
|
+
const [nodeId2] = _entry;
|
|
3089
3068
|
this.knowledgeNodes.delete(nodeId2);
|
|
3090
3069
|
this.conceptGraph.nodes.delete(nodeId2);
|
|
3091
|
-
this.invalidateCache(`
|
|
3070
|
+
this.invalidateCache(`_node:${nodeId2}`);
|
|
3092
3071
|
}
|
|
3093
3072
|
}
|
|
3094
3073
|
}
|
|
3095
3074
|
async compressMemory() {
|
|
3075
|
+
const _cutoffDate = new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3);
|
|
3096
3076
|
this.interactionHistory.sessions = this.interactionHistory.sessions.filter(
|
|
3097
|
-
(session) => session.startTime >
|
|
3077
|
+
(session) => session.startTime > _cutoffDate
|
|
3098
3078
|
);
|
|
3099
3079
|
await this.mergeimilarPatterns();
|
|
3100
3080
|
this.cache.clear();
|
|
3101
3081
|
}
|
|
3102
3082
|
// Private Helper Methods
|
|
3103
|
-
generateNodeId(_type,
|
|
3104
|
-
return `${type}:${
|
|
3083
|
+
generateNodeId(_type, name) {
|
|
3084
|
+
return `${type}:${name}:${Date.now()}`;
|
|
3105
3085
|
}
|
|
3106
|
-
generatePatternId(
|
|
3107
|
-
return `
|
|
3086
|
+
generatePatternId(name) {
|
|
3087
|
+
return `_pattern:${name}:${Date.now()}`;
|
|
3108
3088
|
}
|
|
3109
3089
|
calculateCosineSimilarity(_a, b) {
|
|
3110
3090
|
if (a.length !== b.length) {
|
|
@@ -3114,26 +3094,26 @@ var System1MemoryManager = class {
|
|
|
3114
3094
|
let normA = 0;
|
|
3115
3095
|
let normB = 0;
|
|
3116
3096
|
for (let i = 0; i < a.length && i < b.length; i++) {
|
|
3117
|
-
a[i] ?? 0;
|
|
3118
|
-
b[i] ?? 0;
|
|
3119
|
-
dotProduct +=
|
|
3120
|
-
normA +=
|
|
3121
|
-
normB +=
|
|
3097
|
+
const _aVal = a[i] ?? 0;
|
|
3098
|
+
const _bVal = b[i] ?? 0;
|
|
3099
|
+
dotProduct += _aVal * _bVal;
|
|
3100
|
+
normA += _aVal * _aVal;
|
|
3101
|
+
normB += _bVal * _bVal;
|
|
3122
3102
|
}
|
|
3123
3103
|
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
|
|
3124
3104
|
}
|
|
3125
|
-
applyAccessDecay(
|
|
3126
|
-
(Date.now() -
|
|
3127
|
-
Math.exp(-this.config.accessDecayRate *
|
|
3128
|
-
|
|
3129
|
-
|
|
3105
|
+
applyAccessDecay(_node) {
|
|
3106
|
+
const _daysSinceAccess = (Date.now() - node.lastAccessed.getTime()) / (1e3 * 60 * 60 * 24);
|
|
3107
|
+
const _decayFactor = Math.exp(-this.config.accessDecayRate * _daysSinceAccess);
|
|
3108
|
+
node.confidence *= _decayFactor;
|
|
3109
|
+
node.confidence = Math.max(node.confidence, 0.1);
|
|
3130
3110
|
}
|
|
3131
|
-
calculateUsageScore(
|
|
3132
|
-
(Date.now() -
|
|
3133
|
-
Math.log(
|
|
3134
|
-
|
|
3135
|
-
|
|
3136
|
-
return (
|
|
3111
|
+
calculateUsageScore(_node) {
|
|
3112
|
+
const _recency = (Date.now() - node.lastAccessed.getTime()) / (1e3 * 60 * 60 * 24);
|
|
3113
|
+
const _frequency = Math.log(node.accessCount + 1);
|
|
3114
|
+
const _confidence = node.confidence;
|
|
3115
|
+
const _quality = node.metadata.quality;
|
|
3116
|
+
return (_frequency + _confidence + _quality) / (1 + _recency * 0.1);
|
|
3137
3117
|
}
|
|
3138
3118
|
invalidateCache(pattern2) {
|
|
3139
3119
|
for (const key of this.cache.keys()) {
|
|
@@ -3143,47 +3123,47 @@ var System1MemoryManager = class {
|
|
|
3143
3123
|
}
|
|
3144
3124
|
}
|
|
3145
3125
|
async detectUsagePatterns() {
|
|
3146
|
-
this.interactionHistory.sessions.slice(-20);
|
|
3147
|
-
for (const session of
|
|
3148
|
-
session.startTime.getHours();
|
|
3149
|
-
hourlyUsage.set(
|
|
3126
|
+
const _recentSessions = this.interactionHistory.sessions.slice(-20);
|
|
3127
|
+
for (const session of _recentSessions) {
|
|
3128
|
+
const _hour = session.startTime.getHours();
|
|
3129
|
+
hourlyUsage.set(_hour, (hourlyUsage.get(_hour) || 0) + 1);
|
|
3150
3130
|
}
|
|
3151
|
-
for (const session of
|
|
3131
|
+
for (const session of _recentSessions) {
|
|
3152
3132
|
for (let i = 0; i < session.commands.length - 1; i++) {
|
|
3153
|
-
`${session.commands[i]} -> ${session.commands[i + 1]}`;
|
|
3154
|
-
sequences.set(
|
|
3133
|
+
const _sequence = `${session.commands[i]} -> ${session.commands[i + 1]}`;
|
|
3134
|
+
sequences.set(_sequence, (sequences.get(_sequence) || 0) + 1);
|
|
3155
3135
|
}
|
|
3156
3136
|
}
|
|
3157
|
-
for (const [
|
|
3158
|
-
if (
|
|
3159
|
-
const
|
|
3160
|
-
id: `seq:${
|
|
3137
|
+
for (const [_sequence, _frequency] of sequences.entries()) {
|
|
3138
|
+
if (_frequency >= 3) {
|
|
3139
|
+
const _pattern = {
|
|
3140
|
+
id: `seq:${_sequence}:${Date.now()}`,
|
|
3161
3141
|
type: "sequential",
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3142
|
+
_pattern: _sequence,
|
|
3143
|
+
_frequency,
|
|
3144
|
+
_confidence: Math.min(_frequency / 10, 1),
|
|
3165
3145
|
conditions: []
|
|
3166
3146
|
};
|
|
3167
|
-
this.interactionHistory.patterns.push(
|
|
3147
|
+
this.interactionHistory.patterns.push(_pattern);
|
|
3168
3148
|
}
|
|
3169
3149
|
}
|
|
3170
3150
|
}
|
|
3171
3151
|
async processCodeGenerationEvent(event) {
|
|
3172
3152
|
event.data;
|
|
3173
3153
|
if (data.code && data.language) {
|
|
3174
|
-
this.extractCodePatterns(data.code, data.language);
|
|
3175
|
-
for (const
|
|
3176
|
-
await this.addCodePattern(
|
|
3154
|
+
const _patterns = this.extractCodePatterns(data.code, data.language);
|
|
3155
|
+
for (const _pattern of _patterns) {
|
|
3156
|
+
await this.addCodePattern(_pattern);
|
|
3177
3157
|
}
|
|
3178
3158
|
}
|
|
3179
3159
|
}
|
|
3180
3160
|
async processPatternRecognitionEvent(event) {
|
|
3181
3161
|
event.data;
|
|
3182
3162
|
if (data.patternId) {
|
|
3183
|
-
this.patternLibrary.codePatterns.find((p) => p.id === data.patternId);
|
|
3184
|
-
if (
|
|
3185
|
-
data.success ? 0.1 : -0.05;
|
|
3186
|
-
console.log(`Pattern ${data.patternId}
|
|
3163
|
+
const _pattern = this.patternLibrary.codePatterns.find((p) => p.id === data.patternId);
|
|
3164
|
+
if (_pattern && data.success !== void 0) {
|
|
3165
|
+
const _adjustment = data.success ? 0.1 : -0.05;
|
|
3166
|
+
console.log(`Pattern ${data.patternId} _adjustment: ${_adjustment}`);
|
|
3187
3167
|
}
|
|
3188
3168
|
}
|
|
3189
3169
|
}
|
|
@@ -3193,15 +3173,15 @@ var System1MemoryManager = class {
|
|
|
3193
3173
|
await this.adaptUserPreferences(data.preference, data.value, data.confidence || 0.8);
|
|
3194
3174
|
}
|
|
3195
3175
|
}
|
|
3196
|
-
extractCodePatterns(_code,
|
|
3197
|
-
const
|
|
3198
|
-
let
|
|
3199
|
-
while ((
|
|
3200
|
-
|
|
3201
|
-
name: `Function: ${
|
|
3202
|
-
description: `Function
|
|
3203
|
-
code:
|
|
3204
|
-
language
|
|
3176
|
+
extractCodePatterns(_code, language) {
|
|
3177
|
+
const _patterns = [];
|
|
3178
|
+
let match;
|
|
3179
|
+
while ((match = functionRegex.exec(code)) !== null) {
|
|
3180
|
+
patterns.push({
|
|
3181
|
+
name: `Function: ${match[1]}`,
|
|
3182
|
+
description: `Function _pattern extracted from code`,
|
|
3183
|
+
code: match[0],
|
|
3184
|
+
language,
|
|
3205
3185
|
useCase: "Function definition",
|
|
3206
3186
|
complexity: "intermediate",
|
|
3207
3187
|
performance: {
|
|
@@ -3211,44 +3191,44 @@ var System1MemoryManager = class {
|
|
|
3211
3191
|
examples: []
|
|
3212
3192
|
});
|
|
3213
3193
|
}
|
|
3214
|
-
return
|
|
3194
|
+
return _patterns;
|
|
3215
3195
|
}
|
|
3216
|
-
async adaptUserPreferences(preference,
|
|
3217
|
-
console.log(`Adapting preference ${preference} to ${
|
|
3196
|
+
async adaptUserPreferences(preference, value, confidence2) {
|
|
3197
|
+
console.log(`Adapting preference ${preference} to ${value} (_confidence: ${confidence2})`);
|
|
3218
3198
|
}
|
|
3219
3199
|
async mergeimilarPatterns() {
|
|
3220
|
-
this.patternLibrary.codePatterns;
|
|
3200
|
+
const _patterns = this.patternLibrary.codePatterns;
|
|
3221
3201
|
const merged = [];
|
|
3222
3202
|
for (let i = 0; i < patterns.length; i++) {
|
|
3223
|
-
|
|
3224
|
-
if (!
|
|
3203
|
+
const _currentPattern = _patterns[i];
|
|
3204
|
+
if (!_currentPattern || processed.has(currentPattern.id)) {
|
|
3225
3205
|
continue;
|
|
3226
3206
|
}
|
|
3227
|
-
|
|
3228
|
-
(p) => p && !processed.has(p.id) && p.language === currentPattern.language && this.calculatePatternSimilarity(
|
|
3207
|
+
const _similar = _patterns.slice(i + 1).filter(
|
|
3208
|
+
(p) => p && !processed.has(p.id) && p.language === currentPattern.language && this.calculatePatternSimilarity(_currentPattern, p) > 0.8
|
|
3229
3209
|
);
|
|
3230
3210
|
if (similar.length > 0) {
|
|
3231
|
-
this.mergePatterns(
|
|
3232
|
-
merged.push(
|
|
3211
|
+
const _mergedPattern = this.mergePatterns(_currentPattern, _similar);
|
|
3212
|
+
merged.push(_mergedPattern);
|
|
3233
3213
|
processed.add(currentPattern.id);
|
|
3234
3214
|
similar.forEach((p) => processed.add(p.id));
|
|
3235
3215
|
} else {
|
|
3236
|
-
merged.push(
|
|
3216
|
+
merged.push(_currentPattern);
|
|
3237
3217
|
processed.add(currentPattern.id);
|
|
3238
3218
|
}
|
|
3239
3219
|
}
|
|
3240
3220
|
this.patternLibrary.codePatterns = merged;
|
|
3241
3221
|
}
|
|
3242
3222
|
calculatePatternSimilarity(_a, b) {
|
|
3243
|
-
a.name.toLowerCase().includes(b.name.toLowerCase()) || b.name.toLowerCase().includes(a.name.toLowerCase());
|
|
3244
|
-
a.useCase.toLowerCase() === b.useCase.toLowerCase();
|
|
3245
|
-
return (
|
|
3223
|
+
const _namesSimilar = a.name.toLowerCase().includes(b.name.toLowerCase()) || b.name.toLowerCase().includes(a.name.toLowerCase());
|
|
3224
|
+
const _useCasesSimilar = a.useCase.toLowerCase() === b.useCase.toLowerCase();
|
|
3225
|
+
return (_namesSimilar ? 0.5 : 0) + (_useCasesSimilar ? 0.5 : 0);
|
|
3246
3226
|
}
|
|
3247
|
-
mergePatterns(_primary,
|
|
3227
|
+
mergePatterns(_primary, _similar) {
|
|
3248
3228
|
return {
|
|
3249
3229
|
...primary,
|
|
3250
|
-
description: `${primary.description} (merged from ${
|
|
3251
|
-
examples: [...primary.examples, ...
|
|
3230
|
+
description: `${primary.description} (merged from ${similar.length + 1} _patterns)`,
|
|
3231
|
+
examples: [...primary.examples, ...similar.flatMap((p) => p.examples)]
|
|
3252
3232
|
};
|
|
3253
3233
|
}
|
|
3254
3234
|
initializeDefaultPreferences() {
|
|
@@ -3256,8 +3236,8 @@ var System1MemoryManager = class {
|
|
|
3256
3236
|
developmentStyle: {
|
|
3257
3237
|
approach: "iterative",
|
|
3258
3238
|
preferredLanguages: [
|
|
3259
|
-
{ language: "typescript", proficiency: "intermediate",
|
|
3260
|
-
{ language: "javascript", proficiency: "intermediate",
|
|
3239
|
+
{ language: "typescript", proficiency: "intermediate", _frequency: 0.8, preference: 4 },
|
|
3240
|
+
{ language: "javascript", proficiency: "intermediate", _frequency: 0.6, preference: 3 }
|
|
3261
3241
|
],
|
|
3262
3242
|
architecturalPatterns: [
|
|
3263
3243
|
{ name: "MVC", familiarity: 0.7, preference: 3, usageFrequency: 0.5 }
|
|
@@ -3353,7 +3333,7 @@ var System2MemoryManager = class {
|
|
|
3353
3333
|
}
|
|
3354
3334
|
get improvementSuggestions() {
|
|
3355
3335
|
return Array.from(this.enhancements.values()).filter(
|
|
3356
|
-
(
|
|
3336
|
+
(_enhancement) => enhancement.status === "proposed" || enhancement.status === "approved"
|
|
3357
3337
|
).sort((a2, b) => b.priority - a2.priority);
|
|
3358
3338
|
}
|
|
3359
3339
|
get reflectionData() {
|
|
@@ -3363,7 +3343,7 @@ var System2MemoryManager = class {
|
|
|
3363
3343
|
}
|
|
3364
3344
|
// Reasoning Trace Management
|
|
3365
3345
|
async startReasoningTrace(_context, initialStep) {
|
|
3366
|
-
const
|
|
3346
|
+
const _trace = {
|
|
3367
3347
|
id: this.generateTraceId(),
|
|
3368
3348
|
timestamp: /* @__PURE__ */ new Date(),
|
|
3369
3349
|
context,
|
|
@@ -3372,7 +3352,7 @@ var System2MemoryManager = class {
|
|
|
3372
3352
|
confidence: 0,
|
|
3373
3353
|
alternatives: [],
|
|
3374
3354
|
metadata: {
|
|
3375
|
-
|
|
3355
|
+
_complexity: this.assessComplexity(context),
|
|
3376
3356
|
domain: this.identifyDomain(context),
|
|
3377
3357
|
techniques: [],
|
|
3378
3358
|
qualityScore: 0,
|
|
@@ -3380,25 +3360,26 @@ var System2MemoryManager = class {
|
|
|
3380
3360
|
}
|
|
3381
3361
|
};
|
|
3382
3362
|
if (initialStep) {
|
|
3383
|
-
await this.addReasoningStep(
|
|
3363
|
+
await this.addReasoningStep(trace.id, {
|
|
3384
3364
|
type: "analysis",
|
|
3385
|
-
description: "Initial
|
|
3365
|
+
description: "Initial _problem analysis",
|
|
3386
3366
|
input: context.problem,
|
|
3387
3367
|
output: initialStep
|
|
3388
3368
|
});
|
|
3389
3369
|
}
|
|
3390
|
-
this.reasoningTraces.set(
|
|
3370
|
+
this.reasoningTraces.set(trace.id, _trace);
|
|
3391
3371
|
await this.manageTraceLimit();
|
|
3392
|
-
return
|
|
3372
|
+
return _trace;
|
|
3393
3373
|
}
|
|
3394
3374
|
async addReasoningStep(traceId, stepData) {
|
|
3395
|
-
this.reasoningTraces.get(traceId);
|
|
3396
|
-
if (!
|
|
3397
|
-
throw new Error(`Reasoning
|
|
3375
|
+
const _trace = this.reasoningTraces.get(traceId);
|
|
3376
|
+
if (!_trace) {
|
|
3377
|
+
throw new Error(`Reasoning _trace ${traceId} not _found`);
|
|
3398
3378
|
}
|
|
3379
|
+
const _startTime = Date.now();
|
|
3399
3380
|
const step = {
|
|
3400
3381
|
id: this.generateStepId(traceId),
|
|
3401
|
-
confidence: this.calculateStepConfidence(stepData,
|
|
3382
|
+
confidence: this.calculateStepConfidence(stepData, _trace),
|
|
3402
3383
|
duration: 0,
|
|
3403
3384
|
// Will be updated when step completes
|
|
3404
3385
|
dependencies: this.identifyDependencies(stepData, trace.steps),
|
|
@@ -3406,27 +3387,27 @@ var System2MemoryManager = class {
|
|
|
3406
3387
|
};
|
|
3407
3388
|
trace.steps.push(step);
|
|
3408
3389
|
trace.metadata.techniques.push(stepData.type);
|
|
3409
|
-
step.duration = Date.now() -
|
|
3410
|
-
await this.updateTraceQuality(
|
|
3390
|
+
step.duration = Date.now() - _startTime;
|
|
3391
|
+
await this.updateTraceQuality(_trace);
|
|
3411
3392
|
return step;
|
|
3412
3393
|
}
|
|
3413
3394
|
async completeReasoningTrace(traceId, conclusion, confidence2) {
|
|
3414
|
-
this.reasoningTraces.get(traceId);
|
|
3415
|
-
if (!
|
|
3416
|
-
throw new Error(`Reasoning
|
|
3395
|
+
const _trace = this.reasoningTraces.get(traceId);
|
|
3396
|
+
if (!_trace) {
|
|
3397
|
+
throw new Error(`Reasoning _trace ${traceId} not _found`);
|
|
3417
3398
|
}
|
|
3418
3399
|
trace.conclusion = conclusion;
|
|
3419
3400
|
trace.confidence = confidence2;
|
|
3420
|
-
trace.metadata.qualityScore = await this.calculateReasoningQuality(
|
|
3401
|
+
trace.metadata.qualityScore = await this.calculateReasoningQuality(_trace);
|
|
3421
3402
|
trace.metadata.reviewRequired = trace.metadata.qualityScore < this.config.qualityThreshold;
|
|
3422
|
-
await this.generateImprovementSuggestions(
|
|
3423
|
-
await this.updateGlobalQualityMetrics(
|
|
3424
|
-
return
|
|
3403
|
+
await this.generateImprovementSuggestions(_trace);
|
|
3404
|
+
await this.updateGlobalQualityMetrics(_trace);
|
|
3405
|
+
return _trace;
|
|
3425
3406
|
}
|
|
3426
3407
|
async addAlternativeReasoning(traceId, alternative) {
|
|
3427
|
-
this.reasoningTraces.get(traceId);
|
|
3428
|
-
if (!
|
|
3429
|
-
throw new Error(`Reasoning
|
|
3408
|
+
const _trace = this.reasoningTraces.get(traceId);
|
|
3409
|
+
if (!_trace) {
|
|
3410
|
+
throw new Error(`Reasoning _trace ${traceId} not _found`);
|
|
3430
3411
|
}
|
|
3431
3412
|
const altReasoning = {
|
|
3432
3413
|
id: this.generateAlternativeId(traceId),
|
|
@@ -3439,33 +3420,33 @@ var System2MemoryManager = class {
|
|
|
3439
3420
|
return this.reasoningTraces.get(traceId) || null;
|
|
3440
3421
|
}
|
|
3441
3422
|
async searchReasoningTraces(query, limit = 10) {
|
|
3442
|
-
`search:reasoning:${JSON.stringify(query)}:${limit}`;
|
|
3443
|
-
this.analysisCache.get(
|
|
3444
|
-
if (
|
|
3445
|
-
return
|
|
3423
|
+
const _cacheKey = `search:reasoning:${JSON.stringify(query)}:${limit}`;
|
|
3424
|
+
const _cached = this.analysisCache.get(_cacheKey);
|
|
3425
|
+
if (_cached) {
|
|
3426
|
+
return _cached;
|
|
3446
3427
|
}
|
|
3447
|
-
let
|
|
3428
|
+
let _traces = Array.from(this.reasoningTraces.values());
|
|
3448
3429
|
if (query.domain) {
|
|
3449
|
-
|
|
3430
|
+
_traces = traces.filter((_trace) => trace.metadata.domain === query.domain);
|
|
3450
3431
|
}
|
|
3451
3432
|
if (query.complexity) {
|
|
3452
|
-
|
|
3433
|
+
_traces = traces.filter((_trace) => trace.metadata.complexity === query.complexity);
|
|
3453
3434
|
}
|
|
3454
3435
|
if (query.minQuality !== void 0) {
|
|
3455
|
-
|
|
3436
|
+
_traces = traces.filter((_trace) => trace.metadata.qualityScore >= (query.minQuality ?? 0));
|
|
3456
3437
|
}
|
|
3457
3438
|
if (query.timeframe) {
|
|
3458
|
-
|
|
3459
|
-
(
|
|
3439
|
+
_traces = traces.filter(
|
|
3440
|
+
(_trace) => trace.timestamp >= query.timeframe.start && trace.timestamp <= query.timeframe.end
|
|
3460
3441
|
);
|
|
3461
3442
|
}
|
|
3462
|
-
|
|
3463
|
-
this.analysisCache.set(
|
|
3464
|
-
return
|
|
3443
|
+
const _results = _traces.sort((a2, b) => b.metadata.qualityScore - a2.metadata.qualityScore).slice(0, limit);
|
|
3444
|
+
this.analysisCache.set(_cacheKey, _results);
|
|
3445
|
+
return _results;
|
|
3465
3446
|
}
|
|
3466
3447
|
// Decision Tree Management
|
|
3467
3448
|
async createDecisionTree(_domain, initialCondition) {
|
|
3468
|
-
const
|
|
3449
|
+
const _tree = {
|
|
3469
3450
|
id: this.generateDecisionTreeId(domain),
|
|
3470
3451
|
rootNode: {
|
|
3471
3452
|
id: "root",
|
|
@@ -3478,26 +3459,26 @@ var System2MemoryManager = class {
|
|
|
3478
3459
|
},
|
|
3479
3460
|
metadata: {
|
|
3480
3461
|
domain,
|
|
3481
|
-
|
|
3462
|
+
_complexity: 1,
|
|
3482
3463
|
accuracy: 0.8,
|
|
3483
3464
|
lastUpdated: /* @__PURE__ */ new Date(),
|
|
3484
3465
|
usageCount: 0
|
|
3485
3466
|
}
|
|
3486
3467
|
};
|
|
3487
|
-
this.decisionTrees.set(
|
|
3488
|
-
return
|
|
3468
|
+
this.decisionTrees.set(tree.id, _tree);
|
|
3469
|
+
return _tree;
|
|
3489
3470
|
}
|
|
3490
|
-
async addDecisionNode(treeId2, parentNodeId,
|
|
3491
|
-
this.decisionTrees.get(treeId2);
|
|
3492
|
-
if (!
|
|
3493
|
-
throw new Error(`Decision
|
|
3471
|
+
async addDecisionNode(treeId2, parentNodeId, _node) {
|
|
3472
|
+
const _tree = this.decisionTrees.get(treeId2);
|
|
3473
|
+
if (!_tree) {
|
|
3474
|
+
throw new Error(`Decision _tree ${treeId2} not _found`);
|
|
3494
3475
|
}
|
|
3495
3476
|
const newNode = {
|
|
3496
3477
|
id: this.generateNodeId(treeId2),
|
|
3497
|
-
...
|
|
3478
|
+
...node
|
|
3498
3479
|
};
|
|
3499
|
-
this.findDecisionNode(tree.rootNode, parentNodeId);
|
|
3500
|
-
if (
|
|
3480
|
+
const _parentNode = this.findDecisionNode(tree.rootNode, parentNodeId);
|
|
3481
|
+
if (_parentNode) {
|
|
3501
3482
|
parentNode.children.push(newNode);
|
|
3502
3483
|
tree.metadata.complexity = this.calculateTreeComplexity(tree.rootNode);
|
|
3503
3484
|
tree.metadata.lastUpdated = /* @__PURE__ */ new Date();
|
|
@@ -3505,20 +3486,20 @@ var System2MemoryManager = class {
|
|
|
3505
3486
|
return newNode;
|
|
3506
3487
|
}
|
|
3507
3488
|
async addEvidence(_treeId, nodeId2, evidence) {
|
|
3508
|
-
this.decisionTrees.get(treeId);
|
|
3509
|
-
if (!
|
|
3510
|
-
throw new Error(`Decision
|
|
3489
|
+
const _tree = this.decisionTrees.get(treeId);
|
|
3490
|
+
if (!_tree) {
|
|
3491
|
+
throw new Error(`Decision _tree ${treeId} not _found`);
|
|
3511
3492
|
}
|
|
3512
|
-
this.findDecisionNode(tree.rootNode, nodeId2);
|
|
3513
|
-
if (
|
|
3493
|
+
const _node = this.findDecisionNode(tree.rootNode, nodeId2);
|
|
3494
|
+
if (_node) {
|
|
3514
3495
|
node.evidence.push(evidence);
|
|
3515
3496
|
node.confidence = this.calculateNodeConfidence(node.evidence);
|
|
3516
3497
|
tree.metadata.lastUpdated = /* @__PURE__ */ new Date();
|
|
3517
3498
|
}
|
|
3518
3499
|
}
|
|
3519
3500
|
async queryDecisionTree(treeId2, context2) {
|
|
3520
|
-
this.decisionTrees.get(treeId2);
|
|
3521
|
-
if (!
|
|
3501
|
+
const _tree = this.decisionTrees.get(treeId2);
|
|
3502
|
+
if (!_tree) {
|
|
3522
3503
|
return [];
|
|
3523
3504
|
}
|
|
3524
3505
|
tree.metadata.usageCount++;
|
|
@@ -3538,8 +3519,8 @@ var System2MemoryManager = class {
|
|
|
3538
3519
|
return newEnhancement;
|
|
3539
3520
|
}
|
|
3540
3521
|
async updateEnhancementStatus(enhancementId, status, feedback) {
|
|
3541
|
-
this.enhancements.get(enhancementId);
|
|
3542
|
-
if (!
|
|
3522
|
+
const _enhancement = this.enhancements.get(enhancementId);
|
|
3523
|
+
if (!_enhancement) {
|
|
3543
3524
|
return false;
|
|
3544
3525
|
}
|
|
3545
3526
|
if (feedback) {
|
|
@@ -3547,16 +3528,16 @@ var System2MemoryManager = class {
|
|
|
3547
3528
|
}
|
|
3548
3529
|
enhancement.status = status;
|
|
3549
3530
|
if (status === "completed") {
|
|
3550
|
-
await this.evaluateEnhancementImpact(
|
|
3531
|
+
await this.evaluateEnhancementImpact(_enhancement);
|
|
3551
3532
|
}
|
|
3552
3533
|
return true;
|
|
3553
3534
|
}
|
|
3554
3535
|
async getEnhancementsByType(type2) {
|
|
3555
|
-
return Array.from(this.enhancements.values()).filter((
|
|
3536
|
+
return Array.from(this.enhancements.values()).filter((_enhancement) => enhancement.type === type2).sort((a2, b) => b.priority - a2.priority);
|
|
3556
3537
|
}
|
|
3557
3538
|
// Reflection Management
|
|
3558
3539
|
async addReflectionEntry(trigger, observation, analysis, insight2, confidence2 = 0.8) {
|
|
3559
|
-
const
|
|
3540
|
+
const _reflection = {
|
|
3560
3541
|
id: this.generateReflectionId(),
|
|
3561
3542
|
timestamp: /* @__PURE__ */ new Date(),
|
|
3562
3543
|
trigger,
|
|
@@ -3566,14 +3547,14 @@ var System2MemoryManager = class {
|
|
|
3566
3547
|
actionItems: [],
|
|
3567
3548
|
confidence: confidence2
|
|
3568
3549
|
};
|
|
3569
|
-
this.reflectionEntries.set(
|
|
3570
|
-
await this.generateActionItems(
|
|
3571
|
-
return
|
|
3550
|
+
this.reflectionEntries.set(reflection.id, _reflection);
|
|
3551
|
+
await this.generateActionItems(_reflection);
|
|
3552
|
+
return _reflection;
|
|
3572
3553
|
}
|
|
3573
3554
|
async addActionItem(reflectionId, actionItem) {
|
|
3574
|
-
this.reflectionEntries.get(reflectionId);
|
|
3575
|
-
if (!
|
|
3576
|
-
throw new Error(`Reflection entry ${reflectionId} not
|
|
3555
|
+
const _reflection = this.reflectionEntries.get(reflectionId);
|
|
3556
|
+
if (!_reflection) {
|
|
3557
|
+
throw new Error(`Reflection entry ${reflectionId} not _found`);
|
|
3577
3558
|
}
|
|
3578
3559
|
const action = {
|
|
3579
3560
|
id: this.generateActionItemId(reflectionId),
|
|
@@ -3610,14 +3591,14 @@ var System2MemoryManager = class {
|
|
|
3610
3591
|
}
|
|
3611
3592
|
}
|
|
3612
3593
|
// Quality Assessment
|
|
3613
|
-
async assessCodeQuality(code2,
|
|
3594
|
+
async assessCodeQuality(code2, language, context2) {
|
|
3614
3595
|
if (context2) {
|
|
3615
|
-
console.log("Code
|
|
3596
|
+
console.log("Code _quality context:", Object.keys(context2));
|
|
3616
3597
|
}
|
|
3617
|
-
`
|
|
3618
|
-
this.analysisCache.get(
|
|
3619
|
-
if (
|
|
3620
|
-
return
|
|
3598
|
+
const _cacheKey = `_quality:${this.hashCode(code2)}:${language}`;
|
|
3599
|
+
const _cached = this.analysisCache.get(_cacheKey);
|
|
3600
|
+
if (_cached) {
|
|
3601
|
+
return _cached;
|
|
3621
3602
|
}
|
|
3622
3603
|
const metrics2 = {
|
|
3623
3604
|
maintainability: await this.calculateMaintainability(code2, _language),
|
|
@@ -3626,9 +3607,9 @@ var System2MemoryManager = class {
|
|
|
3626
3607
|
performance: await this.calculatePerformance(code2, _language),
|
|
3627
3608
|
security: await this.calculateSecurity(code2, _language),
|
|
3628
3609
|
bugDensity: await this.calculateBugDensity(code2, _language),
|
|
3629
|
-
|
|
3610
|
+
_complexity: await this.calculateCyclomaticComplexity(code2, _language)
|
|
3630
3611
|
};
|
|
3631
|
-
this.analysisCache.set(
|
|
3612
|
+
this.analysisCache.set(_cacheKey, metrics2);
|
|
3632
3613
|
return metrics2;
|
|
3633
3614
|
}
|
|
3634
3615
|
async updateQualityMetrics(metrics2) {
|
|
@@ -3636,7 +3617,7 @@ var System2MemoryManager = class {
|
|
|
3636
3617
|
}
|
|
3637
3618
|
// Private Helper Methods
|
|
3638
3619
|
generateTraceId() {
|
|
3639
|
-
return `
|
|
3620
|
+
return `_trace:${Date.now()}:${Math.random().toString(36).substr(2, 9)}`;
|
|
3640
3621
|
}
|
|
3641
3622
|
generateStepId(traceId) {
|
|
3642
3623
|
return `${traceId}:step:${Date.now()}`;
|
|
@@ -3645,16 +3626,16 @@ var System2MemoryManager = class {
|
|
|
3645
3626
|
return `${traceId}:alt:${Date.now()}`;
|
|
3646
3627
|
}
|
|
3647
3628
|
generateDecisionTreeId(domain2) {
|
|
3648
|
-
return `
|
|
3629
|
+
return `_tree:${domain2}:${Date.now()}`;
|
|
3649
3630
|
}
|
|
3650
3631
|
generateNodeId(treeId2) {
|
|
3651
|
-
return `${treeId2}:
|
|
3632
|
+
return `${treeId2}:_node:${Date.now()}`;
|
|
3652
3633
|
}
|
|
3653
3634
|
generateEnhancementId() {
|
|
3654
|
-
return `
|
|
3635
|
+
return `_enhancement:${Date.now()}:${Math.random().toString(36).substr(2, 9)}`;
|
|
3655
3636
|
}
|
|
3656
3637
|
generateReflectionId() {
|
|
3657
|
-
return `
|
|
3638
|
+
return `_reflection:${Date.now()}:${Math.random().toString(36).substr(2, 9)}`;
|
|
3658
3639
|
}
|
|
3659
3640
|
generateActionItemId(reflectionId) {
|
|
3660
3641
|
return `${reflectionId}:action:${Date.now()}`;
|
|
@@ -3666,14 +3647,14 @@ var System2MemoryManager = class {
|
|
|
3666
3647
|
context.assumptions.length > 3,
|
|
3667
3648
|
context.problem.length > 500
|
|
3668
3649
|
];
|
|
3669
|
-
factors.filter(Boolean).length;
|
|
3670
|
-
if (
|
|
3650
|
+
const _complexityScore = factors.filter(Boolean).length;
|
|
3651
|
+
if (_complexityScore === 0) {
|
|
3671
3652
|
return "simple";
|
|
3672
3653
|
}
|
|
3673
|
-
if (
|
|
3654
|
+
if (_complexityScore === 1) {
|
|
3674
3655
|
return "moderate";
|
|
3675
3656
|
}
|
|
3676
|
-
if (
|
|
3657
|
+
if (_complexityScore === 2) {
|
|
3677
3658
|
return "complex";
|
|
3678
3659
|
}
|
|
3679
3660
|
return "very_complex";
|
|
@@ -3694,7 +3675,7 @@ var System2MemoryManager = class {
|
|
|
3694
3675
|
}
|
|
3695
3676
|
return "general";
|
|
3696
3677
|
}
|
|
3697
|
-
calculateStepConfidence(stepData,
|
|
3678
|
+
calculateStepConfidence(stepData, _trace) {
|
|
3698
3679
|
let confidence2 = 0.8;
|
|
3699
3680
|
switch (stepData.type) {
|
|
3700
3681
|
case "analysis":
|
|
@@ -3716,10 +3697,10 @@ var System2MemoryManager = class {
|
|
|
3716
3697
|
if (stepData.output.length > 100) {
|
|
3717
3698
|
confidence2 += 0.1;
|
|
3718
3699
|
}
|
|
3719
|
-
if (
|
|
3700
|
+
if (trace.metadata.complexity === "simple") {
|
|
3720
3701
|
confidence2 += 0.1;
|
|
3721
3702
|
}
|
|
3722
|
-
if (
|
|
3703
|
+
if (trace.metadata.complexity === "very_complex") {
|
|
3723
3704
|
confidence2 -= 0.1;
|
|
3724
3705
|
}
|
|
3725
3706
|
return Math.max(0.1, Math.min(1, confidence2));
|
|
@@ -3733,68 +3714,68 @@ var System2MemoryManager = class {
|
|
|
3733
3714
|
}
|
|
3734
3715
|
return dependencies;
|
|
3735
3716
|
}
|
|
3736
|
-
async updateTraceQuality(
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
let
|
|
3742
|
-
if (
|
|
3743
|
-
|
|
3717
|
+
async updateTraceQuality(_trace) {
|
|
3718
|
+
const _stepCount = trace.steps.length;
|
|
3719
|
+
const _avgConfidence = trace.steps.reduce((sum, step) => sum + step.confidence, 0) / _stepCount;
|
|
3720
|
+
const _hasAnalysis = trace.steps.some((step) => step.type === "analysis");
|
|
3721
|
+
const _hasEvaluation = trace.steps.some((step) => step.type === "evaluation");
|
|
3722
|
+
let _quality = _avgConfidence * 0.6;
|
|
3723
|
+
if (_hasAnalysis) {
|
|
3724
|
+
_quality += 0.2;
|
|
3744
3725
|
}
|
|
3745
|
-
if (
|
|
3746
|
-
|
|
3726
|
+
if (_hasEvaluation) {
|
|
3727
|
+
_quality += 0.2;
|
|
3747
3728
|
}
|
|
3748
|
-
|
|
3729
|
+
trace.metadata.qualityScore = Math.max(0, Math.min(1, _quality));
|
|
3749
3730
|
}
|
|
3750
3731
|
async calculateReasoningQuality(trace2) {
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3732
|
+
const _factors = {
|
|
3733
|
+
_coherence: this.calculateCoherence(trace2),
|
|
3734
|
+
_completeness: this.calculateCompleteness(trace2),
|
|
3754
3735
|
accuracy: this.calculateAccuracy(trace2),
|
|
3755
3736
|
efficiency: this.calculateEfficiency(trace2),
|
|
3756
|
-
|
|
3757
|
-
}
|
|
3758
|
-
return Object.values(
|
|
3737
|
+
_creativity: this.calculateCreativity(trace2)
|
|
3738
|
+
};
|
|
3739
|
+
return Object.values(_factors).reduce((sum, value) => sum + value, 0) / Object.keys(_factors).length;
|
|
3759
3740
|
}
|
|
3760
|
-
calculateCoherence(
|
|
3741
|
+
calculateCoherence(_trace) {
|
|
3761
3742
|
let coherenceSum = 0;
|
|
3762
3743
|
let pairCount = 0;
|
|
3763
|
-
for (let i = 1; i <
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
coherenceSum +=
|
|
3744
|
+
for (let i = 1; i < trace.steps.length; i++) {
|
|
3745
|
+
const _prev = trace.steps[i - 1];
|
|
3746
|
+
const _curr = trace.steps[i];
|
|
3747
|
+
const _coherence = _curr?.input.includes(_prev?.output.slice(0, 30) || "") ? 1 : 0.5;
|
|
3748
|
+
coherenceSum += _coherence;
|
|
3768
3749
|
pairCount++;
|
|
3769
3750
|
}
|
|
3770
3751
|
return pairCount > 0 ? coherenceSum / pairCount : 0.8;
|
|
3771
3752
|
}
|
|
3772
|
-
calculateCompleteness(
|
|
3773
|
-
new Set(
|
|
3774
|
-
requiredStepTypes.filter((type2) => presentTypes.has(type2)).length / requiredStepTypes.length;
|
|
3775
|
-
return
|
|
3776
|
-
}
|
|
3777
|
-
calculateAccuracy(
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
return Math.min(1,
|
|
3781
|
-
}
|
|
3782
|
-
calculateEfficiency(
|
|
3783
|
-
|
|
3784
|
-
Math.max(0.2, 1 - (
|
|
3785
|
-
return
|
|
3786
|
-
}
|
|
3787
|
-
calculateCreativity(
|
|
3788
|
-
new Set(
|
|
3789
|
-
|
|
3790
|
-
Math.min(1,
|
|
3791
|
-
return
|
|
3792
|
-
}
|
|
3793
|
-
async generateImprovementSuggestions(
|
|
3794
|
-
if (
|
|
3753
|
+
calculateCompleteness(_trace) {
|
|
3754
|
+
new Set(trace.steps.map((step) => step.type));
|
|
3755
|
+
const _completeness = requiredStepTypes.filter((type2) => presentTypes.has(type2)).length / requiredStepTypes.length;
|
|
3756
|
+
return _completeness;
|
|
3757
|
+
}
|
|
3758
|
+
calculateAccuracy(_trace) {
|
|
3759
|
+
const _avgConfidence = trace.steps.reduce((sum, step) => sum + step.confidence, 0) / trace.steps.length;
|
|
3760
|
+
const _alternativeBonus = trace.alternatives.length > 0 ? 0.1 : 0;
|
|
3761
|
+
return Math.min(1, _avgConfidence + _alternativeBonus);
|
|
3762
|
+
}
|
|
3763
|
+
calculateEfficiency(_trace) {
|
|
3764
|
+
const _complexity = { simple: 1, moderate: 2, complex: 3, verycomplex: 4 }[trace.metadata.complexity];
|
|
3765
|
+
const _stepEfficiency = Math.max(0.2, 1 - (trace.steps.length - _complexity) * 0.1);
|
|
3766
|
+
return _stepEfficiency;
|
|
3767
|
+
}
|
|
3768
|
+
calculateCreativity(_trace) {
|
|
3769
|
+
const _uniqueTechniques = new Set(trace.metadata.techniques).size;
|
|
3770
|
+
const _alternativeCount = trace.alternatives.length;
|
|
3771
|
+
const _creativity = Math.min(1, _uniqueTechniques * 0.3 + _alternativeCount * 0.2 + 0.5);
|
|
3772
|
+
return _creativity;
|
|
3773
|
+
}
|
|
3774
|
+
async generateImprovementSuggestions(_trace) {
|
|
3775
|
+
if (trace.metadata.qualityScore < 0.7) {
|
|
3795
3776
|
await this.proposeEnhancement({
|
|
3796
|
-
type: "
|
|
3797
|
-
description: `Improve reasoning
|
|
3777
|
+
type: "_quality",
|
|
3778
|
+
description: `Improve reasoning _quality for ${trace.metadata.domain} problems`,
|
|
3798
3779
|
impact: {
|
|
3799
3780
|
benefitScore: 7,
|
|
3800
3781
|
effortScore: 5,
|
|
@@ -3807,7 +3788,7 @@ var System2MemoryManager = class {
|
|
|
3807
3788
|
{
|
|
3808
3789
|
id: "analysis",
|
|
3809
3790
|
name: "Quality Analysis",
|
|
3810
|
-
description: "Analyze low-
|
|
3791
|
+
description: "Analyze low-_quality reasoning patterns",
|
|
3811
3792
|
duration: 3,
|
|
3812
3793
|
deliverables: ["Pattern analysis", "Improvement plan"],
|
|
3813
3794
|
dependencies: []
|
|
@@ -3824,8 +3805,8 @@ var System2MemoryManager = class {
|
|
|
3824
3805
|
dependencies: [],
|
|
3825
3806
|
risks: [
|
|
3826
3807
|
{
|
|
3827
|
-
id: "
|
|
3828
|
-
description: "Reasoning improvement may add
|
|
3808
|
+
id: "_complexity",
|
|
3809
|
+
description: "Reasoning improvement may add _complexity",
|
|
3829
3810
|
probability: 0.3,
|
|
3830
3811
|
impact: 4,
|
|
3831
3812
|
mitigation: "Gradual implementation with testing",
|
|
@@ -3840,11 +3821,11 @@ var System2MemoryManager = class {
|
|
|
3840
3821
|
async updateGlobalQualityMetrics(trace2) {
|
|
3841
3822
|
this.qualityMetrics.reasoningQuality;
|
|
3842
3823
|
this.qualityMetrics.reasoningQuality = {
|
|
3843
|
-
|
|
3844
|
-
|
|
3824
|
+
_coherence: (currentReasoning.coherence + this.calculateCoherence(trace2)) / 2,
|
|
3825
|
+
_completeness: (currentReasoning.completeness + this.calculateCompleteness(trace2)) / 2,
|
|
3845
3826
|
accuracy: (currentReasoning.accuracy + this.calculateAccuracy(trace2)) / 2,
|
|
3846
3827
|
efficiency: (currentReasoning.efficiency + this.calculateEfficiency(trace2)) / 2,
|
|
3847
|
-
|
|
3828
|
+
_creativity: (currentReasoning.creativity + this.calculateCreativity(trace2)) / 2
|
|
3848
3829
|
};
|
|
3849
3830
|
}
|
|
3850
3831
|
createEmptyDecisionTree() {
|
|
@@ -3861,7 +3842,7 @@ var System2MemoryManager = class {
|
|
|
3861
3842
|
},
|
|
3862
3843
|
metadata: {
|
|
3863
3844
|
domain: "unknown",
|
|
3864
|
-
|
|
3845
|
+
_complexity: 0,
|
|
3865
3846
|
accuracy: 0,
|
|
3866
3847
|
lastUpdated: /* @__PURE__ */ new Date(),
|
|
3867
3848
|
usageCount: 0
|
|
@@ -3873,9 +3854,9 @@ var System2MemoryManager = class {
|
|
|
3873
3854
|
return root;
|
|
3874
3855
|
}
|
|
3875
3856
|
for (const child of root.children) {
|
|
3876
|
-
this.findDecisionNode(child, nodeId2);
|
|
3877
|
-
if (
|
|
3878
|
-
return
|
|
3857
|
+
const _found = this.findDecisionNode(child, nodeId2);
|
|
3858
|
+
if (_found) {
|
|
3859
|
+
return _found;
|
|
3879
3860
|
}
|
|
3880
3861
|
}
|
|
3881
3862
|
return null;
|
|
@@ -3883,15 +3864,22 @@ var System2MemoryManager = class {
|
|
|
3883
3864
|
calculateTreeComplexity(root2) {
|
|
3884
3865
|
let maxDepth = 0;
|
|
3885
3866
|
let nodeCount = 0;
|
|
3886
|
-
|
|
3867
|
+
const _traverse = (_node, depth) => {
|
|
3868
|
+
nodeCount++;
|
|
3869
|
+
maxDepth = Math.max(maxDepth, depth);
|
|
3870
|
+
for (const child of node.children) {
|
|
3871
|
+
_traverse(child, depth + 1);
|
|
3872
|
+
}
|
|
3873
|
+
};
|
|
3874
|
+
_traverse(root2, 1);
|
|
3887
3875
|
return maxDepth + Math.log(nodeCount);
|
|
3888
3876
|
}
|
|
3889
3877
|
calculateNodeConfidence(evidence) {
|
|
3890
3878
|
if (evidence.length === 0) {
|
|
3891
3879
|
return 0.5;
|
|
3892
3880
|
}
|
|
3893
|
-
evidence.reduce((sum, e) => sum + e.strength, 0);
|
|
3894
|
-
return Math.min(1,
|
|
3881
|
+
const _weightedSum = evidence.reduce((sum, e) => sum + e.strength, 0);
|
|
3882
|
+
return Math.min(1, _weightedSum / evidence.length);
|
|
3895
3883
|
}
|
|
3896
3884
|
traverseDecisionTree(node2, context2) {
|
|
3897
3885
|
const path2 = [node2];
|
|
@@ -3903,28 +3891,28 @@ var System2MemoryManager = class {
|
|
|
3903
3891
|
}
|
|
3904
3892
|
return path2;
|
|
3905
3893
|
}
|
|
3906
|
-
evaluateCondition(_node,
|
|
3894
|
+
evaluateCondition(_node, _context) {
|
|
3907
3895
|
return node.confidence > 0.5;
|
|
3908
3896
|
}
|
|
3909
|
-
shouldAutoApprove(
|
|
3910
|
-
return
|
|
3897
|
+
shouldAutoApprove(_enhancement) {
|
|
3898
|
+
return enhancement.impact.riskScore <= 3 && enhancement.impact.benefitScore >= 7 && enhancement.priority >= 7;
|
|
3911
3899
|
}
|
|
3912
|
-
async evaluateEnhancementImpact(
|
|
3913
|
-
console.log(`Evaluating impact of
|
|
3900
|
+
async evaluateEnhancementImpact(_enhancement) {
|
|
3901
|
+
console.log(`Evaluating impact of _enhancement: ${enhancement.description}`);
|
|
3914
3902
|
}
|
|
3915
|
-
async generateActionItems(
|
|
3916
|
-
|
|
3903
|
+
async generateActionItems(_reflection) {
|
|
3904
|
+
reflection.insight.toLowerCase();
|
|
3917
3905
|
if (insight.includes("improve") || insight.includes("optimize")) {
|
|
3918
|
-
await this.addActionItem(
|
|
3919
|
-
description: `Implement improvement based on: ${
|
|
3906
|
+
await this.addActionItem(reflection.id, {
|
|
3907
|
+
description: `Implement improvement based on: ${reflection.insight}`,
|
|
3920
3908
|
priority: 7,
|
|
3921
3909
|
dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1e3)
|
|
3922
3910
|
// 1 week
|
|
3923
3911
|
});
|
|
3924
3912
|
}
|
|
3925
3913
|
if (insight.includes("learn") || insight.includes("study")) {
|
|
3926
|
-
await this.addActionItem(
|
|
3927
|
-
description: `Research and learn: ${
|
|
3914
|
+
await this.addActionItem(reflection.id, {
|
|
3915
|
+
description: `Research and learn: ${reflection.insight}`,
|
|
3928
3916
|
priority: 5,
|
|
3929
3917
|
dueDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1e3)
|
|
3930
3918
|
// 2 weeks
|
|
@@ -3962,14 +3950,14 @@ var System2MemoryManager = class {
|
|
|
3962
3950
|
event.data;
|
|
3963
3951
|
if (data.improvement) {
|
|
3964
3952
|
await this.proposeEnhancement({
|
|
3965
|
-
type: "
|
|
3953
|
+
type: "_quality",
|
|
3966
3954
|
description: `Quality improvement: ${data.improvement}`,
|
|
3967
3955
|
impact: {
|
|
3968
3956
|
benefitScore: data.impact || 5,
|
|
3969
3957
|
effortScore: 3,
|
|
3970
3958
|
riskScore: 2,
|
|
3971
3959
|
affectedUsers: 1,
|
|
3972
|
-
affectedComponents: ["code-
|
|
3960
|
+
affectedComponents: ["code-_quality"]
|
|
3973
3961
|
},
|
|
3974
3962
|
implementation: {
|
|
3975
3963
|
phases: [],
|
|
@@ -3988,104 +3976,136 @@ var System2MemoryManager = class {
|
|
|
3988
3976
|
async manageTraceLimit() {
|
|
3989
3977
|
if (this.reasoningTraces.size > this.config.maxReasoningTraces) {
|
|
3990
3978
|
Array.from(this.reasoningTraces.entries());
|
|
3991
|
-
traces.sort(
|
|
3979
|
+
const _sortedByQuality = traces.sort(
|
|
3992
3980
|
(a2, b) => a2[1].metadata.qualityScore - b[1].metadata.qualityScore
|
|
3993
3981
|
);
|
|
3994
|
-
Math.min(
|
|
3982
|
+
const _removeCount = Math.min(
|
|
3995
3983
|
Math.floor(this.config.maxReasoningTraces * 0.2),
|
|
3996
3984
|
sortedByQuality.length
|
|
3997
3985
|
);
|
|
3998
|
-
for (let i = 0; i <
|
|
3999
|
-
|
|
4000
|
-
if (
|
|
4001
|
-
this.reasoningTraces.delete(
|
|
3986
|
+
for (let i = 0; i < _removeCount; i++) {
|
|
3987
|
+
const _traceEntry = _sortedByQuality[i];
|
|
3988
|
+
if (_traceEntry) {
|
|
3989
|
+
this.reasoningTraces.delete(_traceEntry[0]);
|
|
4002
3990
|
}
|
|
4003
3991
|
}
|
|
4004
3992
|
}
|
|
4005
3993
|
}
|
|
4006
3994
|
// Quality calculation methods
|
|
4007
|
-
async calculateMaintainability(_code,
|
|
4008
|
-
|
|
3995
|
+
async calculateMaintainability(_code, _language2) {
|
|
3996
|
+
const _factors = {
|
|
4009
3997
|
length: Math.max(0, 100 - code.length / 100),
|
|
4010
3998
|
// Shorter is better
|
|
4011
3999
|
comments: (code.match(/\/\/|\/\*|\#/g) || []).length / code.split("\n").length * 100,
|
|
4012
|
-
|
|
4013
|
-
}
|
|
4000
|
+
_complexity: 100 - this.calculateBasicComplexity(code) * 10
|
|
4001
|
+
};
|
|
4014
4002
|
return Math.max(
|
|
4015
4003
|
0,
|
|
4016
|
-
Math.min(100, Object.values(
|
|
4004
|
+
Math.min(100, Object.values(_factors).reduce((sum, val) => sum + val, 0) / 3)
|
|
4017
4005
|
);
|
|
4018
4006
|
}
|
|
4019
|
-
async calculateReadability(_code,
|
|
4007
|
+
async calculateReadability(_code, _language2) {
|
|
4020
4008
|
code.split("\n");
|
|
4021
|
-
lines.length > 0 ? lines.reduce((sum, line) => sum + line.length, 0) / lines.length : 0;
|
|
4022
|
-
Math.max(0, 100 - (
|
|
4023
|
-
return Math.max(0, Math.min(100,
|
|
4024
|
-
}
|
|
4025
|
-
async calculateTestability(_code,
|
|
4026
|
-
/function|def|public|private/.test(code);
|
|
4027
|
-
/class|interface/.test(code);
|
|
4028
|
-
!/global|window|document/.test(code);
|
|
4009
|
+
const _avgLineLength = lines.length > 0 ? lines.reduce((sum, line) => sum + line.length, 0) / lines.length : 0;
|
|
4010
|
+
const _readabilityScore = Math.max(0, 100 - (_avgLineLength - 50) * 2);
|
|
4011
|
+
return Math.max(0, Math.min(100, _readabilityScore));
|
|
4012
|
+
}
|
|
4013
|
+
async calculateTestability(_code, _language2) {
|
|
4014
|
+
const _hasFunctions = /function|def|public|private/.test(code);
|
|
4015
|
+
const _hasClasses = /class|interface/.test(code);
|
|
4016
|
+
const _lowCoupling = !/global|window|document/.test(code);
|
|
4029
4017
|
let score = 50;
|
|
4030
|
-
if (
|
|
4018
|
+
if (_hasFunctions) {
|
|
4031
4019
|
score += 20;
|
|
4032
4020
|
}
|
|
4033
|
-
if (
|
|
4021
|
+
if (_hasClasses) {
|
|
4034
4022
|
score += 15;
|
|
4035
4023
|
}
|
|
4036
|
-
if (
|
|
4024
|
+
if (_lowCoupling) {
|
|
4037
4025
|
score += 15;
|
|
4038
4026
|
}
|
|
4039
4027
|
return Math.max(0, Math.min(100, score));
|
|
4040
4028
|
}
|
|
4041
|
-
async calculatePerformance(_code,
|
|
4042
|
-
(code.match(/for|while/g) || []).length > 2;
|
|
4043
|
-
/return.*\w+\(/.test(code);
|
|
4044
|
-
(code.match(/return/g) || []).length > 1;
|
|
4029
|
+
async calculatePerformance(_code, _language2) {
|
|
4030
|
+
const _hasNestedLoops = (code.match(/for|while/g) || []).length > 2;
|
|
4031
|
+
const _hasRecursion = /return.*\w+\(/.test(code);
|
|
4032
|
+
const _hasEarlyReturns = (code.match(/return/g) || []).length > 1;
|
|
4045
4033
|
let score = 80;
|
|
4046
|
-
if (
|
|
4034
|
+
if (_hasNestedLoops) {
|
|
4047
4035
|
score -= 20;
|
|
4048
4036
|
}
|
|
4049
|
-
if (
|
|
4037
|
+
if (_hasRecursion && !_hasEarlyReturns) {
|
|
4050
4038
|
score -= 15;
|
|
4051
4039
|
}
|
|
4052
|
-
if (
|
|
4040
|
+
if (_hasEarlyReturns) {
|
|
4053
4041
|
score += 10;
|
|
4054
4042
|
}
|
|
4055
4043
|
return Math.max(0, Math.min(100, score));
|
|
4056
4044
|
}
|
|
4057
|
-
async calculateSecurity(_code,
|
|
4045
|
+
async calculateSecurity(_code, _language2) {
|
|
4046
|
+
const _vulnerabilities = [
|
|
4047
|
+
/eval\(/g,
|
|
4048
|
+
/innerHTML\s*=/g,
|
|
4049
|
+
/document\.write/g,
|
|
4050
|
+
/\$\{.*\}/g,
|
|
4051
|
+
// Template injection potential
|
|
4052
|
+
/sql|query.*\+/gi
|
|
4053
|
+
// SQL injection potential
|
|
4054
|
+
];
|
|
4058
4055
|
let score = 90;
|
|
4059
|
-
for (const pattern2 of
|
|
4056
|
+
for (const pattern2 of _vulnerabilities) {
|
|
4060
4057
|
if (pattern2.test(code)) {
|
|
4061
4058
|
score -= 15;
|
|
4062
4059
|
}
|
|
4063
4060
|
}
|
|
4064
4061
|
return Math.max(0, Math.min(100, score));
|
|
4065
4062
|
}
|
|
4066
|
-
async calculateBugDensity(_code,
|
|
4067
|
-
|
|
4063
|
+
async calculateBugDensity(_code, _language2) {
|
|
4064
|
+
const _bugPatterns = [
|
|
4065
|
+
/==\s*null/g,
|
|
4066
|
+
// Null comparison
|
|
4067
|
+
/undefined/g,
|
|
4068
|
+
/NaN/g,
|
|
4069
|
+
/catch\s*\(\s*\)/g,
|
|
4070
|
+
// Empty catch blocks
|
|
4071
|
+
/if\s*\([^)]*=[^=]/g
|
|
4072
|
+
// Assignment in condition
|
|
4073
|
+
];
|
|
4074
|
+
const _lines = code.split("\n").length;
|
|
4068
4075
|
let bugCount = 0;
|
|
4069
|
-
for (const pattern2 of
|
|
4076
|
+
for (const pattern2 of _bugPatterns) {
|
|
4070
4077
|
bugCount += (code.match(pattern2) || []).length;
|
|
4071
4078
|
}
|
|
4072
|
-
return bugCount /
|
|
4079
|
+
return bugCount / _lines * 1e3;
|
|
4073
4080
|
}
|
|
4074
|
-
async calculateCyclomaticComplexity(_code,
|
|
4081
|
+
async calculateCyclomaticComplexity(_code, _language2) {
|
|
4075
4082
|
return this.calculateBasicComplexity(code);
|
|
4076
4083
|
}
|
|
4077
4084
|
calculateBasicComplexity(code2) {
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4085
|
+
const _complexityPatterns = [
|
|
4086
|
+
/if\s*\(/g,
|
|
4087
|
+
/else\s*if/g,
|
|
4088
|
+
/while\s*\(/g,
|
|
4089
|
+
/for\s*\(/g,
|
|
4090
|
+
/switch\s*\(/g,
|
|
4091
|
+
/case\s+/g,
|
|
4092
|
+
/catch\s*\(/g,
|
|
4093
|
+
/\?\s*.*:/g,
|
|
4094
|
+
// Ternary operators
|
|
4095
|
+
/&&|\|\|/g
|
|
4096
|
+
// Logical operators
|
|
4097
|
+
];
|
|
4098
|
+
let _complexity = 1;
|
|
4099
|
+
for (const pattern2 of _complexityPatterns) {
|
|
4100
|
+
_complexity += (code2.match(pattern2) || []).length;
|
|
4081
4101
|
}
|
|
4082
|
-
return
|
|
4102
|
+
return _complexity;
|
|
4083
4103
|
}
|
|
4084
4104
|
hashCode(str) {
|
|
4085
4105
|
let hash = 0;
|
|
4086
4106
|
for (let i = 0; i < str.length; i++) {
|
|
4087
|
-
str.charCodeAt(i);
|
|
4088
|
-
hash = (hash << 5) - hash +
|
|
4107
|
+
const _char = str.charCodeAt(i);
|
|
4108
|
+
hash = (hash << 5) - hash + _char;
|
|
4089
4109
|
hash = hash & hash;
|
|
4090
4110
|
}
|
|
4091
4111
|
return hash.toString(36);
|
|
@@ -4099,14 +4119,14 @@ var System2MemoryManager = class {
|
|
|
4099
4119
|
performance: 85,
|
|
4100
4120
|
security: 90,
|
|
4101
4121
|
bugDensity: 2.5,
|
|
4102
|
-
|
|
4122
|
+
_complexity: 5
|
|
4103
4123
|
},
|
|
4104
4124
|
reasoningQuality: {
|
|
4105
|
-
|
|
4106
|
-
|
|
4125
|
+
_coherence: 0.8,
|
|
4126
|
+
_completeness: 0.75,
|
|
4107
4127
|
accuracy: 0.85,
|
|
4108
4128
|
efficiency: 0.7,
|
|
4109
|
-
|
|
4129
|
+
_creativity: 0.6
|
|
4110
4130
|
},
|
|
4111
4131
|
userSatisfaction: {
|
|
4112
4132
|
userRating: 4.2,
|
|
@@ -4152,13 +4172,13 @@ var DualMemoryEngine = class {
|
|
|
4152
4172
|
// ========== Core Memory Operations ==========
|
|
4153
4173
|
async query(memoryQuery) {
|
|
4154
4174
|
const _startTime = Date.now();
|
|
4155
|
-
const
|
|
4156
|
-
const
|
|
4157
|
-
if (
|
|
4158
|
-
|
|
4175
|
+
const cacheKey = this.generateCacheKey(memoryQuery);
|
|
4176
|
+
const cached = this.performanceCache.get(cacheKey);
|
|
4177
|
+
if (cached && this.isCacheValid(cached)) {
|
|
4178
|
+
cached.hits++;
|
|
4159
4179
|
this.operationMetrics.totalOperations++;
|
|
4160
4180
|
return {
|
|
4161
|
-
|
|
4181
|
+
_data: cached.result,
|
|
4162
4182
|
source: "both",
|
|
4163
4183
|
confidence: 0.9,
|
|
4164
4184
|
latency: Date.now() - _startTime,
|
|
@@ -4167,20 +4187,20 @@ var DualMemoryEngine = class {
|
|
|
4167
4187
|
}
|
|
4168
4188
|
try {
|
|
4169
4189
|
const _strategy = await this.selectMemoryStrategy(memoryQuery);
|
|
4170
|
-
const _result = await this.executeMemoryOperation(memoryQuery,
|
|
4190
|
+
const _result = await this.executeMemoryOperation(memoryQuery, _strategy);
|
|
4171
4191
|
if (result.confidence > 0.7) {
|
|
4172
|
-
this.performanceCache.set(
|
|
4173
|
-
|
|
4192
|
+
this.performanceCache.set(cacheKey, {
|
|
4193
|
+
_result: result._data,
|
|
4174
4194
|
timestamp: /* @__PURE__ */ new Date(),
|
|
4175
4195
|
hits: 1
|
|
4176
4196
|
});
|
|
4177
4197
|
}
|
|
4178
|
-
this.updateOperationMetrics(
|
|
4179
|
-
return
|
|
4180
|
-
} catch (
|
|
4181
|
-
this.updateOperationMetrics("both", Date.now() -
|
|
4198
|
+
this.updateOperationMetrics(_strategy, Date.now() - _startTime, true);
|
|
4199
|
+
return _result;
|
|
4200
|
+
} catch (_error) {
|
|
4201
|
+
this.updateOperationMetrics("both", Date.now() - _startTime, false);
|
|
4182
4202
|
throw new Error(
|
|
4183
|
-
`Memory query failed: ${
|
|
4203
|
+
`Memory query failed: ${_error instanceof Error ? error.message : "Unknown _error"}`
|
|
4184
4204
|
);
|
|
4185
4205
|
}
|
|
4186
4206
|
}
|
|
@@ -4197,7 +4217,7 @@ var DualMemoryEngine = class {
|
|
|
4197
4217
|
timestamp: /* @__PURE__ */ new Date(),
|
|
4198
4218
|
userId: context2["userId"] || "anonymous",
|
|
4199
4219
|
sessionId: context2["sessionId"] || "default",
|
|
4200
|
-
|
|
4220
|
+
_data: { input: input2, output, context: context2, success },
|
|
4201
4221
|
metadata: {
|
|
4202
4222
|
confidence: success ? 0.9 : 0.3,
|
|
4203
4223
|
source: "user_input",
|
|
@@ -4217,27 +4237,27 @@ var DualMemoryEngine = class {
|
|
|
4217
4237
|
urgency: "medium"
|
|
4218
4238
|
});
|
|
4219
4239
|
}
|
|
4220
|
-
async findPatterns(
|
|
4240
|
+
async findPatterns(language, framework, useCase, limit = 10) {
|
|
4221
4241
|
return this.query({
|
|
4222
4242
|
type: "pattern",
|
|
4223
|
-
query: `${
|
|
4224
|
-
context: { language
|
|
4243
|
+
query: `${language || ""} ${framework || ""} ${useCase || ""}`.trim(),
|
|
4244
|
+
context: { language, framework, useCase },
|
|
4225
4245
|
limit,
|
|
4226
4246
|
urgency: "low"
|
|
4227
4247
|
});
|
|
4228
4248
|
}
|
|
4229
|
-
async getReasoning(domain2,
|
|
4249
|
+
async getReasoning(domain2, complexity, minQuality) {
|
|
4230
4250
|
return this.query({
|
|
4231
4251
|
type: "reasoning",
|
|
4232
|
-
query: `${domain2 || ""} ${
|
|
4233
|
-
context: { domain: domain2, complexity
|
|
4252
|
+
query: `${domain2 || ""} ${complexity || ""}`.trim(),
|
|
4253
|
+
context: { domain: domain2, complexity, minQuality },
|
|
4234
4254
|
urgency: "low"
|
|
4235
4255
|
});
|
|
4236
4256
|
}
|
|
4237
4257
|
async getQualityInsights() {
|
|
4238
4258
|
return this.query({
|
|
4239
4259
|
type: "quality",
|
|
4240
|
-
query: "current quality
|
|
4260
|
+
query: "current quality _metrics",
|
|
4241
4261
|
urgency: "low"
|
|
4242
4262
|
});
|
|
4243
4263
|
}
|
|
@@ -4256,8 +4276,8 @@ var DualMemoryEngine = class {
|
|
|
4256
4276
|
limit: options.limit || 10
|
|
4257
4277
|
});
|
|
4258
4278
|
return Array.isArray(result._data) ? result._data : [result._data];
|
|
4259
|
-
} catch (
|
|
4260
|
-
console.warn("Memory recall failed:",
|
|
4279
|
+
} catch (_error) {
|
|
4280
|
+
console.warn("Memory recall failed:", _error);
|
|
4261
4281
|
return [];
|
|
4262
4282
|
}
|
|
4263
4283
|
}
|
|
@@ -4267,32 +4287,32 @@ var DualMemoryEngine = class {
|
|
|
4267
4287
|
this.eventQueue.length = 0;
|
|
4268
4288
|
this.resetMetrics();
|
|
4269
4289
|
console.log("Memory cleared successfully");
|
|
4270
|
-
} catch (
|
|
4271
|
-
console.error("Failed to clear memory:",
|
|
4272
|
-
throw
|
|
4290
|
+
} catch (_error) {
|
|
4291
|
+
console.error("Failed to clear memory:", _error);
|
|
4292
|
+
throw _error;
|
|
4273
4293
|
}
|
|
4274
4294
|
}
|
|
4275
4295
|
// ========== Memory Strategy Selection ==========
|
|
4276
4296
|
async selectMemoryStrategy(query) {
|
|
4277
|
-
|
|
4297
|
+
const _factors = {
|
|
4278
4298
|
urgency: this.getUrgencyScore(query.urgency),
|
|
4279
4299
|
complexity: this.assessQueryComplexity(query),
|
|
4280
4300
|
type: this.getTypePreference(query.type),
|
|
4281
4301
|
cacheStatus: this.getCacheStatus(query)
|
|
4282
|
-
}
|
|
4283
|
-
this.calculateSystem1Score(
|
|
4284
|
-
this.calculateSystem2Score(
|
|
4302
|
+
};
|
|
4303
|
+
const _system1Score = this.calculateSystem1Score(_factors);
|
|
4304
|
+
const _system2Score = this.calculateSystem2Score(_factors);
|
|
4285
4305
|
switch (this.config.coordinator.conflictResolutionStrategy) {
|
|
4286
4306
|
case "system1_priority":
|
|
4287
|
-
return
|
|
4307
|
+
return _system1Score > 0.6 ? "system1" : "both";
|
|
4288
4308
|
case "system2_priority":
|
|
4289
|
-
return
|
|
4309
|
+
return _system2Score > 0.6 ? "system2" : "both";
|
|
4290
4310
|
case "balanced":
|
|
4291
4311
|
default:
|
|
4292
|
-
if (Math.abs(
|
|
4312
|
+
if (Math.abs(_system1Score - _system2Score) < 0.2) {
|
|
4293
4313
|
return "both";
|
|
4294
4314
|
}
|
|
4295
|
-
return
|
|
4315
|
+
return _system1Score > _system2Score ? "system1" : "system2";
|
|
4296
4316
|
}
|
|
4297
4317
|
}
|
|
4298
4318
|
getUrgencyScore(urgency) {
|
|
@@ -4310,34 +4330,34 @@ var DualMemoryEngine = class {
|
|
|
4310
4330
|
}
|
|
4311
4331
|
}
|
|
4312
4332
|
assessQueryComplexity(query) {
|
|
4313
|
-
let
|
|
4333
|
+
let complexity = 0.3;
|
|
4314
4334
|
if (query.query.length > 100) {
|
|
4315
|
-
|
|
4335
|
+
complexity += 0.2;
|
|
4316
4336
|
}
|
|
4317
4337
|
if (query.query.length > 200) {
|
|
4318
|
-
|
|
4338
|
+
complexity += 0.2;
|
|
4319
4339
|
}
|
|
4320
4340
|
if (query.context && Object.keys(query.context).length > 3) {
|
|
4321
|
-
|
|
4341
|
+
complexity += 0.2;
|
|
4322
4342
|
}
|
|
4323
4343
|
switch (query.type) {
|
|
4324
4344
|
case "reasoning":
|
|
4325
|
-
|
|
4345
|
+
complexity += 0.4;
|
|
4326
4346
|
break;
|
|
4327
4347
|
case "quality":
|
|
4328
|
-
|
|
4348
|
+
complexity += 0.3;
|
|
4329
4349
|
break;
|
|
4330
4350
|
case "pattern":
|
|
4331
|
-
|
|
4351
|
+
complexity += 0.2;
|
|
4332
4352
|
break;
|
|
4333
4353
|
case "knowledge":
|
|
4334
|
-
|
|
4354
|
+
complexity += 0.1;
|
|
4335
4355
|
break;
|
|
4336
4356
|
case "preference":
|
|
4337
|
-
|
|
4357
|
+
complexity += 0;
|
|
4338
4358
|
break;
|
|
4339
4359
|
}
|
|
4340
|
-
return Math.min(1,
|
|
4360
|
+
return Math.min(1, complexity);
|
|
4341
4361
|
}
|
|
4342
4362
|
getTypePreference(type2) {
|
|
4343
4363
|
switch (type2) {
|
|
@@ -4356,26 +4376,27 @@ var DualMemoryEngine = class {
|
|
|
4356
4376
|
}
|
|
4357
4377
|
}
|
|
4358
4378
|
getCacheStatus(query) {
|
|
4359
|
-
const
|
|
4360
|
-
const
|
|
4361
|
-
return
|
|
4362
|
-
}
|
|
4363
|
-
calculateSystem1Score(
|
|
4364
|
-
|
|
4365
|
-
(1 -
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
return
|
|
4369
|
-
}
|
|
4370
|
-
calculateSystem2Score(
|
|
4371
|
-
|
|
4372
|
-
(1 -
|
|
4373
|
-
|
|
4374
|
-
|
|
4379
|
+
const cacheKey = this.generateCacheKey(query);
|
|
4380
|
+
const cached = this.performanceCache.get(cacheKey);
|
|
4381
|
+
return cached ? 0.8 : 0.2;
|
|
4382
|
+
}
|
|
4383
|
+
calculateSystem1Score(_factors) {
|
|
4384
|
+
const _urgencyWeight = factors.urgency * 0.4;
|
|
4385
|
+
const _complexityPenalty = (1 - factors.complexity) * 0.3;
|
|
4386
|
+
const _typePreference = factors.type.system1 * 0.2;
|
|
4387
|
+
const _cacheBonus = factors.cacheStatus * 0.1;
|
|
4388
|
+
return _urgencyWeight + _complexityPenalty + _typePreference + _cacheBonus;
|
|
4389
|
+
}
|
|
4390
|
+
calculateSystem2Score(_factors) {
|
|
4391
|
+
const _complexityBonus = factors.complexity * 0.4;
|
|
4392
|
+
const _urgencyPenalty = (1 - factors.urgency) * 0.2;
|
|
4393
|
+
const _typePreference = factors.type.system2 * 0.3;
|
|
4394
|
+
const _qualityBonus = 0.1;
|
|
4395
|
+
return _complexityBonus + _urgencyPenalty + _typePreference + _qualityBonus;
|
|
4375
4396
|
}
|
|
4376
4397
|
// ========== Memory Operation Execution ==========
|
|
4377
|
-
async executeMemoryOperation(query,
|
|
4378
|
-
switch (
|
|
4398
|
+
async executeMemoryOperation(query, strategy) {
|
|
4399
|
+
switch (strategy) {
|
|
4379
4400
|
case "system1":
|
|
4380
4401
|
return this.executeSystem1Operation(query);
|
|
4381
4402
|
case "system2":
|
|
@@ -4383,38 +4404,38 @@ var DualMemoryEngine = class {
|
|
|
4383
4404
|
case "both":
|
|
4384
4405
|
return this.executeCombinedOperation(query);
|
|
4385
4406
|
default:
|
|
4386
|
-
throw new Error(`Unknown
|
|
4407
|
+
throw new Error(`Unknown _strategy: ${strategy}`);
|
|
4387
4408
|
}
|
|
4388
4409
|
}
|
|
4389
4410
|
async executeSystem1Operation(query) {
|
|
4390
4411
|
const _startTime = Date.now();
|
|
4391
|
-
let
|
|
4412
|
+
let _result;
|
|
4392
4413
|
switch (query.type) {
|
|
4393
4414
|
case "knowledge":
|
|
4394
|
-
|
|
4415
|
+
_result = await this.system1.searchKnowledgeNodes(
|
|
4395
4416
|
query.query,
|
|
4396
4417
|
query.embedding || [],
|
|
4397
4418
|
query.limit
|
|
4398
4419
|
);
|
|
4399
4420
|
break;
|
|
4400
4421
|
case "pattern": {
|
|
4401
|
-
const { language
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4422
|
+
const { language, framework, useCase } = query.context || {};
|
|
4423
|
+
_result = await this.system1.findCodePatterns(
|
|
4424
|
+
language,
|
|
4425
|
+
framework,
|
|
4405
4426
|
useCase,
|
|
4406
4427
|
query.limit
|
|
4407
4428
|
);
|
|
4408
4429
|
break;
|
|
4409
4430
|
}
|
|
4410
4431
|
case "preference":
|
|
4411
|
-
|
|
4432
|
+
_result = await this.system1.getUserPreference("learningStyle");
|
|
4412
4433
|
break;
|
|
4413
4434
|
default:
|
|
4414
4435
|
throw new Error(`System 1 cannot handle query type: ${query.type}`);
|
|
4415
4436
|
}
|
|
4416
4437
|
return {
|
|
4417
|
-
|
|
4438
|
+
_data: _result,
|
|
4418
4439
|
source: "system1",
|
|
4419
4440
|
confidence: 0.8,
|
|
4420
4441
|
latency: Date.now() - _startTime,
|
|
@@ -4423,14 +4444,14 @@ var DualMemoryEngine = class {
|
|
|
4423
4444
|
}
|
|
4424
4445
|
async executeSystem2Operation(query) {
|
|
4425
4446
|
const _startTime = Date.now();
|
|
4426
|
-
let
|
|
4447
|
+
let _result;
|
|
4427
4448
|
switch (query.type) {
|
|
4428
4449
|
case "reasoning": {
|
|
4429
|
-
const { domain: domain2, complexity
|
|
4430
|
-
|
|
4450
|
+
const { domain: domain2, complexity, minQuality } = query.context || {};
|
|
4451
|
+
_result = await this.system2.searchReasoningTraces(
|
|
4431
4452
|
{
|
|
4432
4453
|
domain: domain2,
|
|
4433
|
-
complexity
|
|
4454
|
+
complexity,
|
|
4434
4455
|
minQuality
|
|
4435
4456
|
},
|
|
4436
4457
|
query.limit
|
|
@@ -4438,13 +4459,13 @@ var DualMemoryEngine = class {
|
|
|
4438
4459
|
break;
|
|
4439
4460
|
}
|
|
4440
4461
|
case "quality":
|
|
4441
|
-
|
|
4462
|
+
_result = this.system2.qualityEvaluation;
|
|
4442
4463
|
break;
|
|
4443
4464
|
default:
|
|
4444
4465
|
throw new Error(`System 2 cannot handle query type: ${query.type}`);
|
|
4445
4466
|
}
|
|
4446
4467
|
return {
|
|
4447
|
-
|
|
4468
|
+
_data: _result,
|
|
4448
4469
|
source: "system2",
|
|
4449
4470
|
confidence: 0.9,
|
|
4450
4471
|
latency: Date.now() - _startTime,
|
|
@@ -4460,7 +4481,7 @@ var DualMemoryEngine = class {
|
|
|
4460
4481
|
]);
|
|
4461
4482
|
const _combinedResult = this.combineResults(query, system1Result, system2Result);
|
|
4462
4483
|
return {
|
|
4463
|
-
|
|
4484
|
+
_data: combinedResult._data,
|
|
4464
4485
|
source: "both",
|
|
4465
4486
|
confidence: combinedResult.confidence,
|
|
4466
4487
|
latency: Date.now() - _startTime,
|
|
@@ -4468,30 +4489,30 @@ var DualMemoryEngine = class {
|
|
|
4468
4489
|
suggestions: combinedResult.suggestions
|
|
4469
4490
|
};
|
|
4470
4491
|
} catch (_error) {
|
|
4471
|
-
query.type === "reasoning" || query.type === "quality" ? "system2" : "system1";
|
|
4472
|
-
return this.executeMemoryOperation(query,
|
|
4492
|
+
const _fallbackStrategy = query.type === "reasoning" || query.type === "quality" ? "system2" : "system1";
|
|
4493
|
+
return this.executeMemoryOperation(query, _fallbackStrategy);
|
|
4473
4494
|
}
|
|
4474
4495
|
}
|
|
4475
4496
|
combineResults(query, system1Result, system2Result) {
|
|
4476
|
-
system1Result.status === "fulfilled" ? system1Result.value?._data : null;
|
|
4477
|
-
system2Result.status === "fulfilled" ? system2Result.value?._data : null;
|
|
4478
|
-
if (
|
|
4479
|
-
this.assessQueryComplexity(query) > 0.6;
|
|
4497
|
+
const _s1Data = system1Result.status === "fulfilled" ? system1Result.value?._data : null;
|
|
4498
|
+
const _s2Data = system2Result.status === "fulfilled" ? system2Result.value?._data : null;
|
|
4499
|
+
if (_s2Data && _s1Data) {
|
|
4500
|
+
const _useSystem2 = this.assessQueryComplexity(query) > 0.6;
|
|
4480
4501
|
return {
|
|
4481
|
-
|
|
4502
|
+
_data: _useSystem2 ? _s2Data : _s1Data,
|
|
4482
4503
|
confidence: 0.95,
|
|
4483
|
-
suggestions: this.generateCombinedSuggestions(
|
|
4504
|
+
suggestions: this.generateCombinedSuggestions(_s1Data, _s2Data)
|
|
4484
4505
|
};
|
|
4485
4506
|
}
|
|
4486
|
-
if (
|
|
4487
|
-
return {
|
|
4507
|
+
if (_s1Data) {
|
|
4508
|
+
return { _data: _s1Data, confidence: 0.8 };
|
|
4488
4509
|
}
|
|
4489
|
-
if (
|
|
4490
|
-
return {
|
|
4510
|
+
if (_s2Data) {
|
|
4511
|
+
return { _data: _s2Data, confidence: 0.85 };
|
|
4491
4512
|
}
|
|
4492
4513
|
throw new Error("No memory systems could provide results");
|
|
4493
4514
|
}
|
|
4494
|
-
generateCombinedSuggestions(_s1Data,
|
|
4515
|
+
generateCombinedSuggestions(_s1Data, _s2Data) {
|
|
4495
4516
|
return [
|
|
4496
4517
|
{
|
|
4497
4518
|
id: `suggestion:${Date.now()}`,
|
|
@@ -4525,8 +4546,8 @@ var DualMemoryEngine = class {
|
|
|
4525
4546
|
routingStrategy.system2 ? this.system2.processMemoryEvent(event) : Promise.resolve()
|
|
4526
4547
|
]);
|
|
4527
4548
|
await this.adaptFromEvent(event);
|
|
4528
|
-
} catch (
|
|
4529
|
-
console.error(`Error processing memory event ${event.id}:`,
|
|
4549
|
+
} catch (_error) {
|
|
4550
|
+
console.error(`Error processing memory event ${event.id}:`, _error);
|
|
4530
4551
|
}
|
|
4531
4552
|
}
|
|
4532
4553
|
determineEventRouting(event) {
|
|
@@ -4595,7 +4616,7 @@ var DualMemoryEngine = class {
|
|
|
4595
4616
|
this.processingLock = true;
|
|
4596
4617
|
try {
|
|
4597
4618
|
const _batchSize = this.config.performance.batchSize;
|
|
4598
|
-
const _batch = this.eventQueue.splice(0,
|
|
4619
|
+
const _batch = this.eventQueue.splice(0, _batchSize);
|
|
4599
4620
|
await Promise.all(batch.map((event) => this.processEvent(event)));
|
|
4600
4621
|
} finally {
|
|
4601
4622
|
this.processingLock = false;
|
|
@@ -4603,9 +4624,9 @@ var DualMemoryEngine = class {
|
|
|
4603
4624
|
}
|
|
4604
4625
|
cleanupCache() {
|
|
4605
4626
|
const _maxAge = 30 * 60 * 1e3;
|
|
4606
|
-
for (const [key,
|
|
4607
|
-
const age = now.getTime() -
|
|
4608
|
-
if (age > _maxAge ||
|
|
4627
|
+
for (const [key, cached] of this.performanceCache.entries()) {
|
|
4628
|
+
const age = now.getTime() - cached.timestamp.getTime();
|
|
4629
|
+
if (age > _maxAge || cached.hits < 2) {
|
|
4609
4630
|
this.performanceCache.delete(key);
|
|
4610
4631
|
}
|
|
4611
4632
|
}
|
|
@@ -4617,12 +4638,12 @@ var DualMemoryEngine = class {
|
|
|
4617
4638
|
const _entries = Array.from(this.performanceCache.entries());
|
|
4618
4639
|
const _sortedByUsage = entries.sort((a2, b) => b[1].hits - a2[1].hits);
|
|
4619
4640
|
this.performanceCache.clear();
|
|
4620
|
-
sortedByUsage.slice(0, 500).forEach(([key,
|
|
4621
|
-
this.performanceCache.set(key,
|
|
4641
|
+
sortedByUsage.slice(0, 500).forEach(([key, value]) => {
|
|
4642
|
+
this.performanceCache.set(key, value);
|
|
4622
4643
|
});
|
|
4623
4644
|
}
|
|
4624
|
-
} catch (
|
|
4625
|
-
console.error("Memory optimization failed:",
|
|
4645
|
+
} catch (_error) {
|
|
4646
|
+
console.error("Memory optimization failed:", _error);
|
|
4626
4647
|
}
|
|
4627
4648
|
}
|
|
4628
4649
|
// ========== System Access Methods ==========
|
|
@@ -4642,22 +4663,22 @@ var DualMemoryEngine = class {
|
|
|
4642
4663
|
}
|
|
4643
4664
|
// ========== Utility Methods ==========
|
|
4644
4665
|
generateCacheKey(query) {
|
|
4645
|
-
query.context ? JSON.stringify(query.context) : "";
|
|
4646
|
-
query.embedding ? query.embedding.slice(0, 5).join(",") : "";
|
|
4647
|
-
return `${query.type}:${query.query}:${
|
|
4666
|
+
const _contextStr = query.context ? JSON.stringify(query.context) : "";
|
|
4667
|
+
const _embeddingStr = query.embedding ? query.embedding.slice(0, 5).join(",") : "";
|
|
4668
|
+
return `${query.type}:${query.query}:${_contextStr}:${_embeddingStr}:${query.limit || 10}`;
|
|
4648
4669
|
}
|
|
4649
|
-
isCacheValid(
|
|
4650
|
-
const age = Date.now() -
|
|
4651
|
-
const
|
|
4652
|
-
return age <
|
|
4670
|
+
isCacheValid(cached) {
|
|
4671
|
+
const age = Date.now() - cached.timestamp.getTime();
|
|
4672
|
+
const _maxAge = 10 * 60 * 1e3;
|
|
4673
|
+
return age < _maxAge;
|
|
4653
4674
|
}
|
|
4654
|
-
updateOperationMetrics(
|
|
4675
|
+
updateOperationMetrics(strategy, latency, success) {
|
|
4655
4676
|
this.operationMetrics.totalOperations++;
|
|
4656
4677
|
this.operationMetrics.averageLatency = (this.operationMetrics.averageLatency + latency) / 2;
|
|
4657
|
-
if (
|
|
4678
|
+
if (strategy === "system1" || strategy === "both") {
|
|
4658
4679
|
this.operationMetrics.system1Operations++;
|
|
4659
4680
|
}
|
|
4660
|
-
if (
|
|
4681
|
+
if (strategy === "system2" || strategy === "both") {
|
|
4661
4682
|
this.operationMetrics.system2Operations++;
|
|
4662
4683
|
}
|
|
4663
4684
|
if (!success) {
|
|
@@ -4677,11 +4698,11 @@ var DualMemoryEngine = class {
|
|
|
4677
4698
|
}
|
|
4678
4699
|
// ========== Public API for Monitoring ==========
|
|
4679
4700
|
getMetrics() {
|
|
4680
|
-
Array.from(this.performanceCache.values()).reduce(
|
|
4681
|
-
(sum,
|
|
4701
|
+
const _totalCacheAccess = Array.from(this.performanceCache.values()).reduce(
|
|
4702
|
+
(sum, cached) => sum + cached.hits,
|
|
4682
4703
|
0
|
|
4683
4704
|
);
|
|
4684
|
-
this.operationMetrics.cacheHitRate = this.operationMetrics.totalOperations > 0 ?
|
|
4705
|
+
this.operationMetrics.cacheHitRate = this.operationMetrics.totalOperations > 0 ? _totalCacheAccess / this.operationMetrics.totalOperations : 0;
|
|
4685
4706
|
return { ...this.operationMetrics };
|
|
4686
4707
|
}
|
|
4687
4708
|
resetMetrics() {
|
|
@@ -4698,9 +4719,9 @@ var DualMemoryEngine = class {
|
|
|
4698
4719
|
try {
|
|
4699
4720
|
this.resetMetrics();
|
|
4700
4721
|
this.performanceCache.clear();
|
|
4701
|
-
} catch (
|
|
4702
|
-
console.error("Failed to initialize DualMemoryEngine:",
|
|
4703
|
-
throw
|
|
4722
|
+
} catch (_error) {
|
|
4723
|
+
console.error("Failed to initialize DualMemoryEngine:", _error);
|
|
4724
|
+
throw _error;
|
|
4704
4725
|
}
|
|
4705
4726
|
}
|
|
4706
4727
|
// ========== Configuration Management ==========
|
|
@@ -4733,8 +4754,8 @@ var DualMemoryEngine = class {
|
|
|
4733
4754
|
// Will be populated when system2 interface is stable
|
|
4734
4755
|
};
|
|
4735
4756
|
return {
|
|
4736
|
-
system1:
|
|
4737
|
-
system2:
|
|
4757
|
+
system1: _system1Stats,
|
|
4758
|
+
system2: _system2Stats,
|
|
4738
4759
|
performance: {
|
|
4739
4760
|
avgResponseTime: metrics.averageLatency || 50,
|
|
4740
4761
|
memoryUsage: process.memoryUsage().heapUsed
|
|
@@ -4795,27 +4816,27 @@ var FileSystemService = class _FileSystemService {
|
|
|
4795
4816
|
async readFile(_filePath, encoding = "utf8") {
|
|
4796
4817
|
try {
|
|
4797
4818
|
const _resolvedPath = path.resolve(filePath);
|
|
4798
|
-
const _content = await fsAsync.readFile(
|
|
4799
|
-
this.logOperation("read",
|
|
4800
|
-
return
|
|
4819
|
+
const _content = await fsAsync.readFile(_resolvedPath, encoding);
|
|
4820
|
+
this.logOperation("read", _resolvedPath, true);
|
|
4821
|
+
return _content;
|
|
4801
4822
|
} catch (_error) {
|
|
4802
4823
|
this.logOperation("read", filePath, false);
|
|
4803
4824
|
throw new Error(`Failed to read file ${filePath}: ${error.message}`);
|
|
4804
4825
|
}
|
|
4805
4826
|
}
|
|
4806
|
-
async writeFile(filePath2,
|
|
4827
|
+
async writeFile(filePath2, content, options = {}) {
|
|
4807
4828
|
try {
|
|
4808
4829
|
const _resolvedPath = path.resolve(filePath2);
|
|
4809
|
-
if (options.backup && await this.exists(
|
|
4810
|
-
await this.createBackup(
|
|
4830
|
+
if (options.backup && await this.exists(_resolvedPath)) {
|
|
4831
|
+
await this.createBackup(_resolvedPath);
|
|
4811
4832
|
}
|
|
4812
4833
|
if (options.dryRun) {
|
|
4813
|
-
console.log(chalk2.yellow(`[DRY RUN] Would write to: ${
|
|
4834
|
+
console.log(chalk2.yellow(`[DRY RUN] Would write to: ${_resolvedPath}`));
|
|
4814
4835
|
return;
|
|
4815
4836
|
}
|
|
4816
|
-
await this.ensureDirectoryExists(path.dirname(
|
|
4817
|
-
await fsAsync.writeFile(
|
|
4818
|
-
this.logOperation("write",
|
|
4837
|
+
await this.ensureDirectoryExists(path.dirname(_resolvedPath));
|
|
4838
|
+
await fsAsync.writeFile(_resolvedPath, content);
|
|
4839
|
+
this.logOperation("write", _resolvedPath, true);
|
|
4819
4840
|
} catch (_error) {
|
|
4820
4841
|
this.logOperation("write", filePath2, false);
|
|
4821
4842
|
throw new Error(`Failed to write file ${filePath2}: ${error.message}`);
|
|
@@ -4824,18 +4845,18 @@ var FileSystemService = class _FileSystemService {
|
|
|
4824
4845
|
async deleteFile(_filePath, options = {}) {
|
|
4825
4846
|
try {
|
|
4826
4847
|
const _resolvedPath = path.resolve(filePath);
|
|
4827
|
-
if (!await this.exists(
|
|
4828
|
-
throw new Error(`File does not exist: ${
|
|
4848
|
+
if (!await this.exists(_resolvedPath)) {
|
|
4849
|
+
throw new Error(`File does not exist: ${_resolvedPath}`);
|
|
4829
4850
|
}
|
|
4830
4851
|
if (options.backup) {
|
|
4831
|
-
await this.createBackup(
|
|
4852
|
+
await this.createBackup(_resolvedPath);
|
|
4832
4853
|
}
|
|
4833
4854
|
if (options.dryRun) {
|
|
4834
|
-
console.log(chalk2.yellow(`[DRY RUN] Would delete: ${
|
|
4855
|
+
console.log(chalk2.yellow(`[DRY RUN] Would delete: ${_resolvedPath}`));
|
|
4835
4856
|
return;
|
|
4836
4857
|
}
|
|
4837
|
-
await fsAsync.unlink(
|
|
4838
|
-
this.logOperation("delete",
|
|
4858
|
+
await fsAsync.unlink(_resolvedPath);
|
|
4859
|
+
this.logOperation("delete", _resolvedPath, true);
|
|
4839
4860
|
} catch (_error) {
|
|
4840
4861
|
this.logOperation("delete", filePath, false);
|
|
4841
4862
|
throw new Error(`Failed to delete file ${filePath}: ${error.message}`);
|
|
@@ -4846,11 +4867,11 @@ var FileSystemService = class _FileSystemService {
|
|
|
4846
4867
|
try {
|
|
4847
4868
|
const _resolvedPath = path.resolve(dirPath);
|
|
4848
4869
|
if (options.dryRun) {
|
|
4849
|
-
console.log(chalk2.yellow(`[DRY RUN] Would create directory: ${
|
|
4870
|
+
console.log(chalk2.yellow(`[DRY RUN] Would create directory: ${_resolvedPath}`));
|
|
4850
4871
|
return;
|
|
4851
4872
|
}
|
|
4852
|
-
await fsAsync.mkdir(
|
|
4853
|
-
this.logOperation("mkdir",
|
|
4873
|
+
await fsAsync.mkdir(_resolvedPath, { recursive: options.recursive ?? true });
|
|
4874
|
+
this.logOperation("mkdir", _resolvedPath, true);
|
|
4854
4875
|
} catch (_error) {
|
|
4855
4876
|
this.logOperation("mkdir", dirPath, false);
|
|
4856
4877
|
throw new Error(`Failed to create directory ${dirPath}: ${error.message}`);
|
|
@@ -4859,19 +4880,19 @@ var FileSystemService = class _FileSystemService {
|
|
|
4859
4880
|
async deleteDirectory(_dirPath, options = {}) {
|
|
4860
4881
|
try {
|
|
4861
4882
|
const _resolvedPath = path.resolve(dirPath);
|
|
4862
|
-
if (!await this.exists(
|
|
4863
|
-
throw new Error(`Directory does not exist: ${
|
|
4883
|
+
if (!await this.exists(_resolvedPath)) {
|
|
4884
|
+
throw new Error(`Directory does not exist: ${_resolvedPath}`);
|
|
4864
4885
|
}
|
|
4865
4886
|
if (options.dryRun) {
|
|
4866
|
-
console.log(chalk2.yellow(`[DRY RUN] Would delete directory: ${
|
|
4887
|
+
console.log(chalk2.yellow(`[DRY RUN] Would delete directory: ${_resolvedPath}`));
|
|
4867
4888
|
return;
|
|
4868
4889
|
}
|
|
4869
4890
|
if (options.recursive) {
|
|
4870
|
-
await this.deleteDirectoryRecursive(
|
|
4891
|
+
await this.deleteDirectoryRecursive(_resolvedPath);
|
|
4871
4892
|
} else {
|
|
4872
|
-
await fsAsync.rmdir(
|
|
4893
|
+
await fsAsync.rmdir(_resolvedPath);
|
|
4873
4894
|
}
|
|
4874
|
-
this.logOperation("rmdir",
|
|
4895
|
+
this.logOperation("rmdir", _resolvedPath, true);
|
|
4875
4896
|
} catch (_error) {
|
|
4876
4897
|
this.logOperation("rmdir", dirPath, false);
|
|
4877
4898
|
throw new Error(`Failed to delete directory ${dirPath}: ${error.message}`);
|
|
@@ -4880,14 +4901,14 @@ var FileSystemService = class _FileSystemService {
|
|
|
4880
4901
|
async listDirectory(_dirPath, options = {}) {
|
|
4881
4902
|
try {
|
|
4882
4903
|
const _resolvedPath = path.resolve(dirPath);
|
|
4883
|
-
const _entries = await fsAsync.readdir(
|
|
4884
|
-
const
|
|
4885
|
-
for (const
|
|
4886
|
-
if (!options.includeHidden &&
|
|
4904
|
+
const _entries = await fsAsync.readdir(_resolvedPath);
|
|
4905
|
+
const results = [];
|
|
4906
|
+
for (const entry of _entries) {
|
|
4907
|
+
if (!options.includeHidden && entry.startsWith(".")) {
|
|
4887
4908
|
continue;
|
|
4888
4909
|
}
|
|
4889
|
-
const _entryPath = path.join(
|
|
4890
|
-
const _stats = await this.getFileStats(
|
|
4910
|
+
const _entryPath = path.join(_resolvedPath, entry);
|
|
4911
|
+
const _stats = await this.getFileStats(_entryPath);
|
|
4891
4912
|
if (options.type) {
|
|
4892
4913
|
if (options.type === "file" && !stats.isFile) {
|
|
4893
4914
|
continue;
|
|
@@ -4898,14 +4919,14 @@ var FileSystemService = class _FileSystemService {
|
|
|
4898
4919
|
}
|
|
4899
4920
|
if (options.pattern) {
|
|
4900
4921
|
const _match = options.caseSensitive ? stats.name.includes(options.pattern) : stats.name.toLowerCase().includes(options.pattern.toLowerCase());
|
|
4901
|
-
if (!
|
|
4922
|
+
if (!_match) {
|
|
4902
4923
|
continue;
|
|
4903
4924
|
}
|
|
4904
4925
|
}
|
|
4905
|
-
|
|
4926
|
+
results.push(_stats);
|
|
4906
4927
|
}
|
|
4907
|
-
this.logOperation("readdir",
|
|
4908
|
-
return
|
|
4928
|
+
this.logOperation("readdir", _resolvedPath, true);
|
|
4929
|
+
return results.sort((a2, b) => {
|
|
4909
4930
|
if (a2.isDirectory && !b.isDirectory) {
|
|
4910
4931
|
return -1;
|
|
4911
4932
|
}
|
|
@@ -4924,23 +4945,23 @@ var FileSystemService = class _FileSystemService {
|
|
|
4924
4945
|
try {
|
|
4925
4946
|
const _resolvedSource = path.resolve(sourcePath);
|
|
4926
4947
|
const _resolvedDest = path.resolve(destPath);
|
|
4927
|
-
if (!await this.exists(
|
|
4928
|
-
throw new Error(`Source file does not exist: ${
|
|
4948
|
+
if (!await this.exists(_resolvedSource)) {
|
|
4949
|
+
throw new Error(`Source file does not exist: ${_resolvedSource}`);
|
|
4929
4950
|
}
|
|
4930
4951
|
if (options.dryRun) {
|
|
4931
|
-
console.log(chalk2.yellow(`[DRY RUN] Would copy: ${
|
|
4952
|
+
console.log(chalk2.yellow(`[DRY RUN] Would copy: ${_resolvedSource} \u2192 ${_resolvedDest}`));
|
|
4932
4953
|
return;
|
|
4933
4954
|
}
|
|
4934
|
-
await this.ensureDirectoryExists(path.dirname(
|
|
4935
|
-
if (await this.exists(
|
|
4936
|
-
throw new Error(`Destination file already exists: ${
|
|
4955
|
+
await this.ensureDirectoryExists(path.dirname(_resolvedDest));
|
|
4956
|
+
if (await this.exists(_resolvedDest) && !options.force) {
|
|
4957
|
+
throw new Error(`Destination file already exists: ${_resolvedDest}`);
|
|
4937
4958
|
}
|
|
4938
|
-
await fsAsync.copyFile(
|
|
4959
|
+
await fsAsync.copyFile(_resolvedSource, _resolvedDest);
|
|
4939
4960
|
if (options.preserveTimestamps) {
|
|
4940
|
-
const _sourceStats = await fsAsync.stat(
|
|
4941
|
-
await fs.promises.utimes(
|
|
4961
|
+
const _sourceStats = await fsAsync.stat(_resolvedSource);
|
|
4962
|
+
await fs.promises.utimes(_resolvedDest, sourceStats.atime, sourceStats.mtime);
|
|
4942
4963
|
}
|
|
4943
|
-
this.logOperation("copy", `${
|
|
4964
|
+
this.logOperation("copy", `${_resolvedSource} \u2192 ${_resolvedDest}`, true);
|
|
4944
4965
|
} catch (_error) {
|
|
4945
4966
|
this.logOperation("copy", `${sourcePath} \u2192 ${destPath}`, false);
|
|
4946
4967
|
throw new Error(`Failed to copy file: ${error.message}`);
|
|
@@ -4950,19 +4971,19 @@ var FileSystemService = class _FileSystemService {
|
|
|
4950
4971
|
try {
|
|
4951
4972
|
const _resolvedSource = path.resolve(sourcePath);
|
|
4952
4973
|
const _resolvedDest = path.resolve(destPath);
|
|
4953
|
-
if (!await this.exists(
|
|
4954
|
-
throw new Error(`Source file does not exist: ${
|
|
4974
|
+
if (!await this.exists(_resolvedSource)) {
|
|
4975
|
+
throw new Error(`Source file does not exist: ${_resolvedSource}`);
|
|
4955
4976
|
}
|
|
4956
4977
|
if (options.dryRun) {
|
|
4957
|
-
console.log(chalk2.yellow(`[DRY RUN] Would move: ${
|
|
4978
|
+
console.log(chalk2.yellow(`[DRY RUN] Would move: ${_resolvedSource} \u2192 ${_resolvedDest}`));
|
|
4958
4979
|
return;
|
|
4959
4980
|
}
|
|
4960
|
-
await this.ensureDirectoryExists(path.dirname(
|
|
4961
|
-
if (await this.exists(
|
|
4962
|
-
throw new Error(`Destination file already exists: ${
|
|
4981
|
+
await this.ensureDirectoryExists(path.dirname(_resolvedDest));
|
|
4982
|
+
if (await this.exists(_resolvedDest) && !options.force) {
|
|
4983
|
+
throw new Error(`Destination file already exists: ${_resolvedDest}`);
|
|
4963
4984
|
}
|
|
4964
|
-
await fsAsync.rename(
|
|
4965
|
-
this.logOperation("move", `${
|
|
4985
|
+
await fsAsync.rename(_resolvedSource, _resolvedDest);
|
|
4986
|
+
this.logOperation("move", `${_resolvedSource} \u2192 ${_resolvedDest}`, true);
|
|
4966
4987
|
} catch (_error) {
|
|
4967
4988
|
this.logOperation("move", `${sourcePath} \u2192 ${destPath}`, false);
|
|
4968
4989
|
throw new Error(`Failed to move file: ${error.message}`);
|
|
@@ -4975,13 +4996,13 @@ var FileSystemService = class _FileSystemService {
|
|
|
4975
4996
|
async findFiles(_searchPath, options = {}) {
|
|
4976
4997
|
try {
|
|
4977
4998
|
const _resolvedPath = path.resolve(searchPath);
|
|
4978
|
-
const
|
|
4979
|
-
await this.findFilesRecursive(
|
|
4980
|
-
this.logOperation("find",
|
|
4981
|
-
return
|
|
4999
|
+
const results = [];
|
|
5000
|
+
await this.findFilesRecursive(_resolvedPath, options, results, 0);
|
|
5001
|
+
this.logOperation("find", _resolvedPath, true);
|
|
5002
|
+
return results;
|
|
4982
5003
|
} catch (_error) {
|
|
4983
5004
|
this.logOperation("find", searchPath, false);
|
|
4984
|
-
throw new Error(`Failed to search
|
|
5005
|
+
throw new Error(`Failed to search _files: ${error.message}`);
|
|
4985
5006
|
}
|
|
4986
5007
|
}
|
|
4987
5008
|
async which(command2) {
|
|
@@ -5000,21 +5021,21 @@ var FileSystemService = class _FileSystemService {
|
|
|
5000
5021
|
});
|
|
5001
5022
|
});
|
|
5002
5023
|
}
|
|
5003
|
-
async glob(
|
|
5004
|
-
|
|
5005
|
-
patternParts.slice(0, -1).join(path.sep) || "./";
|
|
5006
|
-
|
|
5024
|
+
async glob(pattern2, options = {}) {
|
|
5025
|
+
const _patternParts = pattern2.split(path.sep);
|
|
5026
|
+
const _basePath = patternParts.slice(0, -1).join(path.sep) || "./";
|
|
5027
|
+
const _filePattern = _patternParts[patternParts.length - 1];
|
|
5007
5028
|
try {
|
|
5008
|
-
const _regexPattern =
|
|
5009
|
-
const _files = await this.findFiles(
|
|
5029
|
+
const _regexPattern = _filePattern.replace(/\./g, "\\.").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
5030
|
+
const _files = await this.findFiles(_basePath, {
|
|
5010
5031
|
...options,
|
|
5011
|
-
|
|
5032
|
+
_pattern: `^${_regexPattern}$`,
|
|
5012
5033
|
regex: true,
|
|
5013
5034
|
type: "file"
|
|
5014
5035
|
});
|
|
5015
5036
|
return files.map((f) => f.path);
|
|
5016
5037
|
} catch (_error) {
|
|
5017
|
-
throw new Error(`Failed to glob
|
|
5038
|
+
throw new Error(`Failed to glob _pattern ${pattern2}: ${error.message}`);
|
|
5018
5039
|
}
|
|
5019
5040
|
}
|
|
5020
5041
|
// Utility Methods
|
|
@@ -5029,11 +5050,11 @@ var FileSystemService = class _FileSystemService {
|
|
|
5029
5050
|
async getFileStats(filePath2) {
|
|
5030
5051
|
try {
|
|
5031
5052
|
const _resolvedPath = path.resolve(filePath2);
|
|
5032
|
-
const _stats = await fsAsync.lstat(
|
|
5033
|
-
const _name = path.basename(
|
|
5053
|
+
const _stats = await fsAsync.lstat(_resolvedPath);
|
|
5054
|
+
const _name = path.basename(_resolvedPath);
|
|
5034
5055
|
return {
|
|
5035
|
-
|
|
5036
|
-
path:
|
|
5056
|
+
_name,
|
|
5057
|
+
path: _resolvedPath,
|
|
5037
5058
|
isFile: stats.isFile(),
|
|
5038
5059
|
isDirectory: stats.isDirectory(),
|
|
5039
5060
|
isSymlink: stats.isSymbolicLink(),
|
|
@@ -5043,7 +5064,7 @@ var FileSystemService = class _FileSystemService {
|
|
|
5043
5064
|
permissions: (stats.mode & parseInt("777", 8)).toString(8)
|
|
5044
5065
|
};
|
|
5045
5066
|
} catch (_error) {
|
|
5046
|
-
throw new Error(`Failed to get file
|
|
5067
|
+
throw new Error(`Failed to get file _stats for ${filePath2}: ${error.message}`);
|
|
5047
5068
|
}
|
|
5048
5069
|
}
|
|
5049
5070
|
async getRealPath(filePath2) {
|
|
@@ -5065,73 +5086,74 @@ var FileSystemService = class _FileSystemService {
|
|
|
5065
5086
|
await fsAsync.mkdir(dirPath2, { recursive: true });
|
|
5066
5087
|
} catch (_error) {
|
|
5067
5088
|
if (error.code !== "EEXIST") {
|
|
5068
|
-
throw
|
|
5089
|
+
throw _error;
|
|
5069
5090
|
}
|
|
5070
5091
|
}
|
|
5071
5092
|
}
|
|
5072
5093
|
async createBackup(filePath2) {
|
|
5073
|
-
|
|
5094
|
+
const _backupPath = `${filePath2}.backup.${Date.now()}`;
|
|
5095
|
+
await fsAsync.copyFile(filePath2, _backupPath);
|
|
5074
5096
|
}
|
|
5075
5097
|
async deleteDirectoryRecursive(dirPath2) {
|
|
5076
|
-
await fsAsync.readdir(dirPath2);
|
|
5077
|
-
for (const
|
|
5078
|
-
path.join(dirPath2,
|
|
5079
|
-
await fsAsync.lstat(
|
|
5098
|
+
const _entries = await fsAsync.readdir(dirPath2);
|
|
5099
|
+
for (const entry of _entries) {
|
|
5100
|
+
const _entryPath = path.join(dirPath2, entry);
|
|
5101
|
+
await fsAsync.lstat(_entryPath);
|
|
5080
5102
|
if (stats.isDirectory()) {
|
|
5081
|
-
await this.deleteDirectoryRecursive(
|
|
5103
|
+
await this.deleteDirectoryRecursive(_entryPath);
|
|
5082
5104
|
} else {
|
|
5083
|
-
await fsAsync.unlink(
|
|
5105
|
+
await fsAsync.unlink(_entryPath);
|
|
5084
5106
|
}
|
|
5085
5107
|
}
|
|
5086
5108
|
await fsAsync.rmdir(dirPath2);
|
|
5087
5109
|
}
|
|
5088
|
-
async findFilesRecursive(searchPath2, options,
|
|
5110
|
+
async findFilesRecursive(searchPath2, options, results, depth) {
|
|
5089
5111
|
if (options.maxDepth && depth >= options.maxDepth) {
|
|
5090
5112
|
return;
|
|
5091
5113
|
}
|
|
5092
5114
|
try {
|
|
5093
5115
|
const _entries = await fsAsync.readdir(searchPath2);
|
|
5094
|
-
for (const
|
|
5095
|
-
if (!options.includeHidden &&
|
|
5116
|
+
for (const entry of _entries) {
|
|
5117
|
+
if (!options.includeHidden && entry.startsWith(".")) {
|
|
5096
5118
|
continue;
|
|
5097
5119
|
}
|
|
5098
|
-
const _entryPath = path.join(searchPath2,
|
|
5099
|
-
const _stats = await this.getFileStats(
|
|
5120
|
+
const _entryPath = path.join(searchPath2, entry);
|
|
5121
|
+
const _stats = await this.getFileStats(_entryPath);
|
|
5100
5122
|
if (options.pattern) {
|
|
5101
5123
|
const _pattern = options.regex ? new RegExp(options.pattern, options.caseSensitive ? "g" : "gi") : null;
|
|
5102
|
-
const _match =
|
|
5103
|
-
if (
|
|
5124
|
+
const _match = _pattern ? pattern.test(stats.name) : options.caseSensitive ? stats.name.includes(options.pattern) : stats.name.toLowerCase().includes(options.pattern.toLowerCase());
|
|
5125
|
+
if (_match) {
|
|
5104
5126
|
if (options.type) {
|
|
5105
5127
|
if (options.type === "file" && stats.isFile) {
|
|
5106
|
-
|
|
5128
|
+
results.push(_stats);
|
|
5107
5129
|
}
|
|
5108
5130
|
if (options.type === "directory" && stats.isDirectory) {
|
|
5109
|
-
|
|
5131
|
+
results.push(_stats);
|
|
5110
5132
|
}
|
|
5111
5133
|
if (options.type === "both") {
|
|
5112
|
-
|
|
5134
|
+
results.push(_stats);
|
|
5113
5135
|
}
|
|
5114
5136
|
} else {
|
|
5115
|
-
|
|
5137
|
+
results.push(_stats);
|
|
5116
5138
|
}
|
|
5117
5139
|
}
|
|
5118
5140
|
} else if (!options.pattern) {
|
|
5119
5141
|
if (options.type) {
|
|
5120
5142
|
if (options.type === "file" && stats.isFile) {
|
|
5121
|
-
|
|
5143
|
+
results.push(_stats);
|
|
5122
5144
|
}
|
|
5123
5145
|
if (options.type === "directory" && stats.isDirectory) {
|
|
5124
|
-
|
|
5146
|
+
results.push(_stats);
|
|
5125
5147
|
}
|
|
5126
5148
|
if (options.type === "both") {
|
|
5127
|
-
|
|
5149
|
+
results.push(_stats);
|
|
5128
5150
|
}
|
|
5129
5151
|
} else {
|
|
5130
|
-
|
|
5152
|
+
results.push(_stats);
|
|
5131
5153
|
}
|
|
5132
5154
|
}
|
|
5133
5155
|
if (stats.isDirectory && (options.followSymlinks || !stats.isSymlink)) {
|
|
5134
|
-
await this.findFilesRecursive(
|
|
5156
|
+
await this.findFilesRecursive(_entryPath, options, results, depth + 1);
|
|
5135
5157
|
}
|
|
5136
5158
|
}
|
|
5137
5159
|
} catch (_error) {
|