2// Script to clean up old/test agents from the database
3const pool = require('../services/db');
8async function cleanupOldAgents() {
9 console.log('[Cleanup] Starting agent cleanup...');
12 // Find agents older than 30 days with no recent activity
13 const oldAgentsQuery = `
14 SELECT agent_id, agent_uuid, hostname, last_seen, created_at
16 WHERE last_seen < NOW() - INTERVAL '30 days'
17 OR (last_seen IS NULL AND created_at < NOW() - INTERVAL '7 days')
18 ORDER BY last_seen DESC NULLS LAST
21 const result = await pool.query(oldAgentsQuery);
22 console.log(`[Cleanup] Found ${result.rows.length} old agents`);
24 if (result.rows.length === 0) {
25 console.log('[Cleanup] No old agents to clean up');
30 console.log('\nOld agents:');
31 result.rows.forEach((agent, idx) => {
32 console.log(`${idx + 1}. ${agent.hostname} (${agent.agent_uuid})`);
33 console.log(` Last seen: ${agent.last_seen || 'Never'}`);
34 console.log(` Created: ${agent.created_at}`);
38 const readline = require('readline').createInterface({
40 output: process.stdout
43 readline.question('\nDelete these agents? (yes/no): ', async (answer) => {
44 if (answer.toLowerCase() === 'yes' || answer.toLowerCase() === 'y') {
46 for (const agent of result.rows) {
48 await pool.query('DELETE FROM agents WHERE agent_id = $1', [agent.agent_id]);
49 console.log(`✓ Deleted ${agent.hostname} (${agent.agent_uuid})`);
51 console.error(`✗ Failed to delete ${agent.hostname}:`, err.message);
54 console.log('\n[Cleanup] Agent cleanup complete');
56 console.log('[Cleanup] Cancelled');
64 console.error('[Cleanup] Error:', err);