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: preserve runtime records when saved JSON cannot be read (#6971)

[._.]/ Adam Eivy1a44346e3230
diff --git a/server/services/agentRunReconciler.js b/server/services/agentRunReconciler.js
index 2f4dc7c5c6..d35db905a6 100644
--- a/server/services/agentRunReconciler.js
+++ b/server/services/agentRunReconciler.js
@@ -51,6 +51,8 @@ const asRecord = (value) =>
const readRecord = async (runId) => {
const path = metadataPath(runId);
+ // Non-strict exception: unreadable metadata becomes null; repair planning
+ // skips it (including the final re-read), so no default is written back.
return path ? asRecord(await readJSONFile(path, null)) : null;
};
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index e221ddb570..567f0a6477 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -104,6 +104,8 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
const runDir = join(RUNS_DIR, runId);
const metaPath = join(runDir, 'metadata.json');
+ // Non-strict exception: unreadable metadata aborts completion before either
+ // metadata or output is written; it never becomes a saveable default.
const metadata = await readJSONFile(metaPath, null);
if (!metadata) return;
if (metadata.endTime) return;
diff --git a/server/services/autonomousJobs/store.js b/server/services/autonomousJobs/store.js
index a141f86559..97d70e3895 100644
--- a/server/services/autonomousJobs/store.js
+++ b/server/services/autonomousJobs/store.js
@@ -26,7 +26,7 @@ async function initJobs() {
await ensureDir(DATA_DIR)
await syncSkillTemplatesFromSample()
- const loaded = await readJSONFile(JOBS_FILE, null)
+ const loaded = await readJSONFile(JOBS_FILE, null, { strict: true })
if (!loaded) {
const initial = createDefaultJobsData()
await migrateScriptsState(initial)
@@ -96,10 +96,13 @@ async function syncSkillTemplatesFromSample() {
*/
async function loadJobs() {
if (!initPromise) {
- initPromise = initJobs()
+ initPromise = initJobs().catch((err) => {
+ initPromise = null
+ throw err
+ })
}
await initPromise
- const loaded = await readJSONFile(JOBS_FILE, null)
+ const loaded = await readJSONFile(JOBS_FILE, null, { strict: true })
if (!loaded) return createDefaultJobsData()
const { data } = mergeWithDefaults(loaded)
return data
diff --git a/server/services/featureAgents.js b/server/services/featureAgents.js
index c57f2c9516..f4809646cc 100644
--- a/server/services/featureAgents.js
+++ b/server/services/featureAgents.js
@@ -43,7 +43,7 @@ export function calculateBackoff(consecutiveIdles) {
* Read the feature agents data file
*/
async function readData() {
- const data = await readJSONFile(FA_FILE, { version: 1, lastUpdated: new Date().toISOString(), agents: [] });
+ const data = await readJSONFile(FA_FILE, { version: 1, lastUpdated: new Date().toISOString(), agents: [] }, { strict: true });
return data;
}
@@ -459,6 +459,7 @@ export async function getFeatureAgentRuns(id, limit = 20) {
// independent small JSON reads, so a sequential loop needlessly serializes
// disk latency on the run-history endpoint.
const loaded = await Promise.all(
+ // Read-only run history: unreadable entries are filtered, never rewritten.
runFiles.map(file => readJSONFile(join(runDir, file), null))
);
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index 94123cbb7c..31d9d31e44 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -74,7 +74,7 @@ const perRun = createKeyCachedQueue();
let retryTimer = null;
export async function listMaintenanceRuns() {
- const loaded = await readJSONFile(runsFile(), null);
+ const loaded = await readJSONFile(runsFile(), null, { strict: true });
return Array.isArray(loaded?.runs) ? loaded.runs : [];
}
diff --git a/server/services/modelPersonality.js b/server/services/modelPersonality.js
index c651a5e2a3..6efedc9552 100644
--- a/server/services/modelPersonality.js
+++ b/server/services/modelPersonality.js
@@ -63,7 +63,7 @@ export const getSettings = settingsStore.get;
export const updateSettings = settingsStore.update;
export async function getHistory(limit) {
- const stored = await readJSONFile(resultsFile(), []);
+ const stored = await readJSONFile(resultsFile(), [], { strict: true });
const list = Array.isArray(stored) ? stored : [];
return typeof limit === 'number' ? list.slice(0, limit) : list;
}
diff --git a/server/services/rounds.js b/server/services/rounds.js
index 9c8197bc8e..147feb7ed5 100644
--- a/server/services/rounds.js
+++ b/server/services/rounds.js
@@ -512,12 +512,12 @@ const seedTemplate = (id) => SEED_ROUNDS.find((s) => s.id === id) || null;
// is re-entrancy hygiene, not a multi-actor lock (see AGENTS.md Security Model).
const enqueue = createFileWriteQueue();
-// Pure read + sanitize — NO write side effect. When the file is absent or
-// malformed, returns the seed in-memory without persisting it. Mutations call
-// this inside their enqueue() so the read-modify-write cycle never re-enters
+// Pure read + sanitize — NO write side effect. An absent file or a parsed
+// legacy shape without rounds returns the seed in memory. Unreadable bytes
+// reject. Mutations call this inside enqueue() so the cycle never re-enters
// the queue (which would deadlock).
async function readRounds() {
- const state = await readJSONFile(STATE_PATH, null, { allowArray: false });
+ const state = await readJSONFile(STATE_PATH, null, { allowArray: false, strict: true });
if (!state || !Array.isArray(state.rounds)) {
return SEED_ROUNDS.map(sanitizeRound).filter(Boolean);
}
@@ -529,14 +529,14 @@ async function readRounds() {
// as mutations and re-checks inside the queue, so a create that landed first
// can't be clobbered by a late seed write (read-path lazy-init race).
export async function listRounds() {
- const state = await readJSONFile(STATE_PATH, null, { allowArray: false });
+ const state = await readJSONFile(STATE_PATH, null, { allowArray: false, strict: true });
if (state && Array.isArray(state.rounds)) {
return state.rounds.map(sanitizeRound).filter(Boolean);
}
return enqueue(async () => {
// Re-check inside the queue: a queued create may have already written the
// file (with seed + new song). If so, don't overwrite it with bare seed.
- const fresh = await readJSONFile(STATE_PATH, null, { allowArray: false });
+ const fresh = await readJSONFile(STATE_PATH, null, { allowArray: false, strict: true });
if (fresh && Array.isArray(fresh.rounds)) {
return fresh.rounds.map(sanitizeRound).filter(Boolean);
}
diff --git a/server/services/runtimeStoreSafety.test.js b/server/services/runtimeStoreSafety.test.js
new file mode 100644
index 0000000000..093efd0c28
--- /dev/null
+++ b/server/services/runtimeStoreSafety.test.js
@@ -0,0 +1,155 @@
+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { dirname, join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const disk = vi.hoisted(() => {
+ const { mkdtempSync } = require('fs');
+ const { tmpdir } = require('os');
+ const { join } = require('path');
+ return { root: mkdtempSync(join(tmpdir(), 'runtime-store-safety-')), fault: null };
+});
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ readFile: (...args) => {
+ if (args[0] === disk.fault) return Promise.reject(Object.assign(new Error('injected read fault'), { code: 'EACCES' }));
+ return actual.readFile(...args);
+ }
+ };
+});
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: disk.root, extraOverrides: { root: disk.root } }));
+vi.mock('./apps.js', () => ({ getAppById: vi.fn(), getAllApps: vi.fn(), PORTOS_APP_ID: 'self' }));
+vi.mock('./git.js', () => ({ getBranch: vi.fn(), getStatus: vi.fn(), isRepo: vi.fn() }));
+vi.mock('./shell.js', () => ({ listAllSessions: vi.fn(() => []) }));
+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn() }));
+vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn(), on: vi.fn() }, emitLog: vi.fn() }));
+vi.mock('./quotaBurnInvoke.js', () => ({ getQuotaBurnTaskCatalog: vi.fn(), invokeQuotaBurnStep: vi.fn() }));
+vi.mock('./quotaBurnSequence.js', () => ({ ACTIVE_TASK_STATUSES: new Set(), probeSequenceDrain: vi.fn(), sequenceStepShapeReason: vi.fn() }));
+vi.mock('./promptRunner.js', () => ({ resolveProviderAndModel: vi.fn(), runPromptThroughProvider: vi.fn(), assertProvider: vi.fn() }));
+vi.mock('./promptService.js', () => ({ buildPrompt: vi.fn() }));
+vi.mock('./digital-twin-meta.js', () => ({ loadMeta: vi.fn() }));
+vi.mock('./notifications.js', () => ({ addNotification: vi.fn(async () => ({})), NOTIFICATION_TYPES: {}, PRIORITY_LEVELS: {} }));
+
+let timers;
+
+const cases = [
+ {
+ name: 'autonomous jobs', path: 'cos/autonomous-jobs.json',
+ load: () => import('./autonomousJobs/store.js'),
+ read: svc => svc.loadJobs(),
+ mutate: async svc => { const data = await svc.loadJobs(); data.auditMarker = true; await svc.saveJobs(data); },
+ seed: { jobs: [{ id: 'keep', name: 'Custom job', enabled: false }], version: 1 },
+ kept: data => data.jobs.some(job => job.id === 'keep')
+ },
+ {
+ name: 'feature agents', path: 'cos/feature-agents.json',
+ load: () => import('./featureAgents.js'),
+ read: svc => svc.getAllFeatureAgents(),
+ mutate: svc => svc.createFeatureAgent({ name: 'New agent' }),
+ seed: { version: 1, agents: [{ id: 'keep', name: 'Existing agent' }] },
+ kept: data => data.agents.some(agent => agent.id === 'keep')
+ },
+ {
+ name: 'maintenance runs', path: 'cos/maintenance-runs.json',
+ load: () => import('./maintenanceRun.js'),
+ read: svc => svc.listMaintenanceRuns(),
+ mutate: svc => svc.stopMaintenanceRun('stop'),
+ seed: { runs: [{ id: 'keep', status: 'completed' }, { id: 'stop', status: 'running' }] },
+ kept: data => data.runs.some(run => run.id === 'keep')
+ },
+ {
+ name: 'model personality history', path: 'model-personality/results.json',
+ load: () => import('./modelPersonality.js'),
+ read: svc => svc.getHistory(),
+ mutate: svc => svc.deleteResult('delete'),
+ seed: [{ runId: 'keep' }, { runId: 'delete' }],
+ kept: data => data.some(record => record.runId === 'keep')
+ },
+ {
+ name: 'rounds', path: 'rounds.json',
+ load: () => import('./rounds.js'),
+ read: svc => svc.listRounds(),
+ mutate: svc => svc.createRound({ title: 'New song' }),
+ seed: { rounds: [{ id: 'keep', title: 'Existing song' }] },
+ kept: data => data.rounds.some(round => round.id === 'keep')
+ },
+ {
+ name: 'task schedule', path: 'cos/task-schedule.json',
+ load: () => import('./taskScheduleStore.js'),
+ read: svc => svc.loadSchedule(),
+ mutate: svc => svc.updateSchedule(data => { data.auditMarker = true; return { changed: true }; }),
+ seed: { version: 2, tasks: {}, executions: { keep: { count: 7 } } },
+ kept: data => data.executions.keep.count === 7
+ },
+ {
+ name: 'task templates', path: 'cos/task-templates.json',
+ load: () => import('./taskTemplates.js'),
+ read: svc => svc.getAllTemplates(),
+ mutate: svc => svc.createTemplate({ name: 'New template' }),
+ seed: { version: 1, userTemplates: [{ id: 'keep', name: 'Existing template' }], usage: { keep: 3 } },
+ kept: data => data.userTemplates.some(template => template.id === 'keep') && data.usage.keep === 3
+ },
+ {
+ name: 'workspace contexts', path: 'workspace-contexts.json',
+ load: () => import('./workspaceContext.js'),
+ read: svc => svc.getSavedContext('keep'),
+ mutate: svc => svc.deleteContext('delete'),
+ seed: { contexts: { keep: { branch: 'existing' }, delete: { branch: 'old' } } },
+ kept: data => data.contexts.keep.branch === 'existing'
+ }
+];
+
+afterEach(() => { disk.fault = null; timers?.__resetVoiceTimers(); });
+afterAll(() => rm(disk.root, { recursive: true, force: true }));
+
+describe('durable runtime write-back boundaries', () => {
+ for (const boundary of cases) {
+ it(`${boundary.name} preserves unreadable bytes, retries repaired input, and supports absent files`, async () => {
+ // Load only this boundary: focused test-name runs do not instantiate
+ // unrelated service graphs, whose external effects are stubbed above.
+ const svc = await boundary.load();
+ const path = join(disk.root, boundary.path);
+ await mkdir(dirname(path), { recursive: true });
+ // Each store must reject the complete read→mutation path, not only a
+ // helper. Exercise both parse failures and a portable injected I/O fault.
+ for (const bytes of ['{truncated', '', JSON.stringify(boundary.seed)]) {
+ await writeFile(path, bytes);
+ disk.fault = bytes.startsWith('{truncated') || bytes === '' ? null : path;
+ await expect(boundary.mutate(svc)).rejects.toThrow(/Unreadable JSON file/);
+ disk.fault = null;
+ expect(await readFile(path, 'utf8')).toBe(bytes);
+ }
+ // No module reset: the failed jobs initialization and write tails must
+ // recover when the user repairs the file, preserving unrelated records.
+ await writeFile(path, JSON.stringify(boundary.seed));
+ await boundary.mutate(svc);
+ expect(boundary.kept(JSON.parse(await readFile(path, 'utf8')))).toBe(true);
+ await rm(path);
+ await expect(boundary.read(svc)).resolves.toBeDefined();
+ await expect(boundary.mutate(svc)).resolves.not.toThrow();
+ });
+ }
+
+ it('timer scheduling refuses a failed restore and retries without losing pending reminders', async () => {
+ timers = await import('./voice/timers.js');
+ const path = join(disk.root, 'voice-timers.json');
+ for (const bytes of ['', '{truncated', '{"version":1,"timers":[]}']) {
+ await writeFile(path, bytes);
+ disk.fault = bytes.includes('version') ? path : null;
+ await expect(timers.initVoiceTimers()).rejects.toThrow(/Unreadable JSON file/);
+ await expect(timers.scheduleTimer({ totalMs: 60_000, label: 'New reminder' })).rejects.toThrow(/Unreadable JSON file/);
+ disk.fault = null;
+ expect(await readFile(path, 'utf8')).toBe(bytes);
+ }
+ await writeFile(path, JSON.stringify({ version: 1, timers: [{ id: 'keep', label: 'Existing reminder', fireAt: Date.now() + 120_000 }] }));
+ await timers.scheduleTimer({ totalMs: 60_000, label: 'New reminder' });
+ expect(JSON.parse(await readFile(path, 'utf8')).timers.map(timer => timer.label)).toEqual(['Existing reminder', 'New reminder']);
+ timers.__resetVoiceTimers();
+ await rm(path);
+ await timers.scheduleTimer({ totalMs: 60_000, label: 'First reminder' });
+ expect(JSON.parse(await readFile(path, 'utf8')).timers).toHaveLength(1);
+ });
+});
diff --git a/server/services/taskScheduleStore.js b/server/services/taskScheduleStore.js
index befdc5ae4a..97bda9deb6 100644
--- a/server/services/taskScheduleStore.js
+++ b/server/services/taskScheduleStore.js
@@ -176,7 +176,7 @@ function migrateLegacyPrReviewerPipeline(config) {
async function readSchedule() {
await ensureDataDir();
- const loaded = await readJSONFile(SCHEDULE_FILE, null);
+ const loaded = await readJSONFile(SCHEDULE_FILE, null, { strict: true });
if (!loaded) {
return { schedule: { ...DEFAULT_SCHEDULE }, needsSave: false };
}
diff --git a/server/services/taskTemplates.js b/server/services/taskTemplates.js
index dfd7cd6dda..765a620f9f 100644
--- a/server/services/taskTemplates.js
+++ b/server/services/taskTemplates.js
@@ -52,7 +52,7 @@ const DEFAULT_STATE = {
* Load templates state
*/
async function loadState() {
- const data = await readJSONFile(TEMPLATES_FILE);
+ const data = await readJSONFile(TEMPLATES_FILE, null, { strict: true });
if (!data) return { ...DEFAULT_STATE };
return {
...DEFAULT_STATE,
diff --git a/server/services/usageBackfill.js b/server/services/usageBackfill.js
index f9a6550806..db4c6885ff 100644
--- a/server/services/usageBackfill.js
+++ b/server/services/usageBackfill.js
@@ -24,6 +24,8 @@ const publicJob = () => ({ ...job });
const markRunMetadata = async (corrections) => {
for (const correction of corrections) {
+ // Non-strict exception: skip an unreadable run rather than replacing it
+ // with a default; later backfills can retry the repaired metadata.
const metadata = await readJSONFile(correction.metadataPath, null);
if (!metadata) continue;
const now = new Date().toISOString();
diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.js
index 57d0dd6b39..0aa852dd28 100644
--- a/server/services/usageReconciler.js
+++ b/server/services/usageReconciler.js
@@ -432,6 +432,7 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
// chat_history.jsonl carries no timestamps, so the session is placed by
// summary.json and billed whole or not at all; the session-level claim
// is what stops two overlapping runs from each taking it.
+ // Read-only transcript input: no write-back to the summary file.
const summary = await readJSONFile(join(sessionDir, 'summary.json'), null);
if (!summary) continue;
const startedMs = Date.parse(summary.created_at || '');
@@ -773,6 +774,8 @@ export async function recordCompletedRunUsage(metadata, output, { home = homedir
if (!metadata?.id) return;
await markUsageRunReconciled(metadata.id);
const metadataPath = join(PATHS.runs, metadata.id, 'metadata.json');
+ // Non-strict exception: missing/unreadable metadata skips the marker
+ // write; the usage ledger remains authoritative for the accounting.
const persisted = await readJSONFile(metadataPath, null);
if (!persisted) return;
persisted.usageReconciled = true;
diff --git a/server/services/voice/timers.js b/server/services/voice/timers.js
index 5b8f47a010..7abbcbba5b 100644
--- a/server/services/voice/timers.js
+++ b/server/services/voice/timers.js
@@ -97,19 +97,23 @@ function findDuplicate(label, fireAt) {
* Returns `null` for an out-of-range duration (callers validate first; this is
* a defensive guard so a bad value never arms a runaway/zero timer).
*/
-export function scheduleTimer({ totalMs, label } = {}) {
+export async function scheduleTimer({ totalMs, label } = {}) {
if (!Number.isFinite(totalMs) || totalMs < 1000 || totalMs > MAX_DURATION_MS) return null;
+ // A new snapshot must include restored timers; a failed restore must not
+ // arm new work or overwrite the unreadable store. Retry after repair.
+ await initVoiceTimers();
const fireAt = Date.now() + totalMs;
const dup = findDuplicate(label, fireAt);
if (dup) return { id: dup.id, fireAt: dup.fireAt, deduped: true };
const timer = { id: randomUUID(), label, fireAt, createdAt: Date.now() };
arm(timer);
- persist();
+ await persist();
return { id: timer.id, fireAt, deduped: false };
}
// Idempotency guard so a double-call (re-init, tests) can't double-arm.
let initialized = false;
+let initPromise = null;
/**
* Re-arm persisted timers at boot. Any that came due while the process was down
@@ -118,8 +122,19 @@ let initialized = false;
*/
export async function initVoiceTimers() {
if (initialized) return { skipped: true };
- initialized = true;
- const stored = await readJSONFile(STORE_PATH, { version: 1, timers: [] });
+ if (!initPromise) {
+ initPromise = restoreTimers().then((result) => {
+ initialized = true;
+ return result;
+ }).finally(() => {
+ initPromise = null;
+ });
+ }
+ return initPromise;
+}
+
+async function restoreTimers() {
+ const stored = await readJSONFile(STORE_PATH, { version: 1, timers: [] }, { strict: true });
const list = Array.isArray(stored?.timers) ? stored.timers : [];
const now = Date.now();
let armed = 0;
@@ -141,9 +156,7 @@ export async function initVoiceTimers() {
createdAt: typeof rec.createdAt === 'number' ? rec.createdAt : now,
};
// Skip a record already handled, so it can't double-notify:
- // - `active.has` — a timer_set scheduled post-boot (during init's async
- // read; routes are up before this fire-and-forget init settles) is live
- // in memory and authoritative.
+ // - `active.has` — an already restored record is live in memory.
// - `seen.has` — a duplicate id earlier in a corrupt/hand-edited store.
// `active` alone misses this when the records are OVERDUE, since overdue
// timers fire-and-drop without being added to `active`.
@@ -169,4 +182,5 @@ export function __resetVoiceTimers() {
for (const t of active.values()) clearTimeout(t.handle);
active.clear();
initialized = false;
+ initPromise = null;
}
diff --git a/server/services/voice/timers.test.js b/server/services/voice/timers.test.js
index 596157a262..c781280ed8 100644
--- a/server/services/voice/timers.test.js
+++ b/server/services/voice/timers.test.js
@@ -38,7 +38,7 @@ describe('scheduleTimer', () => {
it('arms a timer that raises a notification when it elapses', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
- const res = scheduleTimer({ totalMs: 600000, label: 'call mom' });
+ const res = await scheduleTimer({ totalMs: 600000, label: 'call mom' });
expect(res.deduped).toBe(false);
expect(typeof res.id).toBe('string');
await vi.advanceTimersByTimeAsync(600000);
@@ -53,7 +53,7 @@ describe('scheduleTimer', () => {
it('persists a pending timer (handle stripped) and clears it after firing', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
- scheduleTimer({ totalMs: 600000, label: 'tea' });
+ await scheduleTimer({ totalMs: 600000, label: 'tea' });
await tick(); await tick(); // let the schedule's queued persist() write run
const afterSchedule = atomicWriteMock.mock.calls.at(-1)[1];
expect(afterSchedule.timers).toHaveLength(1);
@@ -65,19 +65,19 @@ describe('scheduleTimer', () => {
vi.useRealTimers();
});
- it('rejects an out-of-range duration without arming anything', () => {
+ it('rejects an out-of-range duration without arming anything', async () => {
vi.useFakeTimers();
- expect(scheduleTimer({ totalMs: 500, label: 'too short' })).toBeNull();
- expect(scheduleTimer({ totalMs: 25 * 60 * 60 * 1000, label: 'too long' })).toBeNull();
- expect(scheduleTimer({ totalMs: NaN, label: 'nan' })).toBeNull();
+ expect(await scheduleTimer({ totalMs: 500, label: 'too short' })).toBeNull();
+ expect(await scheduleTimer({ totalMs: 25 * 60 * 60 * 1000, label: 'too long' })).toBeNull();
+ expect(await scheduleTimer({ totalMs: NaN, label: 'nan' })).toBeNull();
vi.useRealTimers();
});
it('dedups a re-issued identical timer but keeps a distinct label / out-of-window one', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
- const a = scheduleTimer({ totalMs: 600000, label: 'tea' });
- const b = scheduleTimer({ totalMs: 600000, label: 'tea' });
+ const a = await scheduleTimer({ totalMs: 600000, label: 'tea' });
+ const b = await scheduleTimer({ totalMs: 600000, label: 'tea' });
expect(b.deduped).toBe(true);
expect(b.id).toBe(a.id);
@@ -88,12 +88,12 @@ describe('scheduleTimer', () => {
expect(snap.timers.filter((t) => t.label === 'tea')).toHaveLength(1);
// Different label → not a duplicate.
- expect(scheduleTimer({ totalMs: 600000, label: 'eggs' }).deduped).toBe(false);
+ expect((await scheduleTimer({ totalMs: 600000, label: 'eggs' })).deduped).toBe(false);
// Same label but fireAt now 20s past the original → outside the dedup
// window → a genuinely new timer.
vi.advanceTimersByTime(20000);
- expect(scheduleTimer({ totalMs: 600000, label: 'tea' }).deduped).toBe(false);
+ expect((await scheduleTimer({ totalMs: 600000, label: 'tea' })).deduped).toBe(false);
vi.useRealTimers();
});
});
@@ -153,29 +153,16 @@ describe('initVoiceTimers', () => {
expect(second).toEqual({ skipped: true });
});
- it('skips a persisted record whose id is already live in memory (boot race, both branches)', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-05-26T12:00:00Z'));
- const now = Date.now();
- // Simulate the race: a timer_set is scheduled (and persisted) while boot
- // init is still mid-read, so init reads the same id back. Mark the persisted
- // copy OVERDUE to exercise the overdue branch — the in-memory timer is
- // authoritative, so init must skip the record entirely (neither fire it as
- // overdue nor re-arm a second handle), leaving exactly one live timer.
- const scheduled = scheduleTimer({ totalMs: 300000, label: 'overlap' });
- await tick(); await tick(); // let scheduleTimer's persist settle first
- storeRef.value = {
- version: 1,
- timers: [{ id: scheduled.id, label: 'overlap', fireAt: now - 1000, createdAt: now }],
- };
- const res = await initVoiceTimers();
- expect(res).toEqual({ armed: 0, fired: 0 }); // skipped — not fired-as-overdue, not re-armed
- addNotificationMock.mockClear();
- await vi.advanceTimersByTimeAsync(300000);
- expect(addNotificationMock).toHaveBeenCalledTimes(1); // the one live timer fires once
- expect(addNotificationMock).toHaveBeenCalledWith(
- expect.objectContaining({ title: '⏰ overlap', metadata: expect.objectContaining({ timerId: scheduled.id }) })
- );
- vi.useRealTimers();
+ it('waits for a concurrent boot restore before scheduling and persisting a new timer', async () => {
+ let finishRead;
+ readJSONFileMock.mockImplementationOnce(() => new Promise(resolve => { finishRead = resolve; }));
+ const initializing = initVoiceTimers();
+ const scheduling = scheduleTimer({ totalMs: 300000, label: 'new' });
+ await tick();
+ expect(atomicWriteMock).not.toHaveBeenCalled();
+ finishRead({ version: 1, timers: [{ id: 'keep', label: 'existing', fireAt: Date.now() + 600000 }] });
+ expect(await initializing).toEqual({ armed: 1, fired: 0 });
+ await scheduling;
+ expect(storeRef.value.timers.map(timer => timer.label)).toEqual(['existing', 'new']);
});
});
diff --git a/server/services/voice/tools/timer.js b/server/services/voice/tools/timer.js
index b4c5d5e16e..fff63895dd 100644
--- a/server/services/voice/tools/timer.js
+++ b/server/services/voice/tools/timer.js
@@ -36,7 +36,7 @@ export const TIMER_TOOLS = [
// Delegate to the persistent scheduler — it survives a restart (re-armed
// at boot, overdue ones fired once) and dedups an LLM re-issuing the same
// timer inside one reasoning loop.
- const scheduled = scheduleTimer({ totalMs, label: trimmedLabel });
+ const scheduled = await scheduleTimer({ totalMs, label: trimmedLabel });
const totalSecs = Math.round(totalMs / 1000);
const human = totalSecs >= 60
? `${Math.round(totalSecs / 60)} minute${Math.round(totalSecs / 60) === 1 ? '' : 's'}`
diff --git a/server/services/workspaceContext.js b/server/services/workspaceContext.js
index 4545810439..efdb86db06 100644
--- a/server/services/workspaceContext.js
+++ b/server/services/workspaceContext.js
@@ -47,9 +47,9 @@ const CONTEXTS_FILE = join(PATHS.data, 'workspace-contexts.json');
// against the one shared file, so they must serialize.
const queueWrite = createFileWriteQueue();
-/** Read the contexts map ({ [appId]: record }), tolerating a missing/blank file. */
+/** Read the contexts map ({ [appId]: record }), initializing only a missing file. */
async function loadContexts() {
- const data = await readJSONFile(CONTEXTS_FILE, { contexts: {} });
+ const data = await readJSONFile(CONTEXTS_FILE, { contexts: {} }, { strict: true });
if (!data || typeof data.contexts !== 'object' || data.contexts === null) {
return { contexts: {} };
}