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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: surface scheduled job failures with a stack and structured log (#7549)
[._.]/ Adam Eivy293e66726460
diff --git a/server/lib/README.md b/server/lib/README.mdindex d104cee53d..ad3350d116 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -302,6 +302,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. || `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. || `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |+| `failureLogging.js` | `logFailureWithStack(prefix, error, logger = console.error)` — logs `${prefix}: ${message}` plus `error.stack` as a second argument, so a fire-and-forget failure (boot init, a scheduled event handler) keeps its source location instead of collapsing to one message-only line (#6934, #7549). || `fileCore.js` | Cross-cutting filesystem primitives (`atomicWrite`, `writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`, directory helpers, `parseFilesystemStats(stats)` → canonical/byte-alias metrics or `null`, bounded tail reads/watchers), time/format helpers, directory sizing, and SHA-256 helpers. || `familySettingsMap.js` | The merge rule every per-provider-family map in `data/settings.json` shares (plan prices, plan tiers) — `normalizeFamilyMap(raw, normalizeValue)` and `mergeFamilyMap(stored, patch, normalizeValue)`, which hold the absent-vs-present-but-empty contract in ONE place: an omitted family keeps its stored value, one sent empty is an intentional clear and is deleted. Each store supplies only its value normalizer. Pure. || `fileUtils.js` | Backward-compatible facade re-exporting the focused file utility modules so existing deep imports need no caller changes. |diff --git a/server/lib/failureLogging.js b/server/lib/failureLogging.jsnew file mode 100644index 0000000000..7bbafb0c24--- /dev/null+++ b/server/lib/failureLogging.js@@ -0,0 +1,13 @@+/**+ * Keep a fire-and-forget failure actionable. The message is useful for a quick+ * scan; the stack identifies the source location when the moment of failure is+ * the only time it's reproducible (#6934).+ *+ * @param {string} prefix - Short description of what failed+ * @param {Error|unknown} error - The caught error+ * @param {(...args: unknown[]) => void} [logger] - Defaults to console.error+ */+export function logFailureWithStack(prefix, error, logger = console.error) {+ const message = error?.message ?? String(error);+ logger(`${prefix}: ${message}`, error?.stack || '');+}diff --git a/server/lib/failureLogging.test.js b/server/lib/failureLogging.test.jsnew file mode 100644index 0000000000..98f9882732--- /dev/null+++ b/server/lib/failureLogging.test.js@@ -0,0 +1,44 @@+/**+ * Fire-and-forget failures must retain their source location (#6934, #7549).+ */++import { describe, it, expect, vi } from 'vitest';+import { logFailureWithStack } from './failureLogging.js';++describe('logFailureWithStack', () => {+ it('includes an Error stack alongside the failure message', () => {+ const error = vi.fn();++ logFailureWithStack('❌ Backup scheduler init failed', new Error('database unavailable'), error);++ expect(error).toHaveBeenCalledWith(+ '❌ Backup scheduler init failed: database unavailable',+ expect.stringContaining('Error: database unavailable'),+ );+ });++ it('supports a custom logger without dropping the stack', () => {+ const warn = vi.fn();+ const error = new Error('restore failed');++ logFailureWithStack('⚠️ tailcat restore failed', error, warn);++ expect(warn).toHaveBeenCalledWith(+ '⚠️ tailcat restore failed: restore failed',+ expect.stringContaining('Error: restore failed'),+ );+ });++ it('falls back to console.error and String(error) for a non-Error value', () => {+ const originalConsoleError = console.error;+ const spy = vi.fn();+ console.error = spy;+ try {+ logFailureWithStack('❌ Something failed', 'plain string reason');+ } finally {+ console.error = originalConsoleError;+ }++ expect(spy).toHaveBeenCalledWith('❌ Something failed: plain string reason', '');+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 2267fff106..4cc500ae1f 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -275,6 +275,7 @@ export * from './createNewestWinsGuard.js';export * from './dataRoot.js';export * from './downloadPreflight.js';export * from './agentInstructionsFile.js';+export * from './failureLogging.js';export * from './fileCore.js';export * as fileUtils from './fileUtils.js';export * from './fileWriteQueue.js';diff --git a/server/services/bootstrap.errorLogging.test.js b/server/services/bootstrap.errorLogging.test.jsdeleted file mode 100644index 4afd08f8f2..0000000000--- a/server/services/bootstrap.errorLogging.test.js+++ /dev/null@@ -1,47 +0,0 @@-/**- * Boot errors must retain their source location (#6934). This test extracts- * the small logger without importing bootstrap.js, whose module graph starts- * the real service wiring as a side effect of evaluation.- */--import { describe, it, expect, vi } from 'vitest';-import { runInNewContext } from 'node:vm';-import { readFileSync } from 'fs';-import { fileURLToPath } from 'url';-import { dirname, join } from 'path';-import { extractDeclaration } from '../lib/mirrorParity.js';--const __dirname = dirname(fileURLToPath(import.meta.url));-const source = readFileSync(join(__dirname, 'bootstrap.js'), 'utf-8').replace(/\r\n/g, '\n');--const loadLogger = (console) => runInNewContext(`- ${extractDeclaration(source, 'logBootstrapFailure')}- logBootstrapFailure;-`, { console, String });--describe('boot failure logging (#6934)', () => {- it('includes an Error stack with the boot failure message', () => {- const error = vi.fn();- const logBootstrapFailure = loadLogger({ error });-- logBootstrapFailure('❌ Backup scheduler init failed', new Error('database unavailable'));-- expect(error).toHaveBeenCalledWith(- '❌ Backup scheduler init failed: database unavailable',- expect.stringContaining('Error: database unavailable'),- );- });-- it('supports warning and log severity without dropping the stack', () => {- const warn = vi.fn();- const logBootstrapFailure = loadLogger({ error: vi.fn(), warn });- const error = new Error('restore failed');-- logBootstrapFailure('⚠️ tailcat restore failed', error, warn);-- expect(warn).toHaveBeenCalledWith(- '⚠️ tailcat restore failed: restore failed',- expect.stringContaining('Error: restore failed'),- );- });-});diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 935ecc0419..90e1f18c83 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -165,16 +165,7 @@ import * as fableLoomStore from './fableLoom/store.js';import { prerequisitesMetForRouting } from './providerPrerequisites.js';import { localCachedModelIds } from './localCachedModels.js';import { stopCodexAppServer } from './codexAppServer.js';--/**- * Keep boot failures actionable when a service rejects during fire-and-forget- * initialization. The message is useful for a quick scan; the stack identifies- * the source location when boot is the only time the failure is reproducible.- */-const logBootstrapFailure = (prefix, error, logger = console.error) => {- const message = error?.message ?? String(error);- logger(`${prefix}: ${message}`, error?.stack || '');-};+import { logFailureWithStack as logBootstrapFailure } from '../lib/failureLogging.js';/*** Pre-route boot. Everything a route handler may depend on being ready thediff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.jsindex ab52ace1e9..88df1eea52 100644--- a/server/services/bootstrap.shutdown.test.js+++ b/server/services/bootstrap.shutdown.test.js@@ -28,6 +28,10 @@ import { extractDeclaration, stripCommentsAndNormalize } from '../lib/mirrorPariconst __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');@@ -82,7 +86,8 @@ describe('bounded server shutdown', () => {const log = vi.fn();const error = vi.fn();const closeServer = runInNewContext(`- ${extractDeclaration(SRC, 'logBootstrapFailure')}+ ${extractDeclaration(FAILURE_LOGGING_SRC, 'logFailureWithStack').replace(/^export\s+/, '')}+ const logBootstrapFailure = logFailureWithStack;${extractDeclaration(SRC, 'withGrace')}${extractDeclaration(SRC, 'closeServer')}closeServer;diff --git a/server/services/createSettingsGatedSyncScheduler.js b/server/services/createSettingsGatedSyncScheduler.jsindex 4f4f2ad2f2..e260102462 100644--- a/server/services/createSettingsGatedSyncScheduler.js+++ b/server/services/createSettingsGatedSyncScheduler.js@@ -53,7 +53,14 @@ export function createSyncScheduler({ id, label, icon, source, getConfig, runSynconsole.log(`${icon} ${label} sync scheduler: disabled since registration — skipping run`);return;}- await runSync();+ const result = await runSync();+ // `runSync()` reports a detected failure by returning `{ ok: false, error }`+ // rather than throwing (#7549) — surface it as a failed scheduler run so+ // the event's lastError/consecutiveFailures reflect reality instead of a+ // permanently "successful" run.+ if (result?.ok === false) {+ throw new Error(result.error || `${label} sync reported failure`);+ }},metadata: { source },});diff --git a/server/services/createSettingsGatedSyncScheduler.test.js b/server/services/createSettingsGatedSyncScheduler.test.jsindex 3ad5e585d3..4b55f7ac7f 100644--- a/server/services/createSettingsGatedSyncScheduler.test.js+++ b/server/services/createSettingsGatedSyncScheduler.test.js@@ -89,4 +89,22 @@ describe('createSyncScheduler', () => {expect(scheduleMock.mock.calls[0][0].intervalMs).toBe(25 * 60 * 1000);expect(runSync).toHaveBeenCalledTimes(1);});++ it('throws when runSync reports a detected failure via { ok: false }, so the run is recorded failed (#7549)', async () => {+ const runSync = vi.fn(async () => ({ ok: false, error: 'Full Disk Access required' }));+ const { start } = build(vi.fn(async () => ({ enabled: true, intervalMinutes: 25 })), runSync);++ await start();++ await expect(scheduleMock.mock.calls[0][0].handler()).rejects.toThrow('Full Disk Access required');+ });++ it('does not throw when runSync succeeds with { ok: true }', async () => {+ const runSync = vi.fn(async () => ({ ok: true }));+ const { start } = build(vi.fn(async () => ({ enabled: true, intervalMinutes: 25 })), runSync);++ await start();++ await expect(scheduleMock.mock.calls[0][0].handler()).resolves.toBeUndefined();+ });});diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex 128860421e..8acdd61aa2 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -5,7 +5,8 @@* Replaces setInterval with more robust scheduling.*/-import { cosEvents } from './cosEvents.js'+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@@ -391,7 +392,10 @@ function schedule(config) {nextRunAt: null,lastRunAt: null,runCount: 0,- active: true+ active: true,+ lastRunSucceeded: null,+ lastError: null,+ consecutiveFailures: 0}// Calculate next run time@@ -511,13 +515,13 @@ function rearm(event) {try {updateNextRunTime(event)} catch (err) {- console.error(`❌ Event ${event.id} could not compute its next run (${err.message}) - schedule stopped`)+ emitLog('error', `Event ${event.id} could not compute its next run (${err.message}) - schedule stopped`, { eventId: event.id, type: event.type })deactivate(event)return}if (!event.nextRunAt) {- console.error(`❌ Event ${event.id} has no next run time - schedule stopped`)+ emitLog('error', `Event ${event.id} has no next run time - schedule stopped`, { eventId: event.id, type: event.type })deactivate(event)return}@@ -564,10 +568,22 @@ async function runEvent(event) {try {await event.handler(event)+ event.lastRunSucceeded = true+ event.lastError = null+ event.consecutiveFailures = 0} catch (err) {success = falseerror = err.message- console.error(`⚠️ Event ${event.id} failed: ${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+ })} finally {recordEventHistory(event, { startTime, success, error })@@ -697,6 +713,9 @@ function getEvent(id) {nextRunAt: event.nextRunAt,lastRunAt: event.lastRunAt,runCount: event.runCount,+ lastRunSucceeded: event.lastRunSucceeded,+ lastError: event.lastError,+ consecutiveFailures: event.consecutiveFailures,metadata: event.metadata}}@@ -741,7 +760,7 @@ function getStats() {totalRuns: eventHistory.length,recentSuccessRate: recent.length > 0? ((recent.filter(h => h.success).length / recent.length) * 100).toFixed(1) + '%'- : '100%'+ : null}}diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.jsindex cbf9d0f969..08407919a2 100644--- a/server/services/eventScheduler.test.js+++ b/server/services/eventScheduler.test.js@@ -424,6 +424,62 @@ describe('schedule() lifecycle with fake timers', () => {expect(handler).toHaveBeenCalledTimes(2); // recurring run still happened});+ it('logs the stack and emits a structured error carrying the event id when a handler throws (#7549)', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const logListener = vi.fn();+ cosEvents.on('log', logListener);++ try {+ const handler = vi.fn().mockRejectedValue(new Error('boom'));+ schedule({ id: 'fail-log-1', type: 'once', delayMs: 1000, handler });++ 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);+ } finally {+ cosEvents.off('log', logListener);+ consoleError.mockRestore();+ }+ });++ it('tracks lastRunSucceeded/lastError/consecutiveFailures across failing and passing runs', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ try {+ const handler = vi.fn()+ .mockRejectedValueOnce(new Error('first failure'))+ .mockRejectedValueOnce(new Error('second failure'))+ .mockResolvedValueOnce(undefined);+ schedule({ id: 'failure-state-1', type: 'interval', intervalMs: 1000, handler });++ await vi.advanceTimersByTimeAsync(1000);+ let event = getEvent('failure-state-1');+ expect(event.lastRunSucceeded).toBe(false);+ expect(event.lastError).toBe('first failure');+ expect(event.consecutiveFailures).toBe(1);++ await vi.advanceTimersByTimeAsync(1000);+ event = getEvent('failure-state-1');+ expect(event.lastError).toBe('second failure');+ expect(event.consecutiveFailures).toBe(2);++ await vi.advanceTimersByTimeAsync(1000);+ event = getEvent('failure-state-1');+ expect(event.lastRunSucceeded).toBe(true);+ expect(event.lastError).toBeNull();+ expect(event.consecutiveFailures).toBe(0);+ } finally {+ consoleError.mockRestore();+ }+ });+it('records a successful run in history with a non-negative duration', async () => {const handler = vi.fn().mockResolvedValue(undefined);schedule({ id: 'success-1', type: 'once', delayMs: 1000, handler });@@ -529,3 +585,19 @@ describe('schedule() lifecycle with fake timers', () => {expect(stats.byType).toEqual({ once: 1, interval: 1 });});});++// A fresh module instance is required here: eventHistory is module-level state+// that every other test in this file has already appended to by the time this+// 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');+ expect(fresh.getStats().recentSuccessRate).toBeNull();+ });+});