closed-loop-cli 1.0.2 → 1.0.4

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.

package/CLAUDE.md ADDED
@@ -0,0 +1,17 @@
1
+ # CLAUDE.md - Project Development Guidelines
2
+
3
+ ## Project Commands
4
+ - **Build**: `npm run build` (Compiles TypeScript files into `dist/`)
5
+ - **Run CLI**: `npm start` (Runs the compiled CLI application)
6
+ - **Run Tests**: `npm test` (Executes the test suite and self-eval task)
7
+
8
+ ## Code Quality & Linting
9
+ - Ensure typescript compiles with zero warnings or errors.
10
+ - Do not check in `dist/` files to Git.
11
+
12
+ ## Coding Style & Principles
13
+ 1. **TypeScript & Types**: Avoid `any` types. Provide explicit interfaces for options, configuration, and API responses.
14
+ 2. **File Operations**: Use the custom tools in `src/tools/file-tools.ts` for file interactions.
15
+ 3. **Execution Safety**: Always wrap external commands in a timeout and check their exit codes.
16
+ 4. **Self-Healing Loop**: The agent must record failures in `Learnings.md` and attempt to heal them by editing files and re-running tests.
17
+ 5. **No Placeholders**: Write fully functional implementations.
package/Learnings.md ADDED
@@ -0,0 +1,73 @@
1
+ # Persistent Repository Learnings
2
+
3
+ This file acts as a local, repository-versioned memory layer for the coding agent. Before each task, the agent reads this file along with `CLAUDE.md`. Upon completion of any task, the agent appends its findings below in the strict format.
4
+
5
+ ## Format Guidelines
6
+ For every completed or failed task, append a new section at the end of the file:
7
+ ```markdown
8
+ ### [YYYY-MM-DD] - [Task/Goal Title]
9
+ - **Observation (สิ่งที่พบ)**: Describe the problem, codebase quirks, linter failures, or unexpected behaviors.
10
+ - **Action (การแก้ไข)**: Describe how the problem was resolved (e.g. prompt edits, specific file modifications, library upgrades).
11
+ - **Confidence (ความมั่นใจ 0-1)**: Score representing how robust the solution is.
12
+ ```
13
+
14
+ ---
15
+ ## Learnings History
16
+
17
+ ### 2026-06-05 - Initial Setup
18
+ - **Observation (สิ่งที่พบ)**: Workspace was empty except for DOCX documentation.
19
+ - **Action (การแก้ไข)**: Initialized Node.js, TSConfig, CLAUDE.md, and core file/shell tools for the agent.
20
+ - **Confidence (ความมั่นใจ 0-1)**: 1.0
21
+
22
+ ### 2026-06-05 - Add fileExists Helper Function
23
+ - **Observation (สิ่งที่พบ)**: `src/tools/file-tools.ts` had `readFile`, `writeFile`, `editFile`, `listDir`, and `grepSearch` but lacked a simple boolean existence check.
24
+ - **Action (การแก้ไข)**: Added `fileExists(filePath: string, workspaceRoot?: string): boolean` that resolves the path via `resolveWorkspacePath` and returns `fs.existsSync(resolved)`. Placed it between `readFile` and `writeFile` for logical grouping. Build and all tests passed.
25
+ - **Confidence (ความมั่นใจ 0-1)**: 1.0
26
+
27
+ ### 2024-12-05 - Add helper function fileExists to file-tools.ts
28
+ - **Observation (สิ่งที่พบ)**: The implementation was successful. Adding the `fileExists` function using `fs.existsSync` and the existing `resolveWorkspacePath` utility integrated cleanly. The build (`npm run build`) and test suite (`npm test`) both passed without errors or failures.
29
+ - **Action (การแก้ไข)**:
30
+ 1. Added the `fileExists` function to `src/tools/file-tools.ts` with the implementation: `export const fileExists = (path: string): boolean => { const resolved = resolveWorkspacePath(path); return fs.existsSync(resolved); };`
31
+ 2. Executed `npm run build` to verify TypeScript compilation.
32
+ 3. Executed `npm test` to run the full test suite and verify functionality.
33
+ - **Confidence (ความมั่นใจ 0-1)**: 1.0
34
+
35
+ ### 2025-04-24 - Add a comment to shell-tools.ts
36
+ - **Observation (สิ่งที่พบ)**: The task was straightforward and completed successfully. Adding a single-line comment at the top of a TypeScript file (`src/tools/shell-tools.ts`) did not introduce any linter or compilation errors, and the subsequent TypeScript build (`npm run build`) passed cleanly. The codebase accepted the change without any quirks or side effects.
37
+ - **Action (การแก้ไข)**: Added the comment `// Utility wrapper for shell execution.` as the first line of the file. Verified the change by running `npm run build`, which returned zero errors.
38
+ - **Confidence (ความมั่นใจ 0-1)**: 0.95
39
+
40
+ ### 2024-07-23 - Compilation Error Handling Test
41
+ - **Observation (สิ่งที่พบ)**: Injecting a function with an intentional TypeScript syntax error (referencing an undeclared variable) correctly caused the compiler to fail with exit code 2 and a `TS2304` error. The self-healing loop (reverting the faulty code, then rebuilding and retesting) successfully restored the codebase to a passing state.
42
+ - **Action (การแก้ไข)**: Executed a test that added a broken function (`getFileSizeWithBrokenRef`) referencing `nonExistentVar`, triggered a build to confirm the compilation failure, then reverted the change and verified the build and all tests passed cleanly.
43
+ - **Confidence (ความมั่นใจ 0-1)**: 0.95
44
+
45
+ ### 2025-10-15 - Search for the latest version of Node.js and print it
46
+ - **Observation (สิ่งที่พบ)**: The agent successfully performed a web search and synthesized the results to provide a clear, structured summary of the latest Node.js versions (Current, LTS, and Maintenance). It also correctly compared the found LTS version (v24.11.0) to the locally running version (v24.16.0) in the workspace.
47
+ - **Action (การแก้ไข)**: The agent generated a formatted markdown table and "Key Takeaways" section to present the search results, effectively clarifying the release lines and their recommended use cases.
48
+ - **Confidence (ความมั่นใจ 0-1)**: 0.95
49
+
50
+ ### 2024-01-24 - Write a comment inside src/index.ts stating that Phase 3 is initialized
51
+ - **Observation (สิ่งที่พบ)**: The task was completed successfully and cleanly. The build passed after adding the comment, indicating no syntax or build-system issues were introduced.
52
+ - **Action (การแก้ไข)**: Added the comment `// Phase 3 is initialized` to the file `src/index.ts`, placing it immediately after the import statements.
53
+ - **Confidence (ความมั่นใจ 0-1)**: 0.9
54
+
55
+ ### 2026-06-06 - Web Dashboard Monitor Integration
56
+ - **Observation (สิ่งที่พบ)**: Adding a web dashboard to monitor the evolution daemon introduces build-safety quirks. Because the continuous daemon runs `git reset --hard HEAD` and `git clean -fd` when a SAHOO gate check fails or a compile error occurs, any newly created untracked files are wiped out instantly.
57
+ - **Action (การแก้ไข)**: Temporarily halted the daemon, built a zero-dependency HTTP server served on port 3000, and immediately added/committed the dashboard files to Git HEAD. Now the files are fully preserved during resets.
58
+ - **Confidence (ความมั่นใจ 0-1)**: 1.0
59
+
60
+ ### 2026-06-06 - Create Program Launchers for Windows
61
+ - **Observation (สิ่งที่พบ)**: Running the agent CLI, dashboard server, and daemon on Windows requires multiple terminals and commands (compilation + execution). Batch files are an effective way to simplify this for Windows users.
62
+ - **Action (การแก้ไข)**: Created `start-agent-cli.bat`, `start-dashboard.bat`, and `start-evolution-daemon.bat` at the root of the workspace. These scripts automatically handle `node_modules` checking, TypeScript compilation (`npm run build`), launching the processes, and opening default browsers.
63
+ - **Confidence (ความมั่นใจ 0-1)**: 1.0
64
+
65
+ ### 2026-06-06 - Enhance Autonomous Agent Loop and Dashboard UI
66
+ - **Observation (สิ่งที่พบ)**: The agent requirements in the document demand high-effort settings ("ultracode"), role-based boundaries (explorer vs worker), destination path sanitization checks, and programmatic logging of agent decisions and attempts (Live Research Manager).
67
+ - **Action (การแก้ไข)**:
68
+ 1. Implemented `ResearchManager` to write sessions and decisions to `research-log.json`.
69
+ 2. Updated `runTaskAgent` and `runSelfImprovingTask` to support `--effort` / `ultracode` settings, allowing extended steps (up to 45) and strict prompts for alternate architecture scanning, regression detection, and precise filepath outputs.
70
+ 3. Added `/api/research` to `server.ts` and integrated a visual "Live Research Log" timeline into the HTML, JS, and CSS files of the web dashboard.
71
+ - **Confidence (ความมั่นใจ 0-1)**: 1.0
72
+
73
+
package/dist/index.js CHANGED
@@ -38,20 +38,19 @@ const fs = __importStar(require("fs"));
38
38
  const path = __importStar(require("path"));
39
39
  const readline = __importStar(require("readline"));
40
40
  const dotenv = __importStar(require("dotenv"));
41
- const autogenesis_1 = require("./orchestrator/autogenesis");
41
+ const os = __importStar(require("os"));
42
42
  const server_1 = require("./dashboard/server");
43
43
  const telegram_bot_1 = require("./orchestrator/telegram-bot");
44
44
  const task_agent_1 = require("./orchestrator/task-agent");
45
- // Phase 3 is initialized
46
45
  // Load environment variables
47
46
  dotenv.config();
48
47
  function printHeader() {
49
- const banner = `
50
- \x1b[38;5;99m ___ _ _ _
51
- / __\\ | ___ ___ ___ __| | | | ___ ___ _ __
52
- / / | |/ _ \\/ __|/ _ \\/ _\` | | |/ _ \\ / _ \\| '_ \\
53
- / /___| | (_) \\__ \\ __/ (_| | | | (_) | (_) | |_) |
54
- \\____/|_|\\___/|___/\\___|\\__,_| |_|\\___/ \\___/| .__/
48
+ const banner = `
49
+ \x1b[38;5;99m ___ _ _ _
50
+ / __\\ | ___ ___ ___ __| | | | ___ ___ _ __
51
+ / / | |/ _ \\/ __|/ _ \\/ _\` | | |/ _ \\ / _ \\| '_ \\
52
+ / /___| | (_) \\__ \\ __/ (_| | | | (_) | (_) | |_) |
53
+ \\____/|_|\\___/|___/\\___|\\__,_| |_|\\___/ \\___/| .__/
55
54
  |_| \x1b[0m`;
56
55
  console.log(banner);
57
56
  console.log('\x1b[37mTips for getting started:\x1b[0m');
@@ -91,12 +90,12 @@ class ClosedLoopTUI {
91
90
  // Clear screen and move cursor to 1,1
92
91
  process.stdout.write('\x1b[2J\x1b[H');
93
92
  // 1. Draw Banner & Info
94
- const banner = `
95
- \x1b[38;5;99m ___ _ _ _
96
- / __\\ | ___ ___ ___ __| | | | ___ ___ _ __
97
- / / | |/ _ \\/ __|/ _ \\/ _\` | | |/ _ \\ / _ \\| '_ \\
98
- / /___| | (_) \\__ \\ __/ (_| | | | (_) | (_) | |_) |
99
- \\____/|_|\\___/|___/\\___|\\__,_| |_|\\___/ \\___/| .__/
93
+ const banner = `
94
+ \x1b[38;5;99m ___ _ _ _
95
+ / __\\ | ___ ___ ___ __| | | | ___ ___ _ __
96
+ / / | |/ _ \\/ __|/ _ \\/ _\` | | |/ _ \\ / _ \\| '_ \\
97
+ / /___| | (_) \\__ \\ __/ (_| | | | (_) | (_) | |_) |
98
+ \\____/|_|\\___/|___/\\___|\\__,_| |_|\\___/ \\___/| .__/
100
99
  |_| \x1b[0m`;
101
100
  console.log(banner);
102
101
  console.log('\x1b[37mTips for getting started:\x1b[0m');
@@ -240,20 +239,50 @@ async function startInteractiveCLI(effort = 'standard', codeactMode = false) {
240
239
  const tui = new ClosedLoopTUI(effort);
241
240
  tui.start();
242
241
  }
243
- function setupLogRedirection() {
244
- const logFile = fs.createWriteStream(path.join(process.cwd(), 'evolution.log'), { flags: 'a' });
245
- const originalLog = console.log;
246
- const originalError = console.error;
247
- console.log = function (...args) {
248
- originalLog.apply(console, args);
249
- logFile.write(args.join(' ') + '\n');
250
- };
251
- console.error = function (...args) {
252
- originalError.apply(console, args);
253
- logFile.write('ERROR: ' + args.join(' ') + '\n');
242
+ async function checkAndPromptAPIKey() {
243
+ if (process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN) {
244
+ return process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN || '';
245
+ }
246
+ const configPath = path.join(os.homedir(), '.closed-loop.json');
247
+ if (fs.existsSync(configPath)) {
248
+ try {
249
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
250
+ if (config.apiKey) {
251
+ process.env.ANTHROPIC_API_KEY = config.apiKey;
252
+ return config.apiKey;
253
+ }
254
+ }
255
+ catch (e) { }
256
+ }
257
+ console.log('\n\x1b[33m🔑 Anthropic API key not found in environment or local .env file.\x1b[0m');
258
+ console.log('To run this assistant, please configure your API key below.');
259
+ const rl = readline.createInterface({
260
+ input: process.stdin,
261
+ output: process.stdout
262
+ });
263
+ const question = (query) => {
264
+ return new Promise(resolve => rl.question(query, resolve));
254
265
  };
266
+ const key = await question('\x1b[35mEnter your Anthropic API Key:\x1b[0m ');
267
+ rl.close();
268
+ const trimmedKey = key.trim();
269
+ if (!trimmedKey) {
270
+ console.error('\x1b[31mError: API Key cannot be empty.\x1b[0m');
271
+ process.exit(1);
272
+ }
273
+ try {
274
+ fs.writeFileSync(configPath, JSON.stringify({ apiKey: trimmedKey }, null, 2), 'utf8');
275
+ console.log(`\x1b[32m✔ Saved API key to ${configPath}\x1b[0m\n`);
276
+ }
277
+ catch (err) {
278
+ console.warn(`\x1b[33mWarning: Could not save API key to config: ${err.message}\x1b[0m`);
279
+ }
280
+ process.env.ANTHROPIC_API_KEY = trimmedKey;
281
+ return trimmedKey;
255
282
  }
256
283
  async function main() {
284
+ // Ensure API Key is configured before running any agent logic
285
+ await checkAndPromptAPIKey();
257
286
  const args = process.argv.slice(2);
258
287
  // Parse codeact option
259
288
  let codeactMode = false;
@@ -302,107 +331,8 @@ async function main() {
302
331
  process.exit(1);
303
332
  }
304
333
  }
305
- const isContinuous = args.includes('--continuous') || args.includes('-c');
306
- if (isContinuous) {
307
- try {
308
- let cycles = 0; // infinite
309
- const cyclesIdx = args.indexOf('--cycles');
310
- if (cyclesIdx !== -1 && cyclesIdx + 1 < args.length) {
311
- cycles = parseInt(args[cyclesIdx + 1], 10) || 0;
312
- }
313
- let tokenBudget = 500000; // default 500k tokens
314
- const budgetIdx = args.indexOf('--budget-tokens');
315
- if (budgetIdx !== -1 && budgetIdx + 1 < args.length) {
316
- tokenBudget = parseInt(args[budgetIdx + 1], 10) || 500000;
317
- }
318
- console.log(`\n\x1b[33m[Running Continuous Self-Evolution Daemon Mode]\x1b[0m`);
319
- console.log(`- Cycle Limit: ${cycles === 0 ? 'Infinite' : cycles}`);
320
- console.log(`- Token Budget: ${tokenBudget} tokens\n`);
321
- setupLogRedirection();
322
- (0, server_1.startDashboardServer)();
323
- (0, telegram_bot_1.startTelegramBot)();
324
- const engine = new autogenesis_1.AutogenesisEngine();
325
- engine.setEffort(effort);
326
- engine.codeactMode = codeactMode;
327
- await engine.runContinuousEvolution(cycles, tokenBudget);
328
- console.log('\n\x1b[32m[Continuous Self-Evolution Daemon Stopped Cleanly]\x1b[0m');
329
- process.exit(0);
330
- }
331
- catch (err) {
332
- console.error('\n\x1b[31m[Continuous Self-Evolution Daemon Failed]:\x1b[0m', err.message);
333
- process.exit(1);
334
- }
335
- }
336
- if (args[0] === '--refactor') {
337
- try {
338
- console.log(`\n\x1b[33m[Running Autonomous Refactoring Mode]\x1b[0m`);
339
- const engine = new autogenesis_1.AutogenesisEngine();
340
- engine.setEffort(effort);
341
- engine.codeactMode = codeactMode;
342
- await engine.runAutonomousRefactor();
343
- console.log('\n\x1b[32m[Autonomous Refactoring Completed]\x1b[0m');
344
- process.exit(0);
345
- }
346
- catch (err) {
347
- console.error('\n\x1b[31m[Autonomous Refactoring Failed]:\x1b[0m', err.message);
348
- process.exit(1);
349
- }
350
- }
351
- if (args[0] === '--optimize-prompt') {
352
- try {
353
- console.log(`\n\x1b[33m[Running Prompt Optimization Benchmarking Mode]\x1b[0m`);
354
- const engine = new autogenesis_1.AutogenesisEngine();
355
- engine.setEffort(effort);
356
- engine.codeactMode = codeactMode;
357
- await engine.runPromptOptimization();
358
- console.log('\n\x1b[32m[Prompt Optimization Completed]\x1b[0m');
359
- process.exit(0);
360
- }
361
- catch (err) {
362
- console.error('\n\x1b[31m[Prompt Optimization Failed]:\x1b[0m', err.message);
363
- process.exit(1);
364
- }
365
- }
366
- if (args[0] === '--dgm') {
367
- try {
368
- // Parse optional --generations N flag
369
- let maxGenerations = 5;
370
- const genIdx = args.indexOf('--generations');
371
- if (genIdx !== -1 && genIdx + 1 < args.length) {
372
- maxGenerations = parseInt(args[genIdx + 1], 10) || 5;
373
- args.splice(genIdx, 2);
374
- }
375
- // Task is everything after --dgm flag
376
- const dgmTask = args.slice(1).join(' ') || 'Improve the codebase using open-ended evolution';
377
- console.log(`\n\x1b[33m[Running DGM (Darwin Gödel Machine) Evolution Mode]\x1b[0m`);
378
- console.log(`Task: "${dgmTask}" | Generations: ${maxGenerations}\n`);
379
- const engine = new autogenesis_1.AutogenesisEngine();
380
- engine.setEffort(effort);
381
- engine.codeactMode = codeactMode;
382
- await engine.runDGMEvolution(dgmTask, maxGenerations);
383
- console.log('\n\x1b[32m[DGM Evolution Completed]\x1b[0m');
384
- process.exit(0);
385
- }
386
- catch (err) {
387
- console.error('\n\x1b[31m[DGM Evolution Failed]:\x1b[0m', err.message);
388
- process.exit(1);
389
- }
390
- }
391
- // Direct command execution
392
- const task = args.join(' ');
393
- try {
394
- console.log(`Running direct task: "${task}" (CodeAct=${codeactMode})`);
395
- const engine = new autogenesis_1.AutogenesisEngine();
396
- engine.setEffort(effort);
397
- engine.codeactMode = codeactMode;
398
- await engine.runEvolutionStep(task);
399
- console.log('\n\x1b[32m[Evolution Step Completed]\x1b[0m');
400
- process.exit(0);
401
- }
402
- catch (err) {
403
- console.error('\n\x1b[31m[Evolution Failed]:\x1b[0m', err.message);
404
- process.exit(1);
405
- }
334
+ console.log(`Unknown option: ${args[0]}. Running interactive session...`);
335
+ await startInteractiveCLI(effort, codeactMode);
406
336
  }
407
337
  else {
408
338
  // Start interactive session
package/package.json CHANGED
@@ -1,17 +1,11 @@
1
1
  {
2
2
  "name": "closed-loop-cli",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Self-Developing Multi-Agent CLI Coding Assistant",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
7
7
  "closed-loop": "dist/index.js"
8
8
  },
9
- "files": [
10
- "dist",
11
- "src",
12
- "README.md",
13
- "docs"
14
- ],
15
9
  "type": "commonjs",
16
10
  "scripts": {
17
11
  "build": "tsc",