-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.js
More file actions
483 lines (425 loc) · 18.9 KB
/
report.js
File metadata and controls
483 lines (425 loc) · 18.9 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
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const os = require('os');
const { program } = require('commander');
const { execSync } = require('child_process');
const { sendCard, sendStructuredCard, postCard } = require('./feishu-helper.js');
const { fetchWithAuth } = require('../feishu-common/index.js');
const { generateDashboardCard, formatUptime } = require('./utils/dashboard-generator.js');
const crypto = require('crypto');
// Check for integration key (tenant_access_token or webhook)
const integrationKey = process.env.FEISHU_APP_ID || process.env.FEISHU_BOT_NAME;
if (!integrationKey) {
console.warn('⚠️ Integration key missing (FEISHU_APP_ID). Reporting might fail or degrade to console only.');
// Don't exit, just warn - we might be in a test env
}
// --- REPORT DEDUP ---
const DEDUP_FILE = path.resolve(__dirname, '../../memory/report_dedup.json');
const DEDUP_WINDOW_MS = 30 * 60 * 1000; // 30 minutes
function isDuplicateReport(reportKey) {
if (process.env.EVOLVE_REPORT_DEDUP === '0') return false;
try {
var cache = {};
if (fs.existsSync(DEDUP_FILE)) {
cache = JSON.parse(fs.readFileSync(DEDUP_FILE, 'utf8'));
}
var now = Date.now();
// Prune old entries
for (var k in cache) {
if (now - cache[k] > DEDUP_WINDOW_MS) delete cache[k];
}
if (cache[reportKey]) {
console.log('[Wrapper] Report dedup: skipping duplicate report (' + reportKey.slice(0, 40) + '...)');
return true;
}
cache[reportKey] = now;
var tmpDedup = DEDUP_FILE + '.tmp.' + process.pid;
fs.writeFileSync(tmpDedup, JSON.stringify(cache, null, 2));
fs.renameSync(tmpDedup, DEDUP_FILE);
return false;
} catch (e) {
// On error, allow the report through
return false;
}
}
// --- DASHBOARD LOGIC START ---
const EVENTS_FILE = path.resolve(__dirname, '../../assets/gep/events.jsonl');
function getDashboardStats() {
if (!fs.existsSync(EVENTS_FILE)) return null;
try {
const content = fs.readFileSync(EVENTS_FILE, 'utf8');
const lines = content.split('\n').filter(Boolean);
const events = lines.map(l => { try { return JSON.parse(l); } catch(e){ return null; } }).filter(e => e && e.type === 'EvolutionEvent');
if (events.length === 0) return null;
const total = events.length;
const successful = events.filter(e => e.outcome && e.outcome.status === 'success').length;
const successRate = ((successful / total) * 100).toFixed(1);
const intents = { innovate: 0, repair: 0, optimize: 0 };
let totalFiles = 0, totalLines = 0, countBlast = 0;
let totalRigor = 0, totalRisk = 0, countPers = 0;
events.forEach(e => {
if (intents[e.intent] !== undefined) intents[e.intent]++;
// Blast Radius Stats (Recent 10)
if (e.blast_radius) {
totalFiles += (e.blast_radius.files || 0);
totalLines += (e.blast_radius.lines || 0);
countBlast++;
}
// Personality Stats (Recent 10)
if (e.personality_state) {
totalRigor += (e.personality_state.rigor || 0);
totalRisk += (e.personality_state.risk_tolerance || 0);
countPers++;
}
});
const recent = events.slice(-10).reverse().map(e => ({
id: e.id.replace('evt_', '').substring(0, 6),
intent: e.intent || 'repair',
status: e.outcome && e.outcome.status === 'success' ? 'success' : 'failed',
files: (e.blast_radius && e.blast_radius.files) || 0,
lines: (e.blast_radius && e.blast_radius.lines) || 0
}));
const avgFiles = countBlast > 0 ? (totalFiles / countBlast).toFixed(1) : 0;
const avgLines = countBlast > 0 ? (totalLines / countBlast).toFixed(0) : 0;
const avgRigor = countPers > 0 ? (totalRigor / countPers).toFixed(2) : 0;
return { total, successRate, intents, recent, avgFiles, avgLines, avgRigor };
} catch (e) {
return null;
}
}
// --- DASHBOARD LOGIC END ---
const { requireEvolverModule, resolveEvolverDir } = require('./utils/resolve-evolver');
let runSkillsMonitor;
{
const mod = requireEvolverModule('src/ops/skills_monitor', './skills_monitor.js');
runSkillsMonitor = (mod && mod.run) || (() => []);
}
// INNOVATION: Load dedicated System Monitor (Native Node) if available
let sysMon;
try {
// Try to load the optimized monitor first
sysMon = require('../system-monitor');
} catch (e) {
// Optimized Native Implementation (Linux/Node 18+)
sysMon = {
getProcessCount: () => {
try {
// Linux: Count numeric directories in /proc
if (process.platform === 'linux') {
return fs.readdirSync('/proc').filter(f => /^\d+$/.test(f)).length;
}
// Fallback for non-Linux
return execSync('ps -e | wc -l').toString().trim();
} catch(e){ return '?'; }
},
getDiskUsage: (mount) => {
try {
if (fs.statfsSync) {
const stats = fs.statfsSync(mount || '/');
const total = stats.blocks * stats.bsize;
const free = stats.bavail * stats.bsize;
const used = total - free;
return Math.round((used / total) * 100) + '%';
}
// Fallback for older Node
return execSync(`df -h "${mount || '/'}" | tail -1 | awk '{print $5}'`).toString().trim();
} catch(e){ return '?'; }
},
getLastLine: (f) => {
try {
if (!fs.existsSync(f)) return '';
const fd = fs.openSync(f, 'r');
const stat = fs.fstatSync(fd);
const size = stat.size;
if (size === 0) { fs.closeSync(fd); return ''; }
const bufSize = Math.min(1024, size);
const buffer = Buffer.alloc(bufSize);
let position = size - bufSize;
fs.readSync(fd, buffer, 0, bufSize, position);
fs.closeSync(fd);
let content = buffer.toString('utf8');
// Trim trailing newline if present
if (content.endsWith('\n')) content = content.slice(0, -1);
const lastBreak = content.lastIndexOf('\n');
return lastBreak === -1 ? content : content.slice(lastBreak + 1);
} catch(e){ return ''; }
}
};
}
const STATE_FILE = path.resolve(__dirname, '../../memory/evolution_state.json');
const CYCLE_COUNTER_FILE = path.resolve(__dirname, '../../logs/cycle_count.txt');
function parseCycleNumber(value) {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
const text = String(value || '').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 isStaleCycleReport(cycleId) {
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(cycleId);
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 getCycleInfo() {
let nextId = 1;
let durationStr = 'N/A';
const now = new Date();
// 1. Try State File (Fast & Persistent)
try {
if (fs.existsSync(STATE_FILE)) {
const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
if (state.lastCycleId) {
nextId = state.lastCycleId + 1;
// Calculate duration since last cycle
if (state.lastUpdate) {
const diff = now.getTime() - new Date(state.lastUpdate).getTime();
const mins = Math.floor(diff / 60000);
const secs = Math.floor((diff % 60000) / 1000);
durationStr = `${mins}m ${secs}s`;
}
// Auto-increment and save
state.lastCycleId = nextId;
state.lastUpdate = now.toISOString();
fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
return { id: nextId, duration: durationStr };
}
}
} catch (e) {}
// 2. Fallback: MEMORY.md (Legacy/Seed)
let maxId = 0;
try {
const memPath = path.resolve(__dirname, '../../MEMORY.md');
if (fs.existsSync(memPath)) {
const memContent = fs.readFileSync(memPath, 'utf8');
const matches = [...memContent.matchAll(/Cycle #(\d+)/g)];
for (const match of matches) {
const id = parseInt(match[1]);
if (id > maxId) maxId = id;
}
}
} catch (e) {}
// Initialize State File if missing
nextId = (maxId > 0 ? maxId : Math.floor(Date.now() / 1000)) + 1;
try {
fs.writeFileSync(STATE_FILE, JSON.stringify({
lastCycleId: nextId,
lastUpdate: now.toISOString()
}, null, 2));
} catch(e) {}
return { id: nextId, duration: 'First Run' };
}
async function findEvolutionGroup() {
try {
let pageToken = '';
do {
const url = `https://open.feishu.cn/open-apis/im/v1/chats?page_size=100${pageToken ? `&page_token=${pageToken}` : ''}`;
const res = await fetchWithAuth(url, { method: 'GET' });
const data = await res.json();
if (data.code !== 0) {
console.warn(`[Wrapper] List Chats failed: ${data.msg}`);
return null;
}
if (data.data && data.data.items) {
const group = data.data.items.find(c => c.name && c.name.includes('🧬'));
if (group) {
// console.log(`[Wrapper] Found Evolution Group: ${group.name} (${group.chat_id})`);
return group.chat_id;
}
}
pageToken = data.data.page_token;
} while (pageToken);
} catch (e) {
console.warn(`[Wrapper] Group lookup error: ${e.message}`);
}
return null;
}
async function sendReport(options) {
let content = options.status || options.content || '';
if (options.file) {
try {
content = fs.readFileSync(options.file, 'utf8');
} catch (e) {
console.error(`Failed to read file: ${options.file}`);
throw e;
}
}
if (!content && !options.dashboard) {
throw new Error('Must provide --status or --file (unless --dashboard is set)');
}
const cycleInfo = options.cycle ? { id: options.cycle, duration: 'Manual' } : getCycleInfo();
const cycleId = cycleInfo.id;
if (isStaleCycleReport(cycleId)) {
console.warn(`[Wrapper] Suppressing stale report for cycle #${cycleId}.`);
return;
}
let title = options.title;
if (!title) {
if (options.lang === 'cn') {
title = `进化 #${cycleId}`;
} else {
title = `Evolution #${cycleId}`;
}
}
const MASTER_ID = process.env.OPENCLAW_MASTER_ID || '';
let target = options.target;
if (!target) {
target = await findEvolutionGroup();
}
if (!target) {
console.warn('[Wrapper] No Evolution Group found. Falling back to Master ID.');
target = MASTER_ID;
}
if (!target) {
throw new Error('No target ID found (Env OPENCLAW_MASTER_ID missing and no --target).');
}
// --- DEDUP CHECK ---
var statusHash = crypto.createHash('md5').update(options.status || '').digest('hex').slice(0, 12);
var reportKey = `${cycleId}:${target}:${title}:${statusHash}`;
if (isDuplicateReport(reportKey)) {
console.log('[Wrapper] Duplicate report suppressed.');
return;
}
try {
console.log(`[Wrapper] Reporting Cycle #${cycleId} to ${target}...`);
let uptime = '?';
let loadAvg = '?';
try {
const wrapperPidFile = path.resolve(__dirname, '../../memory/evolver_wrapper.pid');
if (fs.existsSync(wrapperPidFile)) {
const pid = parseInt(fs.readFileSync(wrapperPidFile, 'utf8').trim(), 10);
if (Number.isFinite(pid) && pid > 1) {
try {
const pidPath = `/proc/${pid}`;
if (fs.existsSync(pidPath)) {
const pidStat = fs.statSync(pidPath);
uptime = Math.floor((Date.now() - pidStat.ctimeMs) / 1000);
} else {
const et = execSync(`ps -o etimes= -p ${pid}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
const secs = parseInt(et, 10);
if (Number.isFinite(secs) && secs >= 0) uptime = secs;
}
} catch (_) {
uptime = Math.round(process.uptime());
}
}
}
if (uptime === '?') uptime = Math.round(process.uptime());
loadAvg = os.loadavg()[0].toFixed(2);
} catch (e) {
console.warn('[Wrapper] Stats collection failed:', e.message);
}
const isChineseReport = options.lang === 'cn';
const footerText = isChineseReport
? `运行: ${uptime}s | 负载: ${loadAvg}`
: `Up: ${uptime}s | Load: ${loadAvg}`;
// Auto-detect color from status text
let headerColor = options.color || 'blue';
if (headerColor === 'blue') {
const statusUpper = (options.status || '').toUpperCase();
if (statusUpper.includes('[SUCCESS]') || statusUpper.includes('[成功]')) headerColor = 'green';
else if (statusUpper.includes('[FAILED]') || statusUpper.includes('[失败]')) headerColor = 'red';
else if (statusUpper.includes('[WARNING]') || statusUpper.includes('[警告]')) headerColor = 'orange';
else if (statusUpper.includes('[INNOVATE]') || statusUpper.includes('[创新]')) headerColor = 'purple';
else if (statusUpper.includes('[REPAIR]') || statusUpper.includes('[修复]')) headerColor = 'orange';
else if (statusUpper.includes('[OPTIMIZE]') || statusUpper.includes('[优化]')) headerColor = 'blue';
else if (statusUpper.includes('SUCCESS')) headerColor = 'green';
else if (statusUpper.includes('FAILED')) headerColor = 'red';
else if (statusUpper.includes('ERROR')) headerColor = 'red';
}
// If summary is provided (merged card mode), use v2 structured card
if (options.summary) {
if (options.summary.success && headerColor === 'blue') headerColor = 'green';
if (!options.summary.success && headerColor === 'blue') headerColor = 'red';
const intentTag = options.summary.success
? { text: isChineseReport ? '成功' : 'Success', color: 'green' }
: { text: isChineseReport ? '失败' : 'Failed', color: 'red' };
await sendStructuredCard({
target,
title,
color: headerColor,
tags: [intentTag],
status: content,
summary: options.summary,
footer: footerText
});
} else if (options.dashboard) {
console.log('[Wrapper] Generating rich dashboard card...');
const stats = getDashboardStats();
const safeStats = stats || { total: 0, successRate: '0.0', intents: { innovate: 0, repair: 0, optimize: 0 }, recent: [] };
const cardData = generateDashboardCard(
safeStats,
{
proc: sysMon.getProcessCount(),
mem: Math.round(process.memoryUsage().rss / 1024 / 1024),
uptime, load: loadAvg,
disk: sysMon.getDiskUsage('/'),
loopStatus: isChineseReport ? '运行中' : 'ON',
errorAlert: '', healthAlert: ''
},
{ id: cycleId, duration: cycleInfo.duration }
);
// Use v2 structured card for dashboard too
const dashCard = {
schema: '2.0',
config: { update_multi: true, width_mode: 'default' },
header: cardData.header,
body: { elements: cardData.elements }
};
await postCard(target, dashCard);
} else {
await sendCard({
target, title,
text: content,
note: footerText,
color: headerColor
});
}
console.log('[Wrapper] Report sent successfully.');
try {
const LOG_FILE = path.resolve(__dirname, '../../logs/evolution_reports.log');
if (!fs.existsSync(path.dirname(LOG_FILE))) {
fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true });
}
fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] Cycle #${cycleId} - Status: SUCCESS - Target: ${target} - Duration: ${cycleInfo.duration}\n`);
} catch (logErr) {
console.warn('[Wrapper] Failed to write to local log:', logErr.message);
}
} catch (e) {
console.error('[Wrapper] Report failed:', e.message);
throw e;
}
}
// CLI Logic
if (require.main === module) {
program
.option('-s, --status <text>', 'Status text/markdown content')
.option('--content <text>', 'Alias for --status (compatibility)')
.option('-f, --file <path>', 'Path to markdown file content')
.option('-c, --cycle <id>', 'Evolution Cycle ID')
.option('--title <text>', 'Card Title override')
.option('--color <color>', 'Header color (blue/red/green/orange)', 'blue')
.option('--target <id>', 'Target User/Chat ID')
.option('--lang <lang>', 'Language (en|cn)', 'en')
.option('--dashboard', 'Send rich dashboard card instead of plain text')
.parse(process.argv);
const options = program.opts();
sendReport(options).catch(err => {
console.error('[Wrapper] Report failed (non-fatal):', err.message);
// Don't fail the build/cycle just because reporting failed (e.g. permission issues)
process.exit(0);
});
}
module.exports = { sendReport };