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

simplify: collapse duplicate failure logging into emitLog (#7549)

[._.]/ Adam Eivyb66c51ab144e
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
index 88df1eea52..55ed3edc1f 100644
--- a/server/services/bootstrap.shutdown.test.js
+++ b/server/services/bootstrap.shutdown.test.js
@@ -25,13 +25,10 @@ import { dirname, join } from 'path';
// anchor" version silently slices the wrong region the moment a signature grows
// a destructured or defaulted parameter.
import { extractDeclaration, stripCommentsAndNormalize } from '../lib/mirrorParity.js';
+import { logFailureWithStack } from '../lib/failureLogging.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const SRC = readFileSync(join(__dirname, 'bootstrap.js'), 'utf-8').replace(/\r\n/g, '\n');
-// logBootstrapFailure now lives in ../lib/failureLogging.js (#7549) — bootstrap.js
-// only imports it, so it's mirrored from its own source and aliased back to the
-// name closeServer's body references as a free variable.
-const FAILURE_LOGGING_SRC = readFileSync(join(__dirname, '..', 'lib', 'failureLogging.js'), 'utf-8').replace(/\r\n/g, '\n');
describe('shutdown handler — host-restart bookkeeping (#3202)', () => {
const shutdownBody = extractDeclaration(SRC, 'shutdown');
@@ -86,12 +83,10 @@ describe('bounded server shutdown', () => {
const log = vi.fn();
const error = vi.fn();
const closeServer = runInNewContext(`
- ${extractDeclaration(FAILURE_LOGGING_SRC, 'logFailureWithStack').replace(/^export\s+/, '')}
- const logBootstrapFailure = logFailureWithStack;
${extractDeclaration(SRC, 'withGrace')}
${extractDeclaration(SRC, 'closeServer')}
closeServer;
- `, { console: { log, error }, setTimeout });
+ `, { console: { log, error }, setTimeout, logBootstrapFailure: logFailureWithStack });
return { closeServer, log, error };
};
diff --git a/server/services/cosEvents.js b/server/services/cosEvents.js
index 3504d5820f..0e82e11517 100644
--- a/server/services/cosEvents.js
+++ b/server/services/cosEvents.js
@@ -15,7 +15,9 @@ cosEvents.setMaxListeners(60);
* Emit a log event for UI display
* @param {string} level - Log level: 'info', 'warn', 'error', 'success', 'debug'
* @param {string} message - Log message
- * @param {Object} data - Additional data to include in log entry
+ * @param {Object} data - Additional data to include in log entry. A `stack`
+ * string is also appended to the console line (#7549), so a caller reporting
+ * a caught error doesn't need a second console.error call to keep it.
* @param {string} prefix - Optional prefix for console output (e.g., 'SelfImprovement')
*/
export function emitLog(level, message, data = {}, prefix = '') {
@@ -30,7 +32,9 @@ export function emitLog(level, message, data = {}, prefix = '') {
const emoji = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : level === 'debug' ? '🔍' : 'ℹ️';
const prefixStr = prefix ? ` ${prefix}` : '';
const logFn = level === 'error' ? console.error : level === 'warn' ? console.warn : console.log;
- logFn(`${emoji}${prefixStr} ${message}`);
+ const consoleArgs = [`${emoji}${prefixStr} ${message}`];
+ if (data.stack) consoleArgs.push(data.stack);
+ logFn(...consoleArgs);
}
cosEvents.emit('log', logEntry);
}
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.js
index 8acdd61aa2..36c7e51d63 100644
--- a/server/services/eventScheduler.js
+++ b/server/services/eventScheduler.js
@@ -6,7 +6,6 @@
*/
import { cosEvents, emitLog } from './cosEvents.js'
-import { logFailureWithStack } from '../lib/failureLogging.js'
import { getLocalParts } from '../lib/timezone.js'
import { recurrenceRuleSchema } from '../lib/recurrenceValidation.js'
// Syntax/range validation is shared with every save boundary and the browser
@@ -568,23 +567,21 @@ async function runEvent(event) {
try {
await event.handler(event)
- event.lastRunSucceeded = true
- event.lastError = null
- event.consecutiveFailures = 0
} catch (err) {
success = false
error = err.message
- event.lastRunSucceeded = false
- event.lastError = error
- event.consecutiveFailures += 1
- logFailureWithStack(`⚠️ Event ${event.id} failed`, err)
emitLog('error', `Event ${event.id} failed: ${err.message}`, {
eventId: event.id,
type: event.type,
source: event.metadata?.source,
- durationMs: Date.now() - startTime
+ durationMs: Date.now() - startTime,
+ stack: err.stack
})
} finally {
+ event.lastRunSucceeded = success
+ event.lastError = error
+ event.consecutiveFailures = success ? 0 : event.consecutiveFailures + 1
+
recordEventHistory(event, { startTime, success, error })
// A synchronous listener that throws must not cost the schedule its re-arm
diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.js
index 08407919a2..1249ee68cc 100644
--- a/server/services/eventScheduler.test.js
+++ b/server/services/eventScheduler.test.js
@@ -435,14 +435,13 @@ describe('schedule() lifecycle with fake timers', () => {
await vi.advanceTimersByTimeAsync(1000);
- // A stack-bearing console line exists among whatever else logged.
- expect(consoleError.mock.calls.some(call =>
- call.some(arg => typeof arg === 'string' && arg.includes('Event fail-log-1 failed: boom')) &&
- call.some(arg => typeof arg === 'string' && arg.includes('Error: boom'))
- )).toBe(true);
-
- const errorLogs = logListener.mock.calls.map(([entry]) => entry).filter(entry => entry.level === 'error');
- expect(errorLogs.some(entry => entry.eventId === 'fail-log-1' && entry.message.includes('boom'))).toBe(true);
+ expect(consoleError).toHaveBeenCalledWith(
+ expect.stringContaining('Event fail-log-1 failed: boom'),
+ expect.stringContaining('Error: boom'),
+ );
+
+ const [entry] = logListener.mock.calls.map(([e]) => e).filter(e => e.level === 'error');
+ expect(entry).toMatchObject({ eventId: 'fail-log-1', message: expect.stringContaining('boom') });
} finally {
cosEvents.off('log', logListener);
consoleError.mockRestore();
@@ -591,10 +590,6 @@ describe('schedule() lifecycle with fake timers', () => {
// describe runs, so getStats() from the shared import can never observe a truly
// empty ring (#7549).
describe('getStats().recentSuccessRate on an empty ring', () => {
- afterEach(() => {
- vi.resetModules();
- });
-
it('is null, not "100%", when no run has been recorded', async () => {
vi.resetModules();
const fresh = await import('./eventScheduler.js');