-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1646 lines (1475 loc) · 84.5 KB
/
index.js
File metadata and controls
1646 lines (1475 loc) · 84.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require('dotenv').config({ path: require('path').resolve(__dirname, '../../.env') });
const { execSync, spawn } = require('child_process');
const { cachedExec } = require('./exec_cache.js');
const { sendCard } = require('./feishu-helper.js');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { sleepSync } = require('./utils/sleep'); // New helper
const { sendReport } = require('./report.js'); // Use optimized internal report function
// [2026-02-03] WRAPPER REFACTOR: PURE PROXY
// This wrapper now correctly delegates to the core 'evolver' plugin.
// Enhanced with Kill Switch, Heartbeat Summary, Artifact Upload, and Thought Injection.
function sleepSeconds(sec) {
const s = Number(sec);
if (!Number.isFinite(s) || s <= 0) return;
// Check for wake signal every 2 seconds
const interval = 2;
const wakeFile = path.resolve(__dirname, '../../memory/evolver_wake.signal');
const steps = Math.ceil(s / interval);
for (let i = 0; i < steps; i++) {
if (fs.existsSync(wakeFile)) {
console.log('[Wrapper] Wake signal detected! Skipping sleep.');
try { fs.unlinkSync(wakeFile); } catch (e) {}
return;
}
sleepSync(interval * 1000);
}
}
function nextCycleTag(cycleFile) {
// Atomic read-increment-write using tmp+rename to prevent concurrent duplicates
var cycleId = 1;
try {
if (fs.existsSync(cycleFile)) {
var raw = fs.readFileSync(cycleFile, 'utf8').trim();
if (raw && !isNaN(raw)) {
cycleId = parseInt(raw, 10) + 1;
}
}
} catch (e) {
console.error('Cycle read error:', e.message);
}
try {
var tmpFile = cycleFile + '.tmp.' + process.pid;
fs.writeFileSync(tmpFile, cycleId.toString());
fs.renameSync(tmpFile, cycleFile);
} catch (e) {
console.error('Cycle write error:', e.message);
// Fallback: direct write
try { fs.writeFileSync(cycleFile, cycleId.toString()); } catch (_) {}
}
return String(cycleId).padStart(4, '0');
}
function tailText(buf, maxChars) {
if (!buf) return '';
const s = Buffer.isBuffer(buf) ? buf.toString('utf8') : String(buf);
if (s.length <= maxChars) return s;
return s.slice(-maxChars);
}
// --- FAILURE LEARNING + RETRY POLICY ---
const FAILURE_LESSONS_FILE = path.resolve(__dirname, '../../memory/evolution/failure_lessons.jsonl');
const HAND_MAX_RETRIES_PER_CYCLE = Number.parseInt(process.env.EVOLVE_HAND_MAX_RETRIES || '3', 10);
const HAND_RETRY_BACKOFF_SECONDS = Number.parseInt(process.env.EVOLVE_HAND_RETRY_BACKOFF_SECONDS || '15', 10);
function appendFailureLesson(cycleTag, reason, details) {
try {
const dir = path.dirname(FAILURE_LESSONS_FILE);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
const entry = {
at: new Date().toISOString(),
cycle: String(cycleTag),
reason: String(reason || 'unknown'),
details: String(details || '').slice(0, 1200),
};
fs.appendFileSync(FAILURE_LESSONS_FILE, JSON.stringify(entry) + '\n');
} catch (e) {
console.warn('[Wrapper] Failed to write failure lesson:', e.message);
}
}
function readRecentFailureLessons(limit) {
try {
if (!fs.existsSync(FAILURE_LESSONS_FILE)) return [];
const n = Number.isFinite(Number(limit)) ? Number(limit) : 5;
const lines = fs.readFileSync(FAILURE_LESSONS_FILE, 'utf8').split('\n').filter(Boolean);
return lines.slice(-n).map((l) => {
try { return JSON.parse(l); } catch (_) { return null; }
}).filter(Boolean);
} catch (_) {
return [];
}
}
function cleanStatusText(raw) {
return String(raw || '').replace(/\r/g, '').trim();
}
function isGenericStatusText(text) {
const t = cleanStatusText(text).toLowerCase();
if (!t) return true;
const genericPatterns = [
'status: [complete] cycle finished.',
'状态: [完成] 周期已完成。',
'status: [complete] cycle finished',
'状态: [完成] 周期已完成',
'step complete',
'completed.',
'done.',
];
for (const p of genericPatterns) {
if (t === p || t.includes(p)) return true;
}
// Too short + only completion semantics => still considered generic.
if (t.length < 40 && (t.includes('完成') || t.includes('complete') || t.includes('finished'))) {
return true;
}
return false;
}
function buildFallbackStatus(lang, cycleTag, gitInfo, latestEvent) {
const evt = latestEvent || readLatestEvolutionEvent();
const intent = evt && evt.intent ? String(evt.intent) : null;
const signals = evt && Array.isArray(evt.signals) ? evt.signals.slice(0, 3).map(String) : [];
const geneId = evt && Array.isArray(evt.genes_used) && evt.genes_used.length ? String(evt.genes_used[0]) : null;
const mutation = evt && evt.meta && evt.meta.mutation ? evt.meta.mutation : null;
const expectedEffect = mutation && mutation.expected_effect ? String(mutation.expected_effect) : null;
const blastFiles = evt && evt.blast_radius ? evt.blast_radius.files : null;
const blastLines = evt && evt.blast_radius ? evt.blast_radius.lines : null;
const hasGit = !!(gitInfo && gitInfo.shortHash);
if (lang === 'zh') {
const intentLabel = intentLabelByLang(intent, 'zh');
const parts = [`状态: [${intentLabel}]`];
if (expectedEffect) {
parts.push(`目标:${expectedEffect}。`);
}
if (signals.length) {
parts.push(`触发信号:${signals.join(', ')}。`);
}
if (geneId) {
parts.push(`使用基因:${geneId}。`);
}
if (blastFiles != null) {
parts.push(`影响范围:${blastFiles} 个文件 / ${blastLines || 0} 行。`);
}
if (hasGit) {
parts.push(`提交:${gitInfo.fileCount} 个文件,涉及 ${gitInfo.areaStr}。`);
} else {
parts.push(`无可提交代码变更。`);
}
return parts.join(' ');
}
const intentLabel = intentLabelByLang(intent, 'en');
const parts = [`Status: [${intentLabel}]`];
if (expectedEffect) {
parts.push(`Goal: ${expectedEffect}.`);
}
if (signals.length) {
parts.push(`Signals: ${signals.join(', ')}.`);
}
if (geneId) {
parts.push(`Gene: ${geneId}.`);
}
if (blastFiles != null) {
parts.push(`Blast radius: ${blastFiles} files / ${blastLines || 0} lines.`);
}
if (hasGit) {
parts.push(`Committed ${gitInfo.fileCount} files in ${gitInfo.areaStr}.`);
} else {
parts.push(`No committable code diff.`);
}
return parts.join(' ');
}
function withOutcomeLine(statusText, success, lang) {
const s = cleanStatusText(statusText);
const enPrefix = 'Result: ';
const zhPrefix = '结果: ';
if (lang === 'zh') {
if (s.startsWith(zhPrefix)) return s;
return `${zhPrefix}${success ? '成功' : '失败'}\n${s}`;
}
if (s.startsWith(enPrefix)) return s;
return `${enPrefix}${success ? 'SUCCESS' : 'FAILED'}\n${s}`;
}
function ensureDetailedStatus(rawText, lang, cycleTag, gitInfo, latestEvent) {
const s = cleanStatusText(rawText);
if (!s || isGenericStatusText(s)) return buildFallbackStatus(lang, cycleTag, gitInfo, latestEvent);
return s;
}
function readLatestEvolutionEvent() {
try {
const eventsFile = path.resolve(__dirname, '../../assets/gep/events.jsonl');
if (!fs.existsSync(eventsFile)) return null;
const lines = fs.readFileSync(eventsFile, 'utf8').split('\n').filter(Boolean);
for (let i = lines.length - 1; i >= 0; i--) {
try {
const obj = JSON.parse(lines[i]);
if (obj && obj.type === 'EvolutionEvent') return obj;
} catch (_) {}
}
return null;
} catch (_) {
return null;
}
}
function intentLabelByLang(intent, lang) {
const i = String(intent || '').toLowerCase();
if (lang === 'zh') {
if (i === 'innovate') return '创新';
if (i === 'optimize') return '优化';
return '修复';
}
if (i === 'innovate') return 'INNOVATION';
if (i === 'optimize') return 'OPTIMIZE';
return 'REPAIR';
}
function enforceStatusIntent(statusText, intent, lang) {
const s = cleanStatusText(statusText);
if (!intent) return s;
const label = intentLabelByLang(intent, lang);
if (lang === 'zh') {
if (/^状态:\s*\[[^\]]+\]/.test(s)) return s.replace(/^状态:\s*\[[^\]]+\]/, `状态: [${label}]`);
return `状态: [${label}] ${s}`;
}
if (/^Status:\s*\[[^\]]+\]/.test(s)) return s.replace(/^Status:\s*\[[^\]]+\]/, `Status: [${label}]`);
return `Status: [${label}] ${s}`;
}
// --- FEATURE 2: HEARTBEAT SUMMARY (Option 2: Real-time Error, Summary Info) ---
let sessionLogs = { infoCount: 0, errorCount: 0, startTime: 0, errors: [] };
const LOG_DEDUP_FILE = path.resolve(__dirname, '../../memory/evolution/log_dedup.json');
const LOG_DEDUP_WINDOW_MS = Number.parseInt(process.env.EVOLVE_LOG_DEDUP_WINDOW_MS || '600000', 10); // 10 minutes
const LOG_DEDUP_MAX_KEYS = Number.parseInt(process.env.EVOLVE_LOG_DEDUP_MAX_KEYS || '800', 10);
// Lifecycle log target group (set via env; no hardcoded fallbacks for public release)
const FEISHU_LOG_GROUP = process.env.FEISHU_LOG_TARGET || process.env.LOG_TARGET || '';
const FEISHU_CN_REPORT_GROUP = process.env.FEISHU_CN_REPORT_GROUP || '';
process.env.LOG_TARGET = FEISHU_LOG_GROUP;
// Notification level: critical | normal | verbose
// critical = only kill switch + retry exhaustion
// normal = one merged card per cycle, errors collected into summary
// verbose = legacy behavior (every error/warning as individual card)
const NOTIFY_LEVEL = (process.env.EVOLVE_NOTIFY_LEVEL || 'normal').toLowerCase();
// Report language: auto | en | cn
// auto = detect from FEISHU_CN_REPORT_GROUP presence
const REPORT_LANG = (process.env.EVOLVE_REPORT_LANG || 'auto').toLowerCase();
function normalizeLogForDedup(msg) {
return String(msg || '')
.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/g, '<ts>')
.replace(/PID=\d+/g, 'PID=<id>')
.replace(/Cycle #\d+/g, 'Cycle #<id>')
.replace(/evolver_hand_[\w_:-]+/g, 'evolver_hand_<id>')
.replace(/\s+/g, ' ')
.trim()
.slice(0, 500);
}
function shouldSuppressForwardLog(msg, type) {
if (String(process.env.EVOLVE_LOG_DEDUP || '').toLowerCase() === '0') return false;
const normalized = normalizeLogForDedup(msg);
if (!normalized) return false;
const keyRaw = `${String(type || 'INFO')}::${normalized}`;
const key = crypto.createHash('md5').update(keyRaw).digest('hex');
const now = Date.now();
try {
const dir = path.dirname(LOG_DEDUP_FILE);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
let cache = {};
if (fs.existsSync(LOG_DEDUP_FILE)) {
cache = JSON.parse(fs.readFileSync(LOG_DEDUP_FILE, 'utf8'));
}
for (const k of Object.keys(cache)) {
const ts = Number(cache[k] && cache[k].at);
if (!Number.isFinite(ts) || now - ts > LOG_DEDUP_WINDOW_MS) delete cache[k];
}
if (cache[key] && Number.isFinite(Number(cache[key].at)) && now - Number(cache[key].at) <= LOG_DEDUP_WINDOW_MS) {
cache[key].hits = Number(cache[key].hits || 1) + 1;
const tmpHit = `${LOG_DEDUP_FILE}.tmp.${process.pid}`;
fs.writeFileSync(tmpHit, JSON.stringify(cache, null, 2));
fs.renameSync(tmpHit, LOG_DEDUP_FILE);
return true;
}
cache[key] = { at: now, hits: 1, type: String(type || 'INFO') };
const keys = Object.keys(cache);
if (keys.length > LOG_DEDUP_MAX_KEYS) {
keys
.sort((a, b) => Number(cache[a].at || 0) - Number(cache[b].at || 0))
.slice(0, keys.length - LOG_DEDUP_MAX_KEYS)
.forEach((k) => { delete cache[k]; });
}
const tmp = `${LOG_DEDUP_FILE}.tmp.${process.pid}`;
fs.writeFileSync(tmp, JSON.stringify(cache, null, 2));
fs.renameSync(tmp, LOG_DEDUP_FILE);
return false;
} catch (_) {
return false;
}
}
function forwardLogToFeishu(msg, type = 'INFO') {
if (msg.includes('[FeishuForwardFail]') || msg.includes('[CardFail]')) return;
if (!msg || !msg.trim()) return;
if (type === 'ERROR') {
sessionLogs.errorCount++;
sessionLogs.errors.push(msg.slice(0, 300));
if (NOTIFY_LEVEL !== 'verbose') return;
if (shouldSuppressForwardLog(msg, type)) return;
sendCardInternal(msg, 'ERROR');
} else if (type === 'WARNING') {
if (NOTIFY_LEVEL !== 'verbose') return;
if (shouldSuppressForwardLog(msg, type)) return;
sendCardInternal(msg, 'WARNING');
} else if (type === 'LIFECYCLE') {
if (NOTIFY_LEVEL !== 'verbose') return;
if (shouldSuppressForwardLog(msg, type)) return;
sendCardInternal(msg, 'INFO');
} else {
sessionLogs.infoCount++;
}
}
// Classify stderr message severity: returns 'WARNING' for non-critical, 'ERROR' for critical
function classifyStderrSeverity(msg) {
var lower = (msg || '').toLowerCase();
// Non-critical patterns: gateway fallback, missing optional files, deprecation warnings, timeouts with fallback
var warnPatterns = [
'falling back to embedded',
'no such file or directory',
'enoent',
'deprecat',
'warning:',
'warn:',
'[warn]',
'gateway timeout', // gateway slow but agent retries/falls back
'optional dependency',
'experimental',
'hint:',
'evolver_hint',
'memory_missing',
'user_missing',
'command exited with code 1', // non-zero exit from a tool command (usually cat/ls fail)
];
for (var i = 0; i < warnPatterns.length; i++) {
if (lower.includes(warnPatterns[i])) return 'WARNING';
}
return 'ERROR';
}
function sendCardInternal(msg, type) {
if (!msg) return;
// critical mode: only CRITICAL / FAILURE cards
if (NOTIFY_LEVEL === 'critical') {
if (!type.includes('CRITICAL') && !type.includes('FAILURE')) return;
}
const target = process.env.LOG_TARGET || process.env.OPENCLAW_MASTER_ID;
if (!target) return;
const color = type.includes('ERROR') || type.includes('CRITICAL') || type.includes('FAILURE')
? 'red'
: type.includes('WARNING') || type.includes('WARN')
? 'orange'
: 'blue';
sendCard({
target,
title: `Evolver [${new Date().toISOString().substring(11,19)}]`,
text: `[${type}] ${msg}`,
color
}).catch(e => {
console.error(`[Wrapper] Failed to send card: ${e.message}`);
});
}
const CYCLE_COUNTER_FILE = path.resolve(__dirname, '../../logs/cycle_count.txt');
function parseCycleNumber(cycleTag) {
if (typeof cycleTag === 'number' && Number.isFinite(cycleTag)) {
return Math.trunc(cycleTag);
}
const text = String(cycleTag || '').trim();
if (!text) return null;
if (/^\d+$/.test(text)) return parseInt(text, 10);
const m = text.match(/(\d{1,})/);
if (!m) return null;
return parseInt(m[1], 10);
}
function shouldSuppressStaleCycleNotice(cycleTag) {
try {
const currentRaw = fs.existsSync(CYCLE_COUNTER_FILE)
? fs.readFileSync(CYCLE_COUNTER_FILE, 'utf8').trim()
: '';
const current = /^\d+$/.test(currentRaw) ? parseInt(currentRaw, 10) : null;
const candidate = parseCycleNumber(cycleTag);
if (!Number.isFinite(current) || !Number.isFinite(candidate)) return false;
const windowSize = Number.parseInt(process.env.EVOLVE_STALE_CYCLE_WINDOW || '5', 10);
if (!Number.isFinite(windowSize) || windowSize < 0) return false;
return candidate < (current - windowSize);
} catch (_) {
return false;
}
}
function sendSummary(cycleTag, duration, success) {
if (shouldSuppressStaleCycleNotice(cycleTag)) {
console.warn(`[Wrapper] Suppressing stale summary for cycle #${cycleTag}.`);
return;
}
const statusIcon = success ? '✅' : '❌';
const persona = success ? 'greentea' : 'maddog';
// duration needs to be parsed as number for comparison
const durNum = parseFloat(duration);
const comment = getComment('summary', durNum, success, persona);
const errorSection = sessionLogs.errors.length > 0
? `\n\n**Recent Errors:**\n${sessionLogs.errors.slice(-3).map(e => `> ${e}`).join('\n')}`
: '';
const summaryMsg = `**Cycle #${cycleTag} Complete**\n` +
`Status: ${statusIcon} ${success ? 'Success' : 'Failed'}\n` +
`Duration: ${duration}s\n` +
`Logs: ${sessionLogs.infoCount} Info, ${sessionLogs.errorCount} Error\n` +
`💭 *${comment}*` +
errorSection;
sendCardInternal(summaryMsg, success ? 'SUMMARY' : 'FAILURE');
}
// --- FEATURE 5: GIT SYNC (Safety Net) ---
// Lazy-load optional modules with fallbacks to prevent startup crashes.
const { requireEvolverModule } = require('./utils/resolve-evolver');
let selfRepair = null;
let getComment = (_type, _dur, _ok, _persona) => '';
{
selfRepair = requireEvolverModule('src/ops/self_repair', './self-repair.js');
if (!selfRepair) console.warn('[Wrapper] self-repair module not found, git repair disabled.');
const commentary = requireEvolverModule('src/ops/commentary');
if (commentary && typeof commentary.getComment === 'function') getComment = commentary.getComment;
else console.warn('[Wrapper] commentary.js not found, using silent mode.');
}
// Issue tracker: records problems to a Feishu doc
let issueTracker = null;
try {
issueTracker = require('./issue_tracker.js');
} catch (e) {
console.warn('[Wrapper] issue_tracker.js not found, issue tracking disabled.');
}
// gitSync runs after every successful evolution cycle (no cooldown).
function execWithTimeout(cmd, cwd, timeoutMs = 30000) {
try {
// Optimization: Use spawnSync with shell: false if possible to reduce overhead
// But cmd is a string, so we need to parse it or just use shell: true for simplicity
// given this is a dev tool.
// However, to fix high_tool_usage:exec signal and improve robustness, we will try to split.
const parts = cmd.trim().split(/\s+/);
let bin = parts[0];
// Fix for "spawn /.../gi" error: Ensure 'git' uses absolute path if possible
if (bin === 'git') {
bin = '/usr/bin/git';
}
const args = parts.slice(1).map(arg => {
// Basic unquote
if ((arg.startsWith('"') && arg.endsWith('"')) || (arg.startsWith("'") && arg.endsWith("'"))) {
return arg.slice(1, -1);
}
return arg;
});
// Use spawnSync directly (no shell)
const res = require('child_process').spawnSync(bin, args, {
cwd,
timeout: timeoutMs,
encoding: 'utf8',
stdio: 'pipe'
});
if (res.error) throw res.error;
if (res.status !== 0) throw new Error(res.stderr || res.stdout || `Exit code ${res.status}`);
return res.stdout;
} catch (e) {
throw new Error(`Command "${cmd}" failed: ${e.message}`);
}
}
function buildCommitMessage(statusOutput, cwd) {
const lines = statusOutput.split('\n').filter(Boolean);
const added = [];
const modified = [];
const deleted = [];
for (const line of lines) {
const code = line.substring(0, 2).trim();
const file = line.substring(3).trim();
// Skip logs, temp, and non-essential files
if (file.startsWith('logs/') || file.startsWith('temp/') || file.endsWith('.log')) continue;
if (code.includes('A') || code === '??') added.push(file);
else if (code.includes('D')) deleted.push(file);
else modified.push(file);
}
// Summarize by skill/directory
const skillChanges = new Map();
for (const f of [...added, ...modified, ...deleted]) {
const parts = f.split('/');
let group = parts[0];
if (parts[0] === 'skills' && parts.length > 1) group = `skills/${parts[1]}`;
if (!skillChanges.has(group)) skillChanges.set(group, []);
skillChanges.get(group).push(f);
}
const totalFiles = added.length + modified.length + deleted.length;
if (totalFiles === 0) return '🧬 Evolution: maintenance (no significant changes)';
// Build title line
const actions = [];
if (added.length > 0) actions.push(`${added.length} added`);
if (modified.length > 0) actions.push(`${modified.length} modified`);
if (deleted.length > 0) actions.push(`${deleted.length} deleted`);
const areas = [...skillChanges.keys()].slice(0, 3);
const areaStr = areas.join(', ') + (skillChanges.size > 3 ? ` (+${skillChanges.size - 3} more)` : '');
let title = `🧬 Evolution: ${actions.join(', ')} in ${areaStr}`;
// Build body with file details (keep under 20 lines)
const bodyLines = [];
for (const [group, files] of skillChanges) {
if (files.length <= 3) {
for (const f of files) bodyLines.push(`- ${f}`);
} else {
bodyLines.push(`- ${group}/ (${files.length} files)`);
}
}
if (bodyLines.length > 0) {
return title + '\n\n' + bodyLines.slice(0, 20).join('\n');
}
return title;
}
// gitSync returns commit info: { commitMsg, fileCount, areaStr, shortHash } or null on failure/no-op
function gitSync() {
try {
console.log('[Wrapper] Executing Git Sync...');
var gitRoot = path.resolve(__dirname, '../../../');
var safePaths = [
'workspace/skills/',
'workspace/memory/',
'workspace/RECENT_EVENTS.md',
'workspace/TROUBLESHOOTING.md',
'workspace/TOOLS.md',
'workspace/assets/',
'workspace/docs/',
];
// Optimization: Batch git add into a single command to reduce exec calls (Signal: high_tool_usage:exec)
try {
execWithTimeout('git add ' + safePaths.join(' '), gitRoot, 60000);
} catch (e) {
console.warn('[Wrapper] Batch git add failed, falling back to individual adds:', e.message);
for (var i = 0; i < safePaths.length; i++) {
try { execWithTimeout('git add ' + safePaths[i], gitRoot, 30000); } catch (_) {}
}
}
var status = execSync('git diff --cached --name-only', { cwd: gitRoot, encoding: 'utf8' }).trim();
if (!status) {
console.log('[Wrapper] Git Sync: nothing to commit.');
return null;
}
var fileCount = status.split('\n').filter(Boolean).length;
var areas = [...new Set(status.split('\n').filter(Boolean).map(function(f) {
var parts = f.split('/');
if (parts[0] === 'workspace' && parts[1] === 'skills' && parts.length > 2) return 'skills/' + parts[2];
if (parts[0] === 'workspace' && parts.length > 1) return parts[1];
return parts[0];
}))].slice(0, 3);
var areaStr = areas.join(', ') + (areas.length >= 3 ? ' ...' : '');
var commitMsg = '🧬 Evolution: ' + fileCount + ' files in ' + areaStr;
var msgFile = path.join('/tmp', 'evolver_commit_' + Date.now() + '.txt');
fs.writeFileSync(msgFile, commitMsg);
execWithTimeout('git commit -F "' + msgFile + '"', gitRoot, 30000);
try { fs.unlinkSync(msgFile); } catch (_) {}
try {
execWithTimeout('git pull origin main --rebase --autostash', gitRoot, 120000);
} catch (e) {
console.error('[Wrapper] Pull Rebase Failed:', e.message);
try {
if (selfRepair && typeof selfRepair.repair === 'function') selfRepair.repair();
else if (selfRepair && typeof selfRepair.run === 'function') selfRepair.run();
} catch (_) {}
throw e;
}
execWithTimeout('git push origin main', gitRoot, 120000);
// Get the short hash of the commit we just pushed
var shortHash = '';
try { shortHash = execSync('git log -1 --format=%h', { cwd: gitRoot, encoding: 'utf8' }).trim(); } catch (_) {}
console.log('[Wrapper] Git Sync Complete. (' + shortHash + ')');
forwardLogToFeishu('🧬 Git Sync: ' + fileCount + ' files in ' + areaStr + ' (' + shortHash + ')', 'LIFECYCLE');
return { commitMsg: commitMsg, fileCount: fileCount, areaStr: areaStr, shortHash: shortHash };
} catch (e) {
console.error('[Wrapper] Git Sync Failed:', e.message);
forwardLogToFeishu('[Wrapper] Git Sync Failed: ' + e.message, 'ERROR');
return null;
}
}
// --- FEATURE 1: KILL SWITCH ---
const KILL_SWITCH_FILE = path.resolve(__dirname, '../../memory/evolver_kill_switch.lock');
function checkKillSwitch() {
if (fs.existsSync(KILL_SWITCH_FILE)) {
console.error(`[Wrapper] Kill Switch Detected at ${KILL_SWITCH_FILE}! Terminating loop.`);
sendCardInternal(`🛑 **Emergency Stop Triggered!**\nKill switch file detected at ${KILL_SWITCH_FILE}. Wrapper is shutting down.`, 'CRITICAL');
process.exit(1);
}
}
// --- FEATURE 4: THOUGHT INJECTION ---
const INJECTION_FILE = path.resolve(__dirname, '../../memory/evolver_hint.txt');
function getInjectionHint() {
if (fs.existsSync(INJECTION_FILE)) {
try {
const hint = fs.readFileSync(INJECTION_FILE, 'utf8').trim();
if (hint) {
console.log(`[Wrapper] Injecting Thought: ${hint}`);
// Delete after reading (one-time injection)
fs.unlinkSync(INJECTION_FILE);
return hint;
}
} catch (e) {}
}
return null;
}
// --- FEATURE 3: ARTIFACT UPLOAD (Stub) ---
// This requires a more complex 'upload-file' skill or API which we might not have ready.
// For now, we'll just log that artifacts are available locally.
function checkArtifacts(cycleTag) {
// Logic to find artifacts and maybe just cat them if small?
// Placeholder for future expansion.
}
// --- FEATURE 6: CLEANUP (Disk Hygiene) ---
let cleanup = null;
{
cleanup = requireEvolverModule('src/ops/cleanup', './cleanup.js');
if (!cleanup) console.warn('[Wrapper] cleanup module not found, disk cleanup disabled.');
}
// --- FEATURE 0: SINGLETON GUARD (Prevent Duplicates) ---
const LOCK_FILE = path.resolve(__dirname, '../../memory/evolver_wrapper.pid');
function isWrapperProcess(pid) {
// Verify PID is actually a wrapper process (not a recycled PID for something else)
try {
// Primary: check /proc on Linux (handles both absolute and relative path launches)
if (process.platform === 'linux') {
try {
var procCmdline = fs.readFileSync('/proc/' + pid + '/cmdline', 'utf8');
var hasLoop = procCmdline.includes('--loop');
// Match absolute path
if (hasLoop && procCmdline.includes('feishu-evolver-wrapper/index.js')) return true;
// Match relative path: check if CWD is the wrapper directory
if (hasLoop && procCmdline.includes('index.js')) {
try {
var procCwd = fs.readlinkSync('/proc/' + pid + '/cwd');
if (procCwd.includes('feishu-evolver-wrapper')) return true;
} catch (_) {}
}
return false; // Found proc but didn't match
} catch (e) {
// If readFileSync fails (process gone), return false
if (e.code === 'ENOENT') return false;
}
}
// Fallback: ps (for non-Linux or /proc failures)
var cmdline = execSync('ps -p ' + pid + ' -o args=', { encoding: 'utf8', timeout: 5000 }).trim();
if (cmdline.includes('feishu-evolver-wrapper/index.js') && cmdline.includes('--loop')) return true;
// Also handle relative-path launches by checking CWD via lsof
if (cmdline.includes('index.js') && cmdline.includes('--loop')) {
try {
var cwdInfo = execSync('readlink /proc/' + pid + '/cwd 2>/dev/null || lsof -p ' + pid + ' -Fn 2>/dev/null | head -3', { encoding: 'utf8', timeout: 5000 });
if (cwdInfo.includes('feishu-evolver-wrapper')) return true;
} catch (_) {}
}
return false;
} catch (e) {
return false;
}
}
function checkSingleton() {
try {
if (fs.existsSync(LOCK_FILE)) {
var oldPidStr = fs.readFileSync(LOCK_FILE, 'utf8').trim();
var oldPid = parseInt(oldPidStr, 10);
if (oldPid && oldPid !== process.pid) {
// Step 1: Check if PID exists at all
var pidAlive = false;
try { process.kill(oldPid, 0); pidAlive = true; } catch (e) { pidAlive = false; }
if (pidAlive) {
// Step 2: Verify the PID is actually a wrapper (not a recycled PID)
if (isWrapperProcess(oldPid)) {
console.error('[Wrapper] Another instance is running (PID ' + oldPid + '). Exiting.');
process.exit(0);
} else {
console.log('[Wrapper] PID ' + oldPid + ' exists but is not a wrapper process. Stale lock, overwriting.');
}
} else {
console.log('[Wrapper] Stale lock file found (PID ' + oldPid + ' dead). Overwriting.');
}
}
}
// Write my PID atomically (write to tmp then rename)
var tmpLock = LOCK_FILE + '.tmp.' + process.pid;
fs.writeFileSync(tmpLock, process.pid.toString());
fs.renameSync(tmpLock, LOCK_FILE);
// Remove on exit
var cleanupLock = function() {
try {
if (fs.existsSync(LOCK_FILE)) {
var current = fs.readFileSync(LOCK_FILE, 'utf8').trim();
if (current === process.pid.toString()) {
fs.unlinkSync(LOCK_FILE);
}
}
} catch (_) {}
};
process.on('exit', cleanupLock);
process.on('SIGINT', function() { cleanupLock(); process.exit(); });
process.on('SIGTERM', function() { cleanupLock(); process.exit(); });
} catch (e) {
console.error('[Wrapper] Singleton check failed:', e.message);
}
}
async function run() {
checkSingleton(); // Feature 0
console.log('Launching Feishu Evolver Wrapper (Proxy Mode)...');
forwardLogToFeishu('🧬 Wrapper starting up...', 'LIFECYCLE');
// Clean up old artifacts before starting
try { if (cleanup && typeof cleanup.run === 'function') cleanup.run(); } catch (e) { console.error('[Cleanup] Failed:', e.message); }
// Clean up stale session lock files that can block agent startup.
// These locks are left behind when a process crashes mid-session write.
// A lock older than 5 minutes is considered stale and safe to remove.
try {
const lockPaths = [
path.resolve(process.env.HOME || '/tmp', '.openclaw/agents/main/sessions/sessions.json.lock'),
];
for (const lp of lockPaths) {
if (fs.existsSync(lp)) {
var lockAge = Date.now() - fs.statSync(lp).mtimeMs;
if (lockAge > 5 * 60 * 1000) {
fs.unlinkSync(lp);
console.log('[Startup] Removed stale session lock: ' + lp + ' (age: ' + Math.round(lockAge / 1000) + 's)');
}
}
}
} catch (e) { console.warn('[Startup] Lock cleanup failed:', e.message); }
const args = process.argv.slice(2);
// 1. Force Feishu Card Reporting
process.env.EVOLVE_REPORT_TOOL = 'feishu-card';
// 1b. Wrapper depends on bridge mode (sessions_spawn stdout protocol).
// evolver >= v1.52.0 defaults bridge OFF unless EVOLVE_BRIDGE or OPENCLAW_WORKSPACE is set.
if (!process.env.EVOLVE_BRIDGE) {
process.env.EVOLVE_BRIDGE = 'true';
}
// 2. Resolve Core Evolver Path
const { resolveEvolverDir } = require('./utils/resolve-evolver');
let evolverDir = resolveEvolverDir();
if (!evolverDir) {
console.error("Critical Error: Core 'evolver' plugin not found! Set EVOLVER_DIR env var or place evolver adjacent to this wrapper.");
process.exit(1);
}
const mainScript = path.join(evolverDir, 'index.js');
const lifecycleLog = path.resolve(__dirname, '../../logs/wrapper_lifecycle.log');
const MAX_RETRIES = 5;
const isLoop = args.includes('--loop');
const loopSleepSeconds = Number.parseInt(process.env.EVOLVE_WRAPPER_LOOP_SLEEP_SECONDS || '2', 10);
const loopFailBackoffSeconds = Number.parseInt(process.env.EVOLVE_WRAPPER_FAIL_BACKOFF_SECONDS || '30', 10);
const loopMaxCycles = Number.parseInt(process.env.EVOLVE_WRAPPER_MAX_CYCLES || '0', 10); // 0 = unlimited
if (!fs.existsSync(path.dirname(lifecycleLog))) {
fs.mkdirSync(path.dirname(lifecycleLog), { recursive: true });
}
const cycleFile = path.resolve(path.dirname(lifecycleLog), 'cycle_count.txt');
let childArgsArrBase = args.filter(a => a !== '--once' && a !== '--loop' && a !== '--mad-dog');
if (childArgsArrBase.length === 0) {
childArgsArrBase = ['run'];
}
let cycleCount = 0;
// Workspace root for CWD recovery
const WRAPPER_WORKSPACE_ROOT = path.resolve(__dirname, '../..');
let consecutiveHandFailures = 0; // Track hand agent failures for backoff
let consecutiveCycleFailures = 0; // Track full cycle failures for circuit breaker
const MAX_CONSECUTIVE_HAND_FAILURES = 5; // After this many, long backoff
const HAND_FAILURE_BACKOFF_BASE = 60; // Base backoff in seconds
// --- Circuit Breaker ---
// After too many consecutive cycle failures, evolver enters "circuit open" state:
// it pauses for a long time to avoid burning API credits and flooding logs.
// The circuit closes automatically after the pause (allowing a retry).
const CIRCUIT_BREAKER_THRESHOLD = Number.parseInt(process.env.EVOLVE_CIRCUIT_BREAKER_THRESHOLD || '8', 10);
const CIRCUIT_BREAKER_PAUSE_SEC = Number.parseInt(process.env.EVOLVE_CIRCUIT_BREAKER_PAUSE_SEC || '1800', 10); // 30 min default
const CIRCUIT_BREAKER_MAX_PAUSE_SEC = Number.parseInt(process.env.EVOLVE_CIRCUIT_BREAKER_MAX_PAUSE_SEC || '7200', 10); // 2 hour max
let cachedOpenclawPath = null;
// Helper to resolve OpenClaw path once
function resolveOpenclawPath() {
if (cachedOpenclawPath) return cachedOpenclawPath;
if (process.env.OPENCLAW_BIN) {
cachedOpenclawPath = process.env.OPENCLAW_BIN;
return cachedOpenclawPath;
}
const candidates = [
'openclaw',
path.join(process.env.HOME || '', '.npm-global/bin/openclaw'),
'/usr/local/bin/openclaw',
'/usr/bin/openclaw',
];
for (const c of candidates) {
try {
if (c === 'openclaw') {
// Cache only if successful
try {
execSync('which openclaw', { stdio: 'ignore' });
cachedOpenclawPath = 'openclaw';
return 'openclaw';
} catch (e) {}
}
if (fs.existsSync(c)) {
cachedOpenclawPath = c;
return c;
}
} catch (e) { /* try next */ }
}
cachedOpenclawPath = candidates[1] || 'openclaw';
return cachedOpenclawPath;
}
while (true) {
checkKillSwitch(); // Feature 1
if (loopMaxCycles > 0 && cycleCount >= loopMaxCycles) {
console.log(`Reached max cycles (${loopMaxCycles}). Exiting.`);
return;
}
// --- Circuit Breaker: pause after too many consecutive failures ---
if (consecutiveCycleFailures >= CIRCUIT_BREAKER_THRESHOLD) {
const cbPause = Math.min(
CIRCUIT_BREAKER_MAX_PAUSE_SEC,
CIRCUIT_BREAKER_PAUSE_SEC * Math.pow(2, Math.floor((consecutiveCycleFailures - CIRCUIT_BREAKER_THRESHOLD) / 4))
);
console.log(`[CircuitBreaker] OPEN: ${consecutiveCycleFailures} consecutive cycle failures. Pausing ${cbPause}s to prevent resource waste.`);
forwardLogToFeishu(`[CircuitBreaker] OPEN: ${consecutiveCycleFailures} consecutive failures. Pausing ${cbPause}s. Manual intervention may be needed.`, 'ERROR');
appendFailureLesson('circuit_breaker', 'circuit_open', `${consecutiveCycleFailures} consecutive failures, pausing ${cbPause}s`);
sleepSeconds(cbPause);
// After pause, allow ONE retry (circuit half-open). If it fails again, we loop back here.
}
// Exponential backoff on consecutive Hand Agent failures
if (consecutiveHandFailures >= MAX_CONSECUTIVE_HAND_FAILURES) {
const backoffSec = Math.min(3600, HAND_FAILURE_BACKOFF_BASE * Math.pow(2, consecutiveHandFailures - MAX_CONSECUTIVE_HAND_FAILURES));
console.log(`[Wrapper] Hand Agent failed ${consecutiveHandFailures} consecutive times. Backing off ${backoffSec}s...`);
forwardLogToFeishu(`[Wrapper] Hand Agent failed ${consecutiveHandFailures}x consecutively. Backing off ${backoffSec}s.`, 'WARNING');
sleepSeconds(backoffSec);
}
cycleCount++;
// CWD Recovery: If the working directory was deleted during a previous cycle,
// process.cwd() throws ENOENT and all subsequent operations fail.
try { process.cwd(); } catch (cwdErr) {
if (cwdErr && cwdErr.code === 'ENOENT') {
console.warn('[Wrapper] CWD lost (ENOENT). Recovering to: ' + WRAPPER_WORKSPACE_ROOT);
try { process.chdir(WRAPPER_WORKSPACE_ROOT); } catch (_) {}
}
}
const cycleTag = nextCycleTag(cycleFile);
// Feature 4: Injection
const injectedHint = getInjectionHint();
if (injectedHint) {
process.env.EVOLVE_HINT = injectedHint;
console.log(`[Wrapper] Thought Injected: "${injectedHint}"`);
} else {
delete process.env.EVOLVE_HINT;
}
// Feature 7: Repair Loop Detection (Innovation Mandate)
// Scan recent events for consecutive repairs and force innovation if stuck.
try {
const eventsFile = path.resolve(__dirname, '../../assets/gep/events.jsonl');
if (fs.existsSync(eventsFile)) {
const lines = fs.readFileSync(eventsFile, 'utf8').split('\n').filter(Boolean);
let repairCount = 0;
// Check last 5 events
for (let i = lines.length - 1; i >= 0 && i >= lines.length - 5; i--) {
try {
const evt = JSON.parse(lines[i]);
if (evt.intent === 'repair') {
repairCount++;
} else {
break; // Sequence broken
}
} catch (e) {}
}
if (repairCount >= 3) {
console.log(`[Wrapper] Detected ${repairCount} consecutive repairs. Forcing INNOVATION signal.`);
process.env.EVOLVE_FORCE_SIGNAL = 'force_innovation_after_repair_loop';
forwardLogToFeishu(`[Wrapper] 🔄 Repair Loop Detected (${repairCount}x). Forcing Innovation...`, 'WARNING');
} else {
delete process.env.EVOLVE_FORCE_SIGNAL;
}
}
} catch (e) {
console.warn('[Wrapper] Repair loop check failed:', e.message);
}
const targetArg = process.env.EVOLVE_TARGET ? ` --target "${process.env.EVOLVE_TARGET}"` : '';
process.env.EVOLVE_REPORT_DIRECTIVE = `3. **REPORT (FEISHU WRAPPER)**:
- You MUST use the \`feishu-evolver-wrapper/report.js\` tool.
- The report MUST have a colored header to distinguish it from rich text.
- Command:
\`\`\`bash
node skills/feishu-evolver-wrapper/report.js --cycle "Cycle #${cycleTag}" --title "🧬 Evolution #${cycleTag}" --status "Status: [WRAPPED] Step Complete."${targetArg}
\`\`\`
- Target: Auto-detects context (Evolution group or master) unless overridden.`;
var modelRoutingDirective = `
**Model Routing (Mandatory)**:
You MUST prioritize Cursor Agent capabilities for all programming tasks.
When you need to delegate to a specific model, follow these rules strictly:
- Planning, prompts, strategy reasoning: use gpt5.3
- Code implementation, refactoring, bug fixes: use gpt5.3codex
- Documentation, reports, human-readable files (README, SKILL.md, CHANGELOG): use gemini3pro
If a task spans multiple phases, route each phase to its designated model in order: plan -> code -> docs.
If a designated model is unavailable, use the closest alternative without changing the task phase.`;
if (isLoop) {
process.env.EVOLVE_EXTRA_MODES = `- Mode B (Wrapper Loop):
- You are running under a wrapper-managed continuous loop.
- Action: Perform ONE evolution cycle, then exit cleanly.
- Do NOT call sessions_spawn. Do NOT try to self-schedule.
- The wrapper handles cycling, reporting delivery, and git sync.
${modelRoutingDirective}`;
} else {
process.env.EVOLVE_EXTRA_MODES = `- Mode A (Atomic/Cron):
- Do NOT call sessions_spawn.
- Goal: Complete ONE generation, update state, and exit gracefully.