Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: address Copilot round 4 — semicolons, feedback path resolution

Adam Eivy7f8f2f5deb99
diff --git a/server/services/cosAgents.js b/server/services/cosAgents.js
index 388177d68e..266c40b385 100644
--- a/server/services/cosAgents.js
+++ b/server/services/cosAgents.js
@@ -658,8 +658,9 @@ export async function submitAgentFeedback(agentId, feedback) {
state.agents[agentId].feedback = feedbackData
await saveState(state)
- // Also update on-disk metadata
- const agentDir = getAgentDir(agentId)
+ // Also update on-disk metadata (derive date bucket from completedAt if archived)
+ const dateBucket = agent.completedAt ? agent.completedAt.slice(0, 10) : null
+ const agentDir = getAgentDir(agentId, dateBucket)
const metaPath = join(agentDir, 'metadata.json')
if (existsSync(metaPath)) {
const content = await readFile(metaPath, 'utf-8').catch(() => null)
diff --git a/server/services/cosEvents.js b/server/services/cosEvents.js
index c0bc8c7c8b..0f68cf526e 100644
--- a/server/services/cosEvents.js
+++ b/server/services/cosEvents.js
@@ -5,10 +5,10 @@
* Separated to avoid circular dependencies between cos.js and other modules.
*/
-import { EventEmitter } from 'events'
+import { EventEmitter } from 'events';
// Event emitter for CoS events
-export const cosEvents = new EventEmitter()
+export const cosEvents = new EventEmitter();
/**
* Emit a log event for UI display
@@ -23,12 +23,12 @@ export function emitLog(level, message, data = {}, prefix = '') {
level,
message,
...data
- }
+ };
// Debug messages go to socket only (UI), not console — set COS_LOG_LEVEL=debug to include them
if (level !== 'debug' || process.env.COS_LOG_LEVEL === 'debug') {
- const emoji = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : level === 'debug' ? '🔍' : 'ℹ️'
- const prefixStr = prefix ? ` ${prefix}` : ''
- console.log(`${emoji}${prefixStr} ${message}`)
+ const emoji = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : level === 'debug' ? '🔍' : 'ℹ️';
+ const prefixStr = prefix ? ` ${prefix}` : '';
+ console.log(`${emoji}${prefixStr} ${message}`);
}
- cosEvents.emit('log', logEntry)
+ cosEvents.emit('log', logEntry);
}
diff --git a/server/services/cosReports.js b/server/services/cosReports.js
index f34f4f4119..a62121ec52 100644
--- a/server/services/cosReports.js
+++ b/server/services/cosReports.js
@@ -5,21 +5,21 @@
* Handles daily reports, briefings, activity summaries, and recent tasks.
*/
-import { readFile, writeFile, readdir } from 'fs/promises'
-import { existsSync } from 'fs'
-import { join } from 'path'
-import { loadState, ensureDirectories, REPORTS_DIR, isDaemonRunning } from './cosState.js'
-import { formatDuration, safeJSONParse } from '../lib/fileUtils.js'
+import { readFile, writeFile, readdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { loadState, ensureDirectories, REPORTS_DIR, isDaemonRunning } from './cosState.js';
+import { formatDuration, safeJSONParse } from '../lib/fileUtils.js';
export async function generateReport(date = null) {
- const reportDate = date || new Date().toISOString().split('T')[0]
- const state = await loadState()
+ const reportDate = date || new Date().toISOString().split('T')[0];
+ const state = await loadState();
// Filter agents completed on this date
const completedAgents = Object.values(state.agents).filter(a => {
- if (!a.completedAt) return false
- return a.completedAt.startsWith(reportDate)
- })
+ if (!a.completedAt) return false;
+ return a.completedAt.startsWith(reportDate);
+ });
const report = {
date: reportDate,
@@ -37,97 +37,97 @@ export async function generateReport(date = null) {
? new Date(a.completedAt) - new Date(a.startedAt)
: 0
}))
- }
+ };
// Save report
- const reportFile = join(REPORTS_DIR, `${reportDate}.json`)
- await writeFile(reportFile, JSON.stringify(report, null, 2))
+ const reportFile = join(REPORTS_DIR, `${reportDate}.json`);
+ await writeFile(reportFile, JSON.stringify(report, null, 2));
- return report
+ return report;
}
export async function getReport(date) {
- const reportFile = join(REPORTS_DIR, `${date}.json`)
+ const reportFile = join(REPORTS_DIR, `${date}.json`);
if (!existsSync(reportFile)) {
- return null
+ return null;
}
- const content = await readFile(reportFile, 'utf-8')
- return safeJSONParse(content, null, { logError: true, context: `report ${date}` })
+ const content = await readFile(reportFile, 'utf-8');
+ return safeJSONParse(content, null, { logError: true, context: `report ${date}` });
}
export async function getTodayReport() {
- const today = new Date().toISOString().split('T')[0]
- return (await getReport(today)) ?? generateReport(today)
+ const today = new Date().toISOString().split('T')[0];
+ return (await getReport(today)) ?? generateReport(today);
}
export async function listReports() {
- await ensureDirectories()
+ await ensureDirectories();
- const files = await readdir(REPORTS_DIR)
+ const files = await readdir(REPORTS_DIR);
return files
.filter(f => f.endsWith('.json'))
.map(f => f.replace('.json', ''))
.sort()
- .reverse()
+ .reverse();
}
export async function listBriefings() {
- await ensureDirectories()
+ await ensureDirectories();
- const files = await readdir(REPORTS_DIR)
+ const files = await readdir(REPORTS_DIR);
return files
.filter(f => f.endsWith('-briefing.md'))
.map(f => {
- const date = f.replace('-briefing.md', '')
- return { date, filename: f }
+ const date = f.replace('-briefing.md', '');
+ return { date, filename: f };
})
- .sort((a, b) => b.date.localeCompare(a.date))
+ .sort((a, b) => b.date.localeCompare(a.date));
}
export async function getBriefing(date) {
- const briefingFile = join(REPORTS_DIR, `${date}-briefing.md`)
+ const briefingFile = join(REPORTS_DIR, `${date}-briefing.md`);
if (!existsSync(briefingFile)) {
- return null
+ return null;
}
- const content = await readFile(briefingFile, 'utf-8')
- return { date, content }
+ const content = await readFile(briefingFile, 'utf-8');
+ return { date, content };
}
export async function getLatestBriefing() {
- const briefings = await listBriefings()
- if (briefings.length === 0) return null
- return getBriefing(briefings[0].date)
+ const briefings = await listBriefings();
+ if (briefings.length === 0) return null;
+ return getBriefing(briefings[0].date);
}
export async function getTodayActivity() {
- const state = await loadState()
- const today = new Date().toISOString().split('T')[0]
+ const state = await loadState();
+ const today = new Date().toISOString().split('T')[0];
// Filter agents completed today
const todayAgents = Object.values(state.agents).filter(a => {
- if (!a.completedAt) return false
- return a.completedAt.startsWith(today)
- })
+ if (!a.completedAt) return false;
+ return a.completedAt.startsWith(today);
+ });
- const succeeded = todayAgents.filter(a => a.result?.success)
- const failed = todayAgents.filter(a => !a.result?.success)
+ const succeeded = todayAgents.filter(a => a.result?.success);
+ const failed = todayAgents.filter(a => !a.result?.success);
// Calculate total time worked (sum of agent durations)
const totalDurationMs = todayAgents.reduce((sum, a) => {
- const duration = a.result?.duration || 0
- return sum + duration
- }, 0)
+ const duration = a.result?.duration || 0;
+ return sum + duration;
+ }, 0);
// Get currently running agents
- const runningAgents = Object.values(state.agents).filter(a => a.status === 'running')
+ const runningAgents = Object.values(state.agents).filter(a => a.status === 'running');
const activeTimeMs = runningAgents.reduce((sum, a) => {
- if (!a.startedAt) return sum
- return sum + (Date.now() - new Date(a.startedAt).getTime())
- }, 0)
+ if (!a.startedAt) return sum;
+ return sum + (Date.now() - new Date(a.startedAt).getTime());
+ }, 0);
// Get top accomplishments (successful tasks with description snippets)
const accomplishments = succeeded
@@ -140,12 +140,12 @@ export async function getTodayActivity() {
completedAt: a.completedAt
}))
.sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt))
- .slice(0, 5)
+ .slice(0, 5);
// Calculate success rate
const successRate = todayAgents.length > 0
? Math.round((succeeded.length / todayAgents.length) * 100)
- : 0
+ : 0;
return {
date: today,
@@ -168,17 +168,17 @@ export async function getTodayActivity() {
lastEvaluation: state.stats.lastEvaluation,
isRunning: isDaemonRunning(),
isPaused: state.paused
- }
+ };
}
export async function getRecentTasks(limit = 10) {
- const state = await loadState()
+ const state = await loadState();
// Get all completed agents, sorted by completion time (newest first)
const completedAgents = Object.values(state.agents)
.filter(a => a.status === 'completed' && a.completedAt)
.sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt))
- .slice(0, limit)
+ .slice(0, limit);
// Transform to compact task summaries
const tasks = completedAgents.map(a => ({
@@ -192,11 +192,11 @@ export async function getRecentTasks(limit = 10) {
durationFormatted: formatDuration(a.result?.duration || 0),
completedAt: a.completedAt,
completedRelative: formatRelativeTime(a.completedAt)
- }))
+ }));
// Calculate summary stats
- const successCount = tasks.filter(t => t.success).length
- const failCount = tasks.filter(t => !t.success).length
+ const successCount = tasks.filter(t => t.success).length;
+ const failCount = tasks.filter(t => !t.success).length;
return {
tasks,
@@ -206,21 +206,21 @@ export async function getRecentTasks(limit = 10) {
failed: failCount,
successRate: tasks.length > 0 ? Math.round((successCount / tasks.length) * 100) : 0
}
- }
+ };
}
export function formatRelativeTime(timestamp) {
- const now = new Date()
- const then = new Date(timestamp)
- const diffMs = now - then
- const diffMins = Math.floor(diffMs / 60000)
- const diffHours = Math.floor(diffMs / 3600000)
- const diffDays = Math.floor(diffMs / 86400000)
-
- if (diffMins < 1) return 'just now'
- if (diffMins < 60) return `${diffMins}m ago`
- if (diffHours < 24) return `${diffHours}h ago`
- if (diffDays === 1) return 'yesterday'
- if (diffDays < 7) return `${diffDays}d ago`
- return then.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
+ const now = new Date();
+ const then = new Date(timestamp);
+ const diffMs = now - then;
+ const diffMins = Math.floor(diffMs / 60000);
+ const diffHours = Math.floor(diffMs / 3600000);
+ const diffDays = Math.floor(diffMs / 86400000);
+
+ if (diffMins < 1) return 'just now';
+ if (diffMins < 60) return `${diffMins}m ago`;
+ if (diffHours < 24) return `${diffHours}h ago`;
+ if (diffDays === 1) return 'yesterday';
+ if (diffDays < 7) return `${diffDays}d ago`;
+ return then.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}
diff --git a/server/services/cosState.js b/server/services/cosState.js
index f29849f236..208ca39e98 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -4,20 +4,20 @@
* Shared state management for Chief of Staff services.
*/
-import { readFile, writeFile, rename, readdir, rm } from 'fs/promises'
-import { existsSync } from 'fs'
-import { join, dirname } from 'path'
-import { createMutex } from '../lib/asyncMutex.js'
-import { ensureDirs, safeJSONParse, PATHS } from '../lib/fileUtils.js'
-
-export const STATE_FILE = join(PATHS.cos, 'state.json')
-export const AGENTS_DIR = join(PATHS.cos, 'agents')
-export const REPORTS_DIR = PATHS.reports
-export const SCRIPTS_DIR = PATHS.scripts
-export const ROOT_DIR = PATHS.root
+import { readFile, writeFile, rename, readdir, rm } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { createMutex } from '../lib/asyncMutex.js';
+import { ensureDirs, safeJSONParse, PATHS } from '../lib/fileUtils.js';
+
+export const STATE_FILE = join(PATHS.cos, 'state.json');
+export const AGENTS_DIR = join(PATHS.cos, 'agents');
+export const REPORTS_DIR = PATHS.reports;
+export const SCRIPTS_DIR = PATHS.scripts;
+export const ROOT_DIR = PATHS.root;
// Mutex lock for state operations to prevent race conditions
-export const withStateLock = createMutex()
+export const withStateLock = createMutex();
export const DEFAULT_CONFIG = {
userTasksFile: 'data/TASKS.md',
@@ -62,7 +62,7 @@ export const DEFAULT_CONFIG = {
'import-cleanup'
]
}
-}
+};
export const DEFAULT_STATE = {
running: false,
@@ -79,62 +79,62 @@ export const DEFAULT_STATE = {
lastIdleReview: null
},
agents: {}
-}
+};
export async function ensureDirectories() {
- await ensureDirs([PATHS.data, PATHS.cos, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR])
+ await ensureDirs([PATHS.data, PATHS.cos, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR]);
}
export function isValidJSON(str) {
- if (!str || !str.trim()) return false
- const trimmed = str.trim()
- if (!(trimmed.startsWith('{') && trimmed.endsWith('}'))) return false
- if (trimmed.includes('}{')) return false
- return true
+ if (!str || !str.trim()) return false;
+ const trimmed = str.trim();
+ if (!(trimmed.startsWith('{') && trimmed.endsWith('}'))) return false;
+ if (trimmed.includes('}{')) return false;
+ return true;
}
// In-memory state cache — avoids re-reading state.json from disk on every call.
// All mutations go through withStateLock, so the cache stays consistent.
-let stateCache = null
+let stateCache = null;
export async function loadState() {
- if (stateCache) return stateCache
+ if (stateCache) return stateCache;
- await ensureDirectories()
+ await ensureDirectories();
if (!existsSync(STATE_FILE)) {
- stateCache = structuredClone(DEFAULT_STATE)
- return stateCache
+ stateCache = structuredClone(DEFAULT_STATE);
+ return stateCache;
}
- const content = await readFile(STATE_FILE, 'utf-8')
+ const content = await readFile(STATE_FILE, 'utf-8');
if (!isValidJSON(content)) {
- console.log(`⚠️ Corrupted or empty state file at ${STATE_FILE}, returning default state`)
- const backupPath = `${STATE_FILE}.corrupted.${Date.now()}`
- await writeFile(backupPath, content).catch(() => {})
- console.log(`📝 Backed up corrupted state to ${backupPath}`)
+ console.log(`⚠️ Corrupted or empty state file at ${STATE_FILE}, returning default state`);
+ const backupPath = `${STATE_FILE}.corrupted.${Date.now()}`;
+ await writeFile(backupPath, content).catch(() => {});
+ console.log(`📝 Backed up corrupted state to ${backupPath}`);
// Cleanup old corrupted backups (keep only 3 most recent)
- const cosDir = dirname(STATE_FILE)
- const files = await readdir(cosDir).catch(() => [])
+ const cosDir = dirname(STATE_FILE);
+ const files = await readdir(cosDir).catch(() => []);
const corrupted = files
.filter(f => f.startsWith('state.json.corrupted.'))
.sort()
- .reverse()
+ .reverse();
for (const old of corrupted.slice(3)) {
- await rm(join(cosDir, old)).catch(() => {})
+ await rm(join(cosDir, old)).catch(() => {});
}
if (corrupted.length > 3) {
- console.log(`🗑️ Cleaned up ${corrupted.length - 3} old corrupted state backups`)
+ console.log(`🗑️ Cleaned up ${corrupted.length - 3} old corrupted state backups`);
}
- stateCache = structuredClone(DEFAULT_STATE)
- return stateCache
+ stateCache = structuredClone(DEFAULT_STATE);
+ return stateCache;
}
- const state = safeJSONParse(content, null, { logError: true, context: 'CoS state' })
+ const state = safeJSONParse(content, null, { logError: true, context: 'CoS state' });
if (!state) {
- stateCache = structuredClone(DEFAULT_STATE)
- return stateCache
+ stateCache = structuredClone(DEFAULT_STATE);
+ return stateCache;
}
// Merge with defaults to ensure all fields exist
@@ -144,26 +144,26 @@ export async function loadState() {
config: { ...DEFAULT_CONFIG, ...state.config },
stats: { ...DEFAULT_STATE.stats, ...state.stats },
agents: state.agents ?? {}
- }
- return stateCache
+ };
+ return stateCache;
}
export async function saveState(state) {
- await ensureDirectories()
- stateCache = state
- const tmpFile = `${STATE_FILE}.tmp`
- await writeFile(tmpFile, JSON.stringify(state, null, 2))
- await rename(tmpFile, STATE_FILE)
+ await ensureDirectories();
+ stateCache = state;
+ const tmpFile = `${STATE_FILE}.tmp`;
+ await writeFile(tmpFile, JSON.stringify(state, null, 2));
+ await rename(tmpFile, STATE_FILE);
}
// Daemon state accessors — used by modules that need to check daemon status
// without importing cos.js (which would create circular deps)
-let _daemonRunning = false
+let _daemonRunning = false;
export function isDaemonRunning() {
- return _daemonRunning
+ return _daemonRunning;
}
export function setDaemonRunning(value) {
- _daemonRunning = value
+ _daemonRunning = value;
}