closed-loop-cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of closed-loop-cli might be problematic. Click here for more details.

Files changed (86) hide show
  1. package/dist/dashboard/server.js +237 -0
  2. package/dist/index.js +272 -0
  3. package/dist/orchestrator/agent-prompts.js +42 -0
  4. package/dist/orchestrator/autogenesis.js +973 -0
  5. package/dist/orchestrator/dgm-archive.js +223 -0
  6. package/dist/orchestrator/event-stream.js +103 -0
  7. package/dist/orchestrator/fitness-evaluator.js +99 -0
  8. package/dist/orchestrator/meta-agent.js +421 -0
  9. package/dist/orchestrator/microagent-registry.js +134 -0
  10. package/dist/orchestrator/mutation-strategies.js +174 -0
  11. package/dist/orchestrator/prompt-benchmark.js +102 -0
  12. package/dist/orchestrator/prompt-optimizer.js +169 -0
  13. package/dist/orchestrator/refactor-scanner.js +222 -0
  14. package/dist/orchestrator/research-manager.js +104 -0
  15. package/dist/orchestrator/rulez.js +135 -0
  16. package/dist/orchestrator/sahoo-gateway.js +261 -0
  17. package/dist/orchestrator/state-manager.js +121 -0
  18. package/dist/orchestrator/task-agent.js +444 -0
  19. package/dist/orchestrator/telegram-bot.js +374 -0
  20. package/dist/orchestrator/types.js +2 -0
  21. package/dist/tests/dynamic/dependencies.test.js +37 -0
  22. package/dist/tests/dynamic/dummy.test.js +7 -0
  23. package/dist/tests/dynamic/fuzzy-patch.test.js +68 -0
  24. package/dist/tests/dynamic/indexer.test.js +60 -0
  25. package/dist/tests/dynamic/openhands.test.js +83 -0
  26. package/dist/tests/dynamic/skills.test.js +88 -0
  27. package/dist/tests/run-tests.js +294 -0
  28. package/dist/tools/diff-tools.js +24 -0
  29. package/dist/tools/file-tools.js +191 -0
  30. package/dist/tools/indexer.js +301 -0
  31. package/dist/tools/math-helper.js +6 -0
  32. package/dist/tools/repo-map.js +122 -0
  33. package/dist/tools/search-tools.js +271 -0
  34. package/dist/tools/shell-tools.js +75 -0
  35. package/dist/tools/skills.js +122 -0
  36. package/dist/tools/tui-tools.js +82 -0
  37. package/docs/AI_Arch_Opt_Anti_Gaming.md +227 -0
  38. package/docs/AI_Self_Improvement_Safety.md +457 -0
  39. package/docs/Anthropic AI Agents_ Capabilities and Concerns.md +134 -0
  40. package/docs/Auto_ClosedLoop_AI_Agent.md +415 -0
  41. package/docs/Autonomous AI Agents_ Closing the Loop.docx +0 -0
  42. package/docs/Secure_AI_Sandbox_Framework.md +358 -0
  43. package/docs/skills/add-file-existence-check-utility.json +9 -0
  44. package/docs/skills/add-utility-function-for-file-existence-check.json +9 -0
  45. package/docs/skills/add-utility-function-to-module.json +9 -0
  46. package/docs/skills/extract-command-runner-utility.json +9 -0
  47. package/docs/skills/file-existence-check-utility.json +9 -0
  48. package/package.json +36 -0
  49. package/src/dashboard/public/index.css +1334 -0
  50. package/src/dashboard/public/index.html +385 -0
  51. package/src/dashboard/public/index.js +1059 -0
  52. package/src/dashboard/server.ts +209 -0
  53. package/src/index.ts +256 -0
  54. package/src/orchestrator/agent-prompts.ts +43 -0
  55. package/src/orchestrator/autogenesis.ts +1078 -0
  56. package/src/orchestrator/dgm-archive.ts +257 -0
  57. package/src/orchestrator/event-stream.ts +90 -0
  58. package/src/orchestrator/fitness-evaluator.ts +154 -0
  59. package/src/orchestrator/meta-agent.ts +434 -0
  60. package/src/orchestrator/microagent-registry.ts +115 -0
  61. package/src/orchestrator/microagents/git-helper.md +11 -0
  62. package/src/orchestrator/microagents/test-fixer.md +10 -0
  63. package/src/orchestrator/microagents/typescript-expert.md +11 -0
  64. package/src/orchestrator/mutation-strategies.ts +214 -0
  65. package/src/orchestrator/research-manager.ts +88 -0
  66. package/src/orchestrator/rulez.ts +118 -0
  67. package/src/orchestrator/sahoo-gateway.ts +300 -0
  68. package/src/orchestrator/state-manager.ts +161 -0
  69. package/src/orchestrator/system-prompt.txt +1 -0
  70. package/src/orchestrator/task-agent.ts +461 -0
  71. package/src/orchestrator/telegram-bot.ts +358 -0
  72. package/src/tests/dynamic/dependencies.test.ts +48 -0
  73. package/src/tests/dynamic/dummy.test.ts +4 -0
  74. package/src/tests/dynamic/fuzzy-patch.test.ts +42 -0
  75. package/src/tests/dynamic/indexer.test.ts +31 -0
  76. package/src/tests/dynamic/openhands.test.ts +59 -0
  77. package/src/tests/dynamic/skills.test.ts +63 -0
  78. package/src/tests/run-tests.ts +296 -0
  79. package/src/tools/diff-tools.ts +27 -0
  80. package/src/tools/file-tools.ts +187 -0
  81. package/src/tools/indexer.ts +325 -0
  82. package/src/tools/repo-map.ts +96 -0
  83. package/src/tools/search-tools.ts +258 -0
  84. package/src/tools/shell-tools.ts +90 -0
  85. package/src/tools/skills.ts +101 -0
  86. package/src/tools/tui-tools.ts +87 -0
@@ -0,0 +1,374 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.startTelegramBot = startTelegramBot;
37
+ const https = __importStar(require("https"));
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const child_process_1 = require("child_process");
41
+ const state_manager_1 = require("./state-manager");
42
+ async function callTelegramApi(token, method, payload) {
43
+ return new Promise((resolve, reject) => {
44
+ const url = `https://api.telegram.org/bot${token}/${method}`;
45
+ const data = JSON.stringify(payload);
46
+ const req = https.request(url, {
47
+ method: 'POST',
48
+ headers: {
49
+ 'Content-Type': 'application/json',
50
+ 'Content-Length': Buffer.byteLength(data),
51
+ },
52
+ }, (res) => {
53
+ let body = '';
54
+ res.on('data', chunk => body += chunk);
55
+ res.on('end', () => {
56
+ try {
57
+ const response = JSON.parse(body);
58
+ if (response.ok) {
59
+ resolve(response.result);
60
+ }
61
+ else {
62
+ reject(new Error(`Telegram API Error: ${response.description}`));
63
+ }
64
+ }
65
+ catch (e) {
66
+ reject(e);
67
+ }
68
+ });
69
+ });
70
+ req.on('error', reject);
71
+ req.write(data);
72
+ req.end();
73
+ });
74
+ }
75
+ let runningProcess = null;
76
+ async function handleTelegramCommand(token, message, activeChats) {
77
+ const chatId = message.chat.id;
78
+ const text = message.text?.trim() || '';
79
+ if (text.startsWith('/start') || text.startsWith('/help')) {
80
+ await callTelegramApi(token, 'sendMessage', {
81
+ chat_id: chatId,
82
+ text: `🤖 *Closed-Loop Agent ChatOps Console*\n\n` +
83
+ `*Commands:*\n` +
84
+ `/status - View metrics, cycles, token budget, and active task status\n` +
85
+ `/logs - View last 25 log lines of evolution.log\n` +
86
+ `/refactor <goal> - Run autonomous refactoring for goal\n` +
87
+ `/task <task> - Run custom evolution step for task\n` +
88
+ `/kill - Cancel any running task spawned by the bot`,
89
+ parse_mode: 'Markdown'
90
+ });
91
+ return;
92
+ }
93
+ if (text.startsWith('/status')) {
94
+ const state = (0, state_manager_1.getEvolutionState)();
95
+ const statusText = `📊 *Current Agent Status: ${state.status.toUpperCase()}*\n\n` +
96
+ `- *Cycle*: ${state.currentCycle} / ${state.maxCycles === 0 ? 'Infinite' : state.maxCycles}\n` +
97
+ `- *Token Budget*: ${state.tokenBudget} total\n` +
98
+ `- *Tokens Used*: ${state.tokensUsed.total} (Input: ${state.tokensUsed.input}, Output: ${state.tokensUsed.output})\n` +
99
+ `- *Last Updated*: ${state.lastUpdated}\n` +
100
+ `- *Current Task*: ${state.currentTask || 'None'}`;
101
+ await callTelegramApi(token, 'sendMessage', {
102
+ chat_id: chatId,
103
+ text: statusText,
104
+ parse_mode: 'Markdown'
105
+ });
106
+ return;
107
+ }
108
+ if (text.startsWith('/logs')) {
109
+ try {
110
+ const logPath = path.join(process.cwd(), 'evolution.log');
111
+ if (fs.existsSync(logPath)) {
112
+ const logContent = fs.readFileSync(logPath, 'utf-8');
113
+ const lines = logContent.split('\n');
114
+ const lastLines = lines.slice(-25).join('\n');
115
+ await callTelegramApi(token, 'sendMessage', {
116
+ chat_id: chatId,
117
+ text: `📝 *Last 25 log lines:*\n\`\`\`\n${lastLines || 'No logs yet.'}\n\`\`\``,
118
+ parse_mode: 'Markdown'
119
+ });
120
+ }
121
+ else {
122
+ await callTelegramApi(token, 'sendMessage', {
123
+ chat_id: chatId,
124
+ text: `❌ Log file 'evolution.log' does not exist yet.`
125
+ });
126
+ }
127
+ }
128
+ catch (err) {
129
+ await callTelegramApi(token, 'sendMessage', {
130
+ chat_id: chatId,
131
+ text: `❌ Error reading log file: ${err.message}`
132
+ });
133
+ }
134
+ return;
135
+ }
136
+ if (text.startsWith('/kill')) {
137
+ if (runningProcess) {
138
+ runningProcess.kill();
139
+ runningProcess = null;
140
+ await callTelegramApi(token, 'sendMessage', {
141
+ chat_id: chatId,
142
+ text: `🛑 Active evolution task was manually terminated.`
143
+ });
144
+ }
145
+ else {
146
+ await callTelegramApi(token, 'sendMessage', {
147
+ chat_id: chatId,
148
+ text: `ℹ️ No active evolution task is running.`
149
+ });
150
+ }
151
+ return;
152
+ }
153
+ const isRefactor = text.startsWith('/refactor ');
154
+ const isTask = text.startsWith('/task ');
155
+ if (isRefactor || isTask) {
156
+ if (runningProcess) {
157
+ await callTelegramApi(token, 'sendMessage', {
158
+ chat_id: chatId,
159
+ text: `⚠️ An evolution task is already running. Use /kill to stop it first.`
160
+ });
161
+ return;
162
+ }
163
+ const commandArg = isRefactor ? text.substring(10).trim() : text.substring(6).trim();
164
+ if (!commandArg) {
165
+ await callTelegramApi(token, 'sendMessage', {
166
+ chat_id: chatId,
167
+ text: `❌ Command argument cannot be empty.`
168
+ });
169
+ return;
170
+ }
171
+ // Run the agent process
172
+ await callTelegramApi(token, 'sendMessage', {
173
+ chat_id: chatId,
174
+ text: `🚀 Starting task: "${commandArg}"\nWaiting for initialization...`
175
+ });
176
+ let currentStage = 'reflecting';
177
+ let outputBuffer = '';
178
+ let lastSendTime = Date.now();
179
+ const sendBufferedOutput = async () => {
180
+ if (!outputBuffer.trim())
181
+ return;
182
+ const cleanOutput = outputBuffer.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
183
+ outputBuffer = '';
184
+ lastSendTime = Date.now();
185
+ const chunk = cleanOutput.length > 3900 ? cleanOutput.substring(cleanOutput.length - 3900) : cleanOutput;
186
+ try {
187
+ await callTelegramApi(token, 'sendMessage', {
188
+ chat_id: chatId,
189
+ text: `💻 *Process Logs:*\n\`\`\`\n${chunk}\n\`\`\``,
190
+ parse_mode: 'Markdown'
191
+ });
192
+ }
193
+ catch (err) {
194
+ console.error('[Telegram Bot] Failed to send log chunk:', err.message);
195
+ }
196
+ };
197
+ const handleData = async (data) => {
198
+ outputBuffer += data;
199
+ let stageChanged = false;
200
+ let newStage = '';
201
+ let stageEmoji = '';
202
+ let stageLabel = '';
203
+ if (data.includes('AGP - Reflect') && currentStage !== 'reflecting') {
204
+ newStage = 'reflecting';
205
+ stageEmoji = '🔄';
206
+ stageLabel = 'Reflecting (Diagnosis)';
207
+ stageChanged = true;
208
+ }
209
+ else if (data.includes('AGP - Scan') && currentStage !== 'scanning') {
210
+ newStage = 'scanning';
211
+ stageEmoji = '🔍';
212
+ stageLabel = 'Scanning Codebase';
213
+ stageChanged = true;
214
+ }
215
+ else if ((data.includes('improve') || data.includes('Self-Modification Loop') || data.includes('TaskAgent')) && currentStage !== 'improving') {
216
+ newStage = 'improving';
217
+ stageEmoji = '🛠️';
218
+ stageLabel = 'Refactoring / Implementing';
219
+ stageChanged = true;
220
+ }
221
+ else if ((data.includes('AGP - Evaluate') || data.includes('evaluate') || data.includes('SAHOO')) && currentStage !== 'evaluating') {
222
+ newStage = 'evaluating';
223
+ stageEmoji = '🧪';
224
+ stageLabel = 'Evaluating & SAHOO Verification';
225
+ stageChanged = true;
226
+ }
227
+ else if (data.includes('AGP - Commit') && currentStage !== 'committing') {
228
+ newStage = 'committing';
229
+ stageEmoji = '💾';
230
+ stageLabel = 'Committing Changes';
231
+ stageChanged = true;
232
+ }
233
+ else if (data.includes('AGP - Rollback') && currentStage !== 'rolling_back') {
234
+ newStage = 'rolling_back';
235
+ stageEmoji = '⚠️';
236
+ stageLabel = 'Rolling Back Mutations';
237
+ stageChanged = true;
238
+ }
239
+ if (stageChanged) {
240
+ currentStage = newStage;
241
+ await sendBufferedOutput();
242
+ await callTelegramApi(token, 'sendMessage', {
243
+ chat_id: chatId,
244
+ text: `${stageEmoji} *Evolution Stage*: ${stageLabel}...`,
245
+ parse_mode: 'Markdown'
246
+ });
247
+ }
248
+ else if (Date.now() - lastSendTime > 4000) {
249
+ await sendBufferedOutput();
250
+ }
251
+ };
252
+ const processArgs = ['dist/index.js'];
253
+ if (isRefactor) {
254
+ processArgs.push(`Refactor ${commandArg}`);
255
+ }
256
+ else {
257
+ processArgs.push(commandArg);
258
+ }
259
+ const child = (0, child_process_1.spawn)('node', processArgs, {
260
+ cwd: process.cwd(),
261
+ env: { ...process.env, FORCE_COLOR: '0' }
262
+ });
263
+ runningProcess = child;
264
+ child.stdout.on('data', (chunk) => {
265
+ handleData(chunk.toString());
266
+ });
267
+ child.stderr.on('data', (chunk) => {
268
+ handleData(chunk.toString());
269
+ });
270
+ child.on('close', async (code) => {
271
+ runningProcess = null;
272
+ await sendBufferedOutput();
273
+ if (code === 0) {
274
+ await callTelegramApi(token, 'sendMessage', {
275
+ chat_id: chatId,
276
+ text: `✅ *Evolution Step Completed Successfully!* (Exit Code: ${code})`,
277
+ parse_mode: 'Markdown'
278
+ });
279
+ }
280
+ else {
281
+ await callTelegramApi(token, 'sendMessage', {
282
+ chat_id: chatId,
283
+ text: `❌ *Evolution Step Failed / Aborted!* (Exit Code: ${code})`,
284
+ parse_mode: 'Markdown'
285
+ });
286
+ }
287
+ });
288
+ child.on('error', async (err) => {
289
+ runningProcess = null;
290
+ await callTelegramApi(token, 'sendMessage', {
291
+ chat_id: chatId,
292
+ text: `❌ *Subprocess Error:* ${err.message}`,
293
+ parse_mode: 'Markdown'
294
+ });
295
+ });
296
+ }
297
+ }
298
+ async function startTelegramBot() {
299
+ const token = process.env.TELEGRAM_BOT_TOKEN;
300
+ if (!token) {
301
+ console.log('\x1b[33m[Telegram Bot] Warning: TELEGRAM_BOT_TOKEN is not set in .env. Telegram ChatOps will be inactive.\x1b[0m');
302
+ return;
303
+ }
304
+ const allowedUserIdsStr = process.env.TELEGRAM_ALLOWED_USER_IDS || '';
305
+ const allowedUserIds = allowedUserIdsStr.split(',').map(s => s.trim()).filter(Boolean);
306
+ console.log(`\x1b[32m[Telegram Bot] Initializing Telegram ChatOps... Allowed User IDs: [${allowedUserIds.join(', ')}]\x1b[0m`);
307
+ let lastUpdateId = 0;
308
+ const activeChats = new Set();
309
+ // Start polling loop
310
+ (async () => {
311
+ while (true) {
312
+ try {
313
+ const updates = await callTelegramApi(token, 'getUpdates', {
314
+ offset: lastUpdateId + 1,
315
+ timeout: 20,
316
+ });
317
+ for (const update of updates) {
318
+ lastUpdateId = Math.max(lastUpdateId, update.update_id);
319
+ if (update.message) {
320
+ const chatId = update.message.chat.id;
321
+ const fromId = update.message.from?.id;
322
+ const fromIdStr = fromId ? String(fromId) : '';
323
+ if (!allowedUserIds.includes(fromIdStr)) {
324
+ console.log(`[Telegram Bot] Blocked unauthorized message from user ID: ${fromIdStr}`);
325
+ await callTelegramApi(token, 'sendMessage', {
326
+ chat_id: chatId,
327
+ text: `❌ *Unauthorized*\nYour User ID (${fromIdStr}) is not in the allowed list.`,
328
+ parse_mode: 'Markdown'
329
+ });
330
+ continue;
331
+ }
332
+ activeChats.add(chatId);
333
+ await handleTelegramCommand(token, update.message, activeChats);
334
+ }
335
+ }
336
+ }
337
+ catch (err) {
338
+ console.error('[Telegram Bot] Error polling updates:', err.message);
339
+ await new Promise(resolve => setTimeout(resolve, 5000));
340
+ }
341
+ }
342
+ })();
343
+ // Start state monitoring / progress broadcasting
344
+ let lastStateStr = '';
345
+ setInterval(() => {
346
+ try {
347
+ const state = (0, state_manager_1.getEvolutionState)();
348
+ const stateStr = JSON.stringify({
349
+ status: state.status,
350
+ currentCycle: state.currentCycle,
351
+ tokensUsed: state.tokensUsed.total
352
+ });
353
+ if (lastStateStr && lastStateStr !== stateStr && activeChats.size > 0) {
354
+ const broadcastText = `📢 *Evolution State Update*\n\n` +
355
+ `- *Status*: ${state.status.toUpperCase()}\n` +
356
+ `- *Cycle*: ${state.currentCycle}\n` +
357
+ `- *Tokens Used*: ${state.tokensUsed.total}`;
358
+ for (const chatId of activeChats) {
359
+ callTelegramApi(token, 'sendMessage', {
360
+ chat_id: chatId,
361
+ text: broadcastText,
362
+ parse_mode: 'Markdown'
363
+ }).catch(err => {
364
+ console.error(`[Telegram Bot] Failed to broadcast state to chat ${chatId}:`, err.message);
365
+ });
366
+ }
367
+ }
368
+ lastStateStr = stateStr;
369
+ }
370
+ catch (e) {
371
+ // ignore
372
+ }
373
+ }, 5000);
374
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.run = run;
4
+ const indexer_1 = require("../../tools/indexer");
5
+ async function run() {
6
+ console.log(" --> Running Dependency Graph tests...");
7
+ const workspaceRoot = process.cwd();
8
+ // 1. Rebuild Index
9
+ const index = (0, indexer_1.generateCodeIndex)(workspaceRoot);
10
+ if (index.length === 0) {
11
+ throw new Error("Failed to index files!");
12
+ }
13
+ // Find a file to test dependencies on, e.g. shell-tools.ts
14
+ const shellToolsFile = 'src/tools/shell-tools.ts';
15
+ const dependents = (0, indexer_1.getDependents)(shellToolsFile, workspaceRoot);
16
+ console.log(` --> Dependents of "${shellToolsFile}":\n`, dependents);
17
+ if (dependents.length === 0) {
18
+ throw new Error(`Expected at least one file to import "${shellToolsFile}" but found none!`);
19
+ }
20
+ // Check that key importing files are in the list
21
+ const hasTaskAgent = dependents.some(d => d.includes('task-agent.ts'));
22
+ const hasTests = dependents.some(d => d.includes('run-tests.ts'));
23
+ if (!hasTaskAgent && !hasTests) {
24
+ throw new Error(`Dependency check missed expected importers like task-agent.ts or run-tests.ts!`);
25
+ }
26
+ // 2. Check imports extraction
27
+ const taskAgentIndex = index.find(f => f.filePath === 'src/orchestrator/task-agent.ts');
28
+ if (!taskAgentIndex) {
29
+ throw new Error("Failed to find task-agent.ts index entry!");
30
+ }
31
+ console.log(" --> Imports of task-agent.ts:\n", taskAgentIndex.imports);
32
+ const importsShellTools = taskAgentIndex.imports.some(imp => imp.includes('shell-tools'));
33
+ if (!importsShellTools) {
34
+ throw new Error("Failed to extract shell-tools import from task-agent.ts!");
35
+ }
36
+ console.log(" --> Dependency Graph tests passed!");
37
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.run = run;
4
+ // Dummy dynamic test file
5
+ async function run() {
6
+ console.log(" --> Dynamic dummy test execution successful!");
7
+ }
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.run = run;
37
+ const file_tools_1 = require("../../tools/file-tools");
38
+ const fs = __importStar(require("fs"));
39
+ async function run() {
40
+ console.log(" --> Running Fuzzy Patch tests...");
41
+ const testFile = 'temp-fuzzy-test.ts';
42
+ // Write source code with dynamic formatting
43
+ const originalCode = `function calculateTotal(a: number, b: number) {
44
+ const sum = a + b;
45
+ return sum;
46
+ }`;
47
+ (0, file_tools_1.writeFile)(testFile, originalCode);
48
+ // Attempt fuzzy edit: target has different spaces and newlines
49
+ const targetWithDifferentSpacing = `const sum = a + b;
50
+ return sum;`;
51
+ const replacement = `const sum = a + b;
52
+ console.log("Adding:", a, b);
53
+ return sum;`;
54
+ try {
55
+ (0, file_tools_1.editFile)(testFile, targetWithDifferentSpacing, replacement);
56
+ const resultingCode = (0, file_tools_1.readFile)(testFile);
57
+ console.log(" --> Output content after fuzzy edit:\n", resultingCode);
58
+ if (!resultingCode.includes('console.log("Adding:", a, b)')) {
59
+ throw new Error("Fuzzy patch was not applied successfully!");
60
+ }
61
+ console.log(" --> Fuzzy Patch tests passed!");
62
+ }
63
+ finally {
64
+ if (fs.existsSync(testFile)) {
65
+ fs.unlinkSync(testFile);
66
+ }
67
+ }
68
+ }
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.run = run;
37
+ const indexer_1 = require("../../tools/indexer");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ async function run() {
41
+ console.log(" --> Running indexer tests...");
42
+ // 1. Generate code index
43
+ const workspaceRoot = process.cwd();
44
+ const index = (0, indexer_1.generateCodeIndex)(workspaceRoot);
45
+ if (index.length === 0) {
46
+ throw new Error("Indexed file list should not be empty!");
47
+ }
48
+ // Verify code-index.json exists
49
+ const indexPath = path.join(workspaceRoot, 'code-index.json');
50
+ if (!fs.existsSync(indexPath)) {
51
+ throw new Error("code-index.json file was not created!");
52
+ }
53
+ // 2. Query index
54
+ const queryResult = (0, indexer_1.queryCodeIndex)("AutogenesisEngine");
55
+ console.log(" --> Query search 'AutogenesisEngine' result:\n", queryResult);
56
+ if (!queryResult.includes("AutogenesisEngine")) {
57
+ throw new Error("Indexer query failed to find 'AutogenesisEngine'");
58
+ }
59
+ console.log(" --> Indexer tests passed!");
60
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.run = run;
37
+ const event_stream_1 = require("../../orchestrator/event-stream");
38
+ const microagent_registry_1 = require("../../orchestrator/microagent-registry");
39
+ const fs = __importStar(require("fs"));
40
+ const path = __importStar(require("path"));
41
+ async function run() {
42
+ console.log(" --> Running OpenHands (EventStream & Microagents) tests...");
43
+ // 1. Test EventStream
44
+ const stream = event_stream_1.EventStream.getInstance();
45
+ stream.clear();
46
+ stream.publish('user', 'message', 'TestUserQuery', 'Hello agent');
47
+ stream.publish('agent', 'action', 'readFile', '{"path": "package.json"}');
48
+ stream.publish('environment', 'observation', 'readFileObservation', 'File content here');
49
+ const events = stream.getEvents();
50
+ if (events.length !== 3) {
51
+ throw new Error(`Expected 3 events in EventStream, got ${events.length}`);
52
+ }
53
+ if (events[0].source !== 'user' || events[0].name !== 'TestUserQuery') {
54
+ throw new Error(`EventStream mismatch on user query: ${JSON.stringify(events[0])}`);
55
+ }
56
+ if (events[1].source !== 'agent' || events[1].type !== 'action') {
57
+ throw new Error(`EventStream mismatch on agent action: ${JSON.stringify(events[1])}`);
58
+ }
59
+ // Verify file was written
60
+ const historyPath = path.join(process.cwd(), 'event-stream-history.json');
61
+ if (!fs.existsSync(historyPath)) {
62
+ throw new Error('event-stream-history.json was not created');
63
+ }
64
+ // 2. Test MicroagentRegistry
65
+ const registry = microagent_registry_1.MicroagentRegistry.getInstance();
66
+ registry.loadMicroagents();
67
+ const allAgents = registry.getMicroagents();
68
+ if (allAgents.length === 0) {
69
+ throw new Error('MicroagentRegistry failed to load microagents');
70
+ }
71
+ // Test triggers
72
+ const gitMatches = registry.findMatchingMicroagents('Please commit the changes and push');
73
+ const hasGitHelper = gitMatches.some(a => a.name === 'Git Helper');
74
+ if (!hasGitHelper) {
75
+ throw new Error('Expected Git Helper to match query containing "commit"');
76
+ }
77
+ const tsMatches = registry.findMatchingMicroagents('Refactor using typescript helper');
78
+ const hasTsExpert = tsMatches.some(a => a.name === 'TypeScript Expert');
79
+ if (!hasTsExpert) {
80
+ throw new Error('Expected TypeScript Expert to match query containing "typescript"');
81
+ }
82
+ console.log(" --> OpenHands (EventStream & Microagents) tests passed successfully!");
83
+ }