-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
473 lines (423 loc) · 18.3 KB
/
server.js
File metadata and controls
473 lines (423 loc) · 18.3 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
'use strict';
require('dotenv').config();
const express = require('express');
const { execSync } = require('child_process');
const path = require('path');
const cron = require('node-cron');
const ical = require('node-ical');
const fs = require('fs');
const app = express();
const PORT = 4500;
// ── Config ────────────────────────────────────────────────────────────────────
const ACTIVE_REPOS = [
'DamageLabs/uas-log',
'DamageLabs/armory-core',
'DamageLabs/damagelabs.io',
'DamageLabs/paper_trail_manager',
'DamageLabs/clahub',
'DamageLabs/whiskey-canon',
'DamageLabs/sports-card-tracker',
'DamageLabs/brain',
'DamageLabs/command-center',
'fusion94/fusion94.org',
'fusion94/clawd',
];
const TASKS_DIR = '/Users/guntharp/Documents/guntharp-personal/02 - Action/01 - Tasks';
const VAULT_DIR = '/Users/guntharp/Documents/guntharp-personal';
const DAILY_DIR = `${VAULT_DIR}/03 - Periodic/01 - Daily`;
const DECISIONS_DIR = `${VAULT_DIR}/08 - Projects/DamageLabs/Decisions`;
const STANDUP_DIR = `${process.env.HOME}/Code/brain/standups/daily`;
const TASK_FILES = [
{ file: '02 - General Tasks.md', label: 'General', color: 'amber' },
{ file: '03 - CA Tasks.md', label: 'California', color: 'blue' },
{ file: '04 - TX Tasks.md', label: 'Texas', color: 'green' },
];
const CALENDAR_URLS = [
process.env.CAL_1,
process.env.CAL_2,
].filter(Boolean);
// ── Helpers ───────────────────────────────────────────────────────────────────
function issuePriority(labels) {
const names = labels.map(l => l.name.toLowerCase());
if (names.some(n => n.includes('bug') || n.includes('critical') || n.includes('urgent'))) return 'urgent';
if (names.some(n => n.includes('enhancement') || n.includes('feature') || n.includes('frontend') || n.includes('backend'))) return 'active';
return 'deferred';
}
function gh(cmd) {
return JSON.parse(execSync(`gh ${cmd}`, { encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 }));
}
// ── Cache ─────────────────────────────────────────────────────────────────────
let cache = {
issues: null,
repoStats: null,
events: null,
tasks: null,
notes: null,
standup: null,
prs: null,
prsUpdatedAt: null,
issuesUpdatedAt: null,
eventsUpdatedAt: null,
tasksUpdatedAt: null,
};
// ── Pull Requests ───────────────────────────────────────────────────────────────
function fetchPRs() {
console.log('[prs] fetching open PRs...');
try {
const allPRs = [];
for (const repo of ACTIVE_REPOS) {
try {
const prs = gh(`pr list --repo ${repo} --state open --json number,title,author,createdAt,url,headRefName,isDraft,reviewDecision,labels --limit 20`);
const repoName = repo.split('/')[1];
allPRs.push(...prs.map(pr => ({
...pr,
repo: repoName,
repoFull: repo,
})));
} catch (e) {
// repo may have no PRs or no access
}
}
allPRs.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
cache.prs = allPRs;
cache.prsUpdatedAt = Date.now();
console.log(`[prs] fetched ${allPRs.length} open PRs`);
} catch (err) {
console.error('[prs] fetch error:', err.message);
}
}
// ── Standup ───────────────────────────────────────────────────────────────────
function fetchStandup() {
console.log('[standup] reading latest standup...');
try {
if (!fs.existsSync(STANDUP_DIR)) {
cache.standup = null;
return;
}
const files = fs.readdirSync(STANDUP_DIR)
.filter(f => f.match(/^\d{4}-\d{2}-\d{2}\.md$/))
.sort().reverse();
if (!files.length) { cache.standup = null; return; }
const latest = files[0];
const date = latest.replace('.md', '');
const content = fs.readFileSync(`${STANDUP_DIR}/${latest}`, 'utf8');
// Parse sections: split on ### headings (repos)
const sections = [];
const repoBlocks = content.split(/\n### /);
for (const block of repoBlocks.slice(1)) {
const lines = block.split('\n');
const repo = lines[0].trim();
const statsMatch = lines[1]?.match(/(\d+ PRs?[^|]*)?\|?\s*(\d+ Commits?)?\|?\s*(\d+ Issues?[^*]*)/);
const bullets = lines
.filter(l => l.startsWith('- '))
.slice(0, 4)
.map(l => l.replace(/^- /, '').replace(/\*Closes[^*]*\*/g, '').trim());
sections.push({ repo, stats: lines[1]?.replace(/\*\*/g,'').trim() || '', bullets });
}
const now = new Date();
const todayStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}`;
cache.standup = {
date,
isToday: date === todayStr,
title: content.match(/^# (.+)/m)?.[1] || `Standup ${date}`,
sections,
raw: content,
};
console.log(`[standup] loaded ${date}, ${sections.length} repo sections`);
} catch (err) {
console.error('[standup] error:', err.message);
}
}
// ── Notes ────────────────────────────────────────────────────────────────────
function fetchNotes() {
console.log('[notes] reading obsidian notes...');
try {
const now = new Date();
const result = { dailyNote: null, decisions: [], updatedAt: Date.now() };
// Find today's or most recent daily note
const months = ['01-January','02-February','03-March','04-April','05-May','06-June',
'07-July','08-August','09-September','10-October','11-November','12-December'];
const year = now.getFullYear();
const month = months[now.getMonth()];
const pad = n => String(n).padStart(2,'0');
const todayFile = `${year}-${pad(now.getMonth()+1)}-${pad(now.getDate())}.md`;
const monthDir = `${DAILY_DIR}/${year}/${month}`;
// Try today, then walk back up to 7 days
let noteContent = null, noteDate = null;
for (let i = 0; i < 7; i++) {
const d = new Date(now - i * 86400000);
const m = months[d.getMonth()];
const fname = `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}.md`;
const fpath = `${DAILY_DIR}/${d.getFullYear()}/${m}/${fname}`;
if (fs.existsSync(fpath)) {
noteContent = fs.readFileSync(fpath, 'utf8');
noteDate = fname.replace('.md','');
break;
}
}
if (noteContent) {
// Strip frontmatter
const body = noteContent.replace(/^---[\s\S]*?---\n/, '');
// Strip Obsidian code blocks and button syntax
const clean = body
.replace(/```[\s\S]*?```/g, '')
.replace(/>[^\n]*/g, '') // blockquotes
.replace(/!\[\[[^\]]*\]\]/g, '') // embeds
.replace(/\[\[[^\]|]*(?:\|([^\]]+))?\]\]/g, (_, alt) => alt || '')
.replace(/#{1,6}\s/g, '')
.trim();
// First meaningful paragraph
const lines = clean.split('\n').map(l => l.trim()).filter(l => l.length > 20);
result.dailyNote = {
date: noteDate,
preview: lines.slice(0, 3).join(' ').substring(0, 300),
isToday: noteDate === `${year}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`,
};
}
// Recent decisions
if (fs.existsSync(DECISIONS_DIR)) {
const files = fs.readdirSync(DECISIONS_DIR)
.filter(f => f.endsWith('.md'))
.sort().reverse().slice(0, 5);
for (const file of files) {
const content = fs.readFileSync(`${DECISIONS_DIR}/${file}`, 'utf8');
const titleMatch = content.match(/^#\s+(.+)/m);
const statusMatch = content.match(/\*\*Status:\*\*\s*(.+)/i);
const dateMatch = content.match(/\*\*Date:\*\*\s*(\S+)/i);
const contextLines = content.split('\n')
.filter(l => l.trim().length > 20 && !l.startsWith('#') && !l.startsWith('**'))
.slice(0, 2).join(' ').substring(0, 200);
result.decisions.push({
title: titleMatch ? titleMatch[1].replace('Decision: ','') : file.replace('.md',''),
status: statusMatch ? statusMatch[1].trim() : null,
date: dateMatch ? dateMatch[1].trim() : file.substring(0,10),
preview: contextLines,
file: file.replace('.md',''),
});
}
}
cache.notes = result;
console.log(`[notes] daily note: ${result.dailyNote?.date || 'none'}, decisions: ${result.decisions.length}`);
} catch (err) {
console.error('[notes] error:', err.message);
}
}
// ── Tasks ────────────────────────────────────────────────────────────────────
function fetchTasks() {
console.log('[tasks] reading obsidian tasks...');
try {
const result = [];
for (const { file, label, color } of TASK_FILES) {
const fullPath = `${TASKS_DIR}/${file}`;
if (!fs.existsSync(fullPath)) continue;
const lines = fs.readFileSync(fullPath, 'utf8').split('\n');
let currentSection = null;
for (const line of lines) {
// Track headings as sections
const headingMatch = line.match(/^#+\s+(.+)/);
if (headingMatch) { currentSection = headingMatch[1].trim(); continue; }
// Open tasks only: - [ ] ...
const taskMatch = line.match(/^\s*- \[ \]\s+(.+)/);
if (!taskMatch) continue;
const raw = taskMatch[1];
// Skip pure recurring without todo tag if desired (keep all open)
const dueMatch = raw.match(/📅\s*(\d{4}-\d{2}-\d{2})/);
const title = raw
.replace(/📅\s*\d{4}-\d{2}-\d{2}/g, '')
.replace(/#\w+/g, '')
.replace(/🔁[^\n]*/g, '')
.trim();
if (!title) continue;
result.push({
title,
source: label,
color,
section: currentSection,
due: dueMatch ? dueMatch[1] : null,
recurring: raw.includes('🔁'),
});
}
}
cache.tasks = result;
cache.tasksUpdatedAt = Date.now();
console.log(`[tasks] found ${result.length} open tasks`);
} catch (err) {
console.error('[tasks] error:', err.message);
}
}
// ── GitHub ────────────────────────────────────────────────────────────────────
function fetchGitHub() {
console.log('[github] fetching issues...');
try {
// Fetch all DamageLabs + fusion94 repos dynamically
const damagelabsRepos = gh('repo list DamageLabs --json name,isArchived,pushedAt --limit 200')
.map(r => ({ name: `DamageLabs/${r.name}`, archived: r.isArchived }));
const fusion94Repos = gh('repo list fusion94 --json name,isArchived,pushedAt --limit 100')
.filter(r => ['fusion94.org','clawd','dotfiles','homeassistant'].includes(r.name))
.map(r => ({ name: `fusion94/${r.name}`, archived: r.isArchived }));
const allRepos = [...damagelabsRepos, ...fusion94Repos];
const allIssues = [];
const repoStats = [];
// Fetch issues only for ACTIVE_REPOS (prioritized); collect stats for all
for (const { name: repo, archived } of allRepos) {
try {
const issues = gh(`issue list --repo ${repo} --state open --json number,title,labels,assignees,createdAt,url,milestone --limit 100`);
const repoName = repo.split('/')[1];
allIssues.push(...issues.map(i => ({
...i,
repo: repoName,
repoFull: repo,
priority: issuePriority(i.labels),
})));
repoStats.push({
repo: repoName,
repoFull: repo,
openIssues: issues.length,
bugs: issues.filter(i => i.labels.some(l => l.name === 'bug')).length,
enhancements: issues.filter(i => i.labels.some(l => l.name === 'enhancement')).length,
lastActivity: issues.length > 0 ? issues[0].createdAt : null,
tracked: true,
archived,
});
} catch (e) {
console.warn(`[github] skipping ${repo}: ${e.message}`);
}
}
cache.issues = allIssues;
cache.repoStats = repoStats;
cache.issuesUpdatedAt = Date.now();
console.log(`[github] fetched ${allIssues.length} issues, ${repoStats.length} repos`);
} catch (err) {
console.error('[github] fetch error:', err.message);
}
}
// ── Calendar ──────────────────────────────────────────────────────────────────
async function fetchCalendars() {
console.log('[calendar] fetching events...');
try {
const now = new Date();
const windowEnd = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000); // 30 days ahead
const windowStart = new Date(now.getTime() - 60 * 60 * 1000); // 1hr back (catch in-progress)
const allEvents = [];
for (const url of CALENDAR_URLS) {
try {
const data = await ical.async.fromURL(url);
for (const [, event] of Object.entries(data)) {
if (event.type !== 'VEVENT') continue;
// Handle recurring events
const start = event.start instanceof Date ? event.start : new Date(event.start);
const end = event.end instanceof Date ? event.end : new Date(event.end || start);
if (start < windowStart || start > windowEnd) continue;
allEvents.push({
id: event.uid,
title: event.summary || '(No title)',
start: start.toISOString(),
end: end.toISOString(),
allDay: !event.start?.dateTime && !event.start?.getHours,
location: event.location || null,
description: event.description ? event.description.substring(0, 200) : null,
calendar: url.includes('group.calendar') ? 'Work' : 'Personal',
});
}
} catch (e) {
console.warn(`[calendar] error fetching ${url.substring(0, 50)}...: ${e.message}`);
}
}
// Sort by start time
allEvents.sort((a, b) => new Date(a.start) - new Date(b.start));
cache.events = allEvents;
cache.eventsUpdatedAt = Date.now();
console.log(`[calendar] fetched ${allEvents.length} events`);
} catch (err) {
console.error('[calendar] fetch error:', err.message);
}
}
// ── Schedules ─────────────────────────────────────────────────────────────────
cron.schedule('*/5 * * * *', fetchGitHub);
cron.schedule('*/10 * * * *', fetchCalendars);
cron.schedule('*/2 * * * *', fetchTasks);
cron.schedule('*/5 * * * *', fetchNotes);
cron.schedule('*/10 * * * *', fetchStandup);
cron.schedule('*/5 * * * *', fetchPRs);
fetchGitHub();
fetchCalendars();
fetchTasks();
fetchNotes();
fetchStandup();
fetchPRs();
// ── Routes ────────────────────────────────────────────────────────────────────
app.use(express.static(path.join(__dirname, 'public')));
app.get('/api/issues', (req, res) => {
if (!cache.issues) return res.status(503).json({ ok: false, error: 'loading' });
const urgent = cache.issues.filter(i => i.priority === 'urgent');
const active = cache.issues.filter(i => i.priority === 'active');
const deferred = cache.issues.filter(i => i.priority === 'deferred');
res.json({ ok: true, urgent, active, deferred, total: cache.issues.length, updatedAt: cache.issuesUpdatedAt });
});
app.get('/api/repos', (req, res) => {
if (!cache.repoStats) return res.status(503).json({ ok: false, error: 'loading' });
res.json({ ok: true, repos: cache.repoStats, updatedAt: cache.issuesUpdatedAt });
});
app.get('/api/calendar', (req, res) => {
if (!cache.events) return res.status(503).json({ ok: false, error: 'loading' });
res.json({ ok: true, events: cache.events, updatedAt: cache.eventsUpdatedAt });
});
// Infra — PM2 process list
app.get('/api/infra', (req, res) => {
try {
const raw = execSync('pm2 jlist', { encoding: 'utf8' });
const processes = JSON.parse(raw);
const data = processes.map(p => ({
id: p.pm_id,
name: p.name,
status: p.pm2_env.status,
pid: p.pid,
uptime: p.pm2_env.status === 'online' ? Date.now() - p.pm2_env.pm_uptime : null,
restarts: p.pm2_env.restart_time,
cpu: p.monit?.cpu ?? 0,
memory: p.monit?.memory ?? 0,
}));
res.json({ ok: true, processes: data, updatedAt: Date.now() });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.get('/api/tasks', (req, res) => {
if (!cache.tasks) return res.status(503).json({ ok: false, error: 'loading' });
res.json({ ok: true, tasks: cache.tasks, updatedAt: cache.tasksUpdatedAt });
});
app.get('/api/prs', (req, res) => {
if (!cache.prs) return res.status(503).json({ ok: false, error: 'loading' });
res.json({ ok: true, prs: cache.prs, updatedAt: cache.prsUpdatedAt });
});
app.get('/api/standup', (req, res) => {
res.json({ ok: true, standup: cache.standup || null });
});
app.get('/api/notes', (req, res) => {
if (!cache.notes) return res.status(503).json({ ok: false, error: 'loading' });
res.json({ ok: true, ...cache.notes });
});
// Quick issue close
app.post('/api/issues/:owner/:repo/:number/close', (req, res) => {
try {
const { owner, repo, number } = req.params;
execSync(`gh issue close ${number} --repo ${owner}/${repo}`, { encoding: 'utf8' });
// Trigger background refresh
fetchGitHub();
res.json({ ok: true });
} catch (err) {
res.status(500).json({ ok: false, error: err.message });
}
});
app.post('/api/refresh', async (req, res) => {
fetchGitHub();
await fetchCalendars();
fetchTasks();
fetchNotes();
fetchStandup();
fetchPRs();
res.json({ ok: true });
});
app.listen(PORT, '127.0.0.1', () => {
console.log(`command-center running at http://127.0.0.1:${PORT}`);
});