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: serialize goal check-in and calendar writes through the identity store (#8755)
[._.]/ Adam Eivy28099de87edc
diff --git a/server/services/goalCalendarScheduler.js b/server/services/goalCalendarScheduler.jsindex a750bd5357..eac919b967 100644--- a/server/services/goalCalendarScheduler.js+++ b/server/services/goalCalendarScheduler.js@@ -1,11 +1,8 @@import { calendar } from '@googleapis/calendar';import { v4 as uuidv4 } from '../lib/uuid.js';-import { join } from 'path';-import { PATHS, readJSONFile, ensureDir, atomicWrite } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { getAuthenticatedClient, needsScopeUpgrade, getTokens } from './googleAuth.js';--const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');+import { loadJSON, mutateGoals, GOALS_FILE, DEFAULT_GOALS } from './identity/store.js';const TIME_SLOT_HOURS = {morning: 9,@@ -27,15 +24,6 @@ function resolveTimeSlotMinute(timeSlot) {return parseInt(timeSlot.split(':')[1], 10) || 0;}-async function loadGoals() {- return readJSONFile(GOALS_FILE, { goals: [] }, { strict: true });-}--async function saveGoals(data) {- await ensureDir(PATHS.digitalTwin);- await atomicWrite(GOALS_FILE, data);-}-export async function scheduleTimeBlocks(goalId) {const tokens = await getTokens();if (needsScopeUpgrade(tokens)) {@@ -45,7 +33,11 @@ export async function scheduleTimeBlocks(goalId) {const auth = await getAuthenticatedClient();if (!auth) throw new ServerError('Google OAuth not configured', { status: 401, code: 'NO_AUTH' });- const goals = await loadGoals();+ // This read is only to find the goal and its milestones/config for building the+ // calendar event batch below — it is not the snapshot that gets saved. The+ // Google Calendar round-trips can take a while; `mutateGoals` re-reads+ // goals.json right before persisting so a concurrent edit survives (#8755).+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS, { strict: true });const goal = goals.goals.find(g => g.id === goalId);if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });if (!goal.timeBlockConfig) throw new ServerError('Time block config not set', { status: 400, code: 'NO_CONFIG' });@@ -117,10 +109,17 @@ export async function scheduleTimeBlocks(goalId) {}}- goal.scheduledEvents = scheduledEvents;- goal.updatedAt = new Date().toISOString();- goals.updatedAt = new Date().toISOString();- await saveGoals(goals);+ // Apply to a freshly re-read goal by id rather than the snapshot captured+ // before the calendar batch above — see the note on the initial read.+ await mutateGoals(freshGoals => {+ const freshGoal = freshGoals.goals.find(g => g.id === goalId);+ if (freshGoal) {+ freshGoal.scheduledEvents = scheduledEvents;+ freshGoal.updatedAt = new Date().toISOString();+ }+ freshGoals.updatedAt = new Date().toISOString();+ return freshGoals;+ });console.log(`📅 Scheduled ${scheduledEvents.length} time blocks for goal "${goal.title}"`);return { count: scheduledEvents.length, events: scheduledEvents };@@ -130,7 +129,9 @@ export async function removeScheduledEvents(goalId) {const auth = await getAuthenticatedClient();if (!auth) throw new ServerError('Google OAuth not configured', { status: 401, code: 'NO_AUTH' });- const goals = await loadGoals();+ // Same pattern as scheduleTimeBlocks: this read only locates the events to+ // delete from Google Calendar; the write below re-reads fresh (#8755).+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS, { strict: true });const goal = goals.goals.find(g => g.id === goalId);if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });@@ -147,10 +148,15 @@ export async function removeScheduledEvents(goalId) {})));- goal.scheduledEvents = [];- goal.updatedAt = new Date().toISOString();- goals.updatedAt = new Date().toISOString();- await saveGoals(goals);+ await mutateGoals(freshGoals => {+ const freshGoal = freshGoals.goals.find(g => g.id === goalId);+ if (freshGoal) {+ freshGoal.scheduledEvents = [];+ freshGoal.updatedAt = new Date().toISOString();+ }+ freshGoals.updatedAt = new Date().toISOString();+ return freshGoals;+ });console.log(`📅 Removed ${events.length} scheduled events for goal "${goal.title}"`);return { deleted: events.length };diff --git a/server/services/goalCalendarScheduler.test.js b/server/services/goalCalendarScheduler.test.jsnew file mode 100644index 0000000000..646766daa6--- /dev/null+++ b/server/services/goalCalendarScheduler.test.js@@ -0,0 +1,112 @@+/**+ * #8755: scheduleTimeBlocks/removeScheduledEvents used to read goals.json once,+ * await Google Calendar round-trips, then write back the whole snapshot+ * captured before those calls started — silently dropping any concurrent edit+ * to the goal (or any other goal) made while the calendar calls were in+ * flight. They now apply `scheduledEvents` to a freshly re-read goal via the+ * shared `mutateGoals` serializer.+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++var tempRoot; // eslint-disable-line no-var+function getTempRoot() {+ if (!tempRoot) tempRoot = mkdtempSync(join(tmpdir(), 'goal-calendar-test-'));+ return tempRoot;+}++vi.mock('../lib/fileUtils.js', async (importOriginal) =>+ makePathsProxy(await importOriginal(), { dataRoot: () => getTempRoot() }));++vi.mock('./mortalLoomStore.js', () => ({+ isMortalLoomEnabled: vi.fn(async () => false),+ mlArrayIfEnabled: vi.fn(async () => null),+ mlReplace: vi.fn(async () => {}),+}));++const insertedEvents = [];+vi.mock('@googleapis/calendar', () => ({+ calendar: () => ({+ events: {+ insert: vi.fn(async ({ requestBody }) => {+ const id = `evt-${insertedEvents.length + 1}`;+ insertedEvents.push({ id, requestBody });+ return { data: { id } };+ }),+ delete: vi.fn(async () => ({})),+ },+ }),+}));++vi.mock('./googleAuth.js', () => ({+ getAuthenticatedClient: vi.fn(async () => ({})),+ needsScopeUpgrade: vi.fn(() => false),+ getTokens: vi.fn(async () => ({ access_token: 'fake' })),+}));++import { scheduleTimeBlocks, removeScheduledEvents } from './goalCalendarScheduler.js';+import { addProgressEntry } from './identity/goals.js';++afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });++describe('goalCalendarScheduler write serialization (#8755)', () => {+ const goalsFile = () => join(getTempRoot(), 'digital-twin', 'goals.json');++ const baseGoal = () => ({+ id: 'g1',+ title: 'Example Goal',+ status: 'active',+ createdAt: '2026-01-01T00:00:00.000Z',+ targetDate: '2026-12-31',+ milestones: [+ { id: 'ms1', title: 'Phase 1', order: 0, targetDate: '2026-12-31', completedAt: null }+ ],+ timeBlockConfig: {+ preferredDays: ['mon'],+ timeSlot: 'morning',+ sessionDurationMinutes: 30,+ },+ scheduledEvents: [],+ });++ beforeEach(() => {+ rmSync(getTempRoot(), { recursive: true, force: true });+ mkdirSync(join(getTempRoot(), 'digital-twin'), { recursive: true });+ vi.spyOn(console, 'log').mockImplementation(() => {});+ insertedEvents.length = 0;+ });++ it('applies scheduledEvents onto a goal edited while Calendar calls were in flight, without dropping the edit', async () => {+ writeFileSync(goalsFile(), JSON.stringify({ goals: [baseGoal()] }));++ const result = await scheduleTimeBlocks('g1');+ expect(result.count).toBeGreaterThan(0);++ // Concurrent edit lands AFTER the read scheduleTimeBlocks used to build its+ // calendar batch — simulated here by adding a progress entry once the+ // calendar insert calls (mocked, synchronous-ish) have already run.+ await addProgressEntry('g1', { date: '2026-06-01', note: 'logged during scheduling', durationMinutes: 15 });++ const written = JSON.parse(readFileSync(goalsFile(), 'utf8'));+ const goal = written.goals[0];+ expect(goal.scheduledEvents.length).toBe(result.count);+ expect(goal.progressLog).toHaveLength(1);+ expect(goal.progressLog[0].note).toBe('logged during scheduling');+ });++ it('removeScheduledEvents clears events on a freshly re-read goal', async () => {+ const goal = baseGoal();+ goal.scheduledEvents = [{ id: 'sched-1', googleEventId: 'evt-1', calendarId: 'primary', milestoneId: 'ms1', date: '2026-06-01', createdAt: '2026-01-01T00:00:00.000Z' }];+ writeFileSync(goalsFile(), JSON.stringify({ goals: [goal] }));++ const result = await removeScheduledEvents('g1');+ expect(result.deleted).toBe(1);++ const written = JSON.parse(readFileSync(goalsFile(), 'utf8'));+ expect(written.goals[0].scheduledEvents).toEqual([]);+ });+});diff --git a/server/services/goalCheckIn.js b/server/services/goalCheckIn.jsindex 25f5def60a..e1c901d2fb 100644--- a/server/services/goalCheckIn.js+++ b/server/services/goalCheckIn.js@@ -1,10 +1,7 @@-import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';-import { atomicWrite, PATHS, readJSONFile, ensureDir } from '../lib/fileUtils.js';import { callProviderAISimple, parseLLMJSON } from './aiProvider.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';--const GOALS_FILE = join(PATHS.digitalTwin, 'goals.json');+import { loadJSON, mutateGoals, GOALS_FILE, DEFAULT_GOALS } from './identity/store.js';function computeExpectedProgress(goal) {const start = new Date(goal.createdAt);@@ -40,12 +37,13 @@ Respond with JSON only (no markdown fences): { "assessment": "string", "recommenexport async function runGoalCheckIn({ background = false } = {}) {const { getActiveProvider } = await import('./providers.js');- // Strict (#4115): a swallowed unreadable goals.json reports "no active goals"- // and the check-in reports `{ checked: 0 }` — indistinguishable from a user- // who genuinely has none. The run also writes `goals` straight back, so any- // future non-empty path off a fake default would persist the emptiness.- const goals = await readJSONFile(GOALS_FILE, { goals: [] }, { strict: true });- const activeGoals = goals.goals.filter(g => g.status === 'active' && g.targetDate);+ // This initial load is only to decide WHICH goals to prompt for and to build+ // the LLM prompts — it is never the snapshot that gets saved. The slow LLM+ // calls below can take seconds to minutes, during which the user can add a+ // progress entry or edit a goal; `mutateGoals` re-reads goals.json right+ // before persisting so that concurrent edit survives (#8755).+ const initialGoals = await loadJSON(GOALS_FILE, DEFAULT_GOALS, { strict: true });+ const activeGoals = initialGoals.goals.filter(g => g.status === 'active' && g.targetDate);if (!activeGoals.length) {console.log('📊 Goal check-in: no active goals with target dates');@@ -85,6 +83,11 @@ export async function runGoalCheckIn({ background = false } = {}) {const now = new Date().toISOString();const today = now.slice(0, 10);+ // Build the check-in records off the snapshot captured before the LLM calls+ // (title/status text only needs to be roughly current), but apply them to a+ // freshly re-read goals document inside `mutateGoals` so a concurrent edit+ // that landed while the LLM calls were in flight isn't clobbered (#8755).+ const checkInsByGoalId = new Map();for (let i = 0; i < checkInData.length; i++) {const d = checkInData[i];const llmResult = llmResults[i];@@ -113,15 +116,21 @@ export async function runGoalCheckIn({ background = false } = {}) {createdAt: now};- if (!d.goal.checkIns) d.goal.checkIns = [];- d.goal.checkIns.push(checkIn);- d.goal.updatedAt = now;+ checkInsByGoalId.set(d.goal.id, checkIn);results.push({ goalId: d.goal.id, title: d.goal.title, status: d.status, checkIn });}- goals.updatedAt = now;- await ensureDir(PATHS.digitalTwin);- await atomicWrite(GOALS_FILE, goals);+ await mutateGoals(goals => {+ for (const goal of goals.goals) {+ const checkIn = checkInsByGoalId.get(goal.id);+ if (!checkIn) continue;+ if (!goal.checkIns) goal.checkIns = [];+ goal.checkIns.push(checkIn);+ goal.updatedAt = now;+ }+ goals.updatedAt = now;+ return goals;+ });// Send Telegram notificationconst statusEmoji = { 'on-track': '🟢', 'behind': '🟡', 'at-risk': '🔴' };diff --git a/server/services/goalCheckIn.test.js b/server/services/goalCheckIn.test.jsindex 13dd55fdb0..66d8d7c055 100644--- a/server/services/goalCheckIn.test.js+++ b/server/services/goalCheckIn.test.js@@ -43,7 +43,20 @@ vi.mock('./notifications.js', () => ({NOTIFICATION_TYPES: { HEALTH_ISSUE: 'health_issue' },}));+// MortalLoom is the swappable "active source" the mirror-on-save test drives —+// `ml.enabled` toggles isMortalLoomEnabled() without touching a real iCloud path.+const ml = vi.hoisted(() => ({ enabled: false }));+vi.mock('./mortalLoomStore.js', () => ({+ isMortalLoomEnabled: vi.fn(async () => ml.enabled),+ mlArrayIfEnabled: vi.fn(async () => null),+ mlReplace: vi.fn(async () => {}),+}));+import { runGoalCheckIn } from './goalCheckIn.js';+import { addProgressEntry } from './identity/goals.js';+import { mlReplace } from './mortalLoomStore.js';+import { callProviderAISimple } from './aiProvider.js';+import { dashboardEvents } from './dashboardEvents.js';afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });@@ -68,12 +81,12 @@ describe('runGoalCheckIn strict reads (#4115)', () => {it('rejects instead of reporting a check-in over zero goals', async () => {writeFileSync(goalsFile(), CORRUPT);- await expect(runGoalCheckIn()).rejects.toThrow(/Unreadable JSON file/);+ await expect(runGoalCheckIn()).rejects.toThrow(/Unreadable identity file/);});it('leaves the unreadable goals file byte-for-byte intact', async () => {writeFileSync(goalsFile(), CORRUPT);- await expect(runGoalCheckIn()).rejects.toThrow(/Unreadable JSON file/);+ await expect(runGoalCheckIn()).rejects.toThrow(/Unreadable identity file/);expect(readFileSync(goalsFile(), 'utf8'),'goals.json is the digital twin — a failed read must never rewrite it'@@ -94,3 +107,70 @@ describe('runGoalCheckIn strict reads (#4115)', () => {expect(written.goals[0].checkIns[0].assessment).toBe('ok');});});++// #8755: runGoalCheckIn used to read goals.json once, await one LLM call per+// goal (which can take seconds to minutes), then write back the WHOLE snapshot+// it captured before the calls started — silently dropping any edit made while+// the run was in flight. It now routes through `mutateGoals`, which re-reads+// goals.json right before saving.+describe('runGoalCheckIn concurrency and MortalLoom mirroring (#8755)', () => {+ const goalsFile = () => join(getTempRoot(), 'digital-twin', 'goals.json');++ const activeGoal = {+ id: 'g1',+ title: 'Example Goal',+ status: 'active',+ targetDate: '2027-01-01',+ createdAt: '2026-01-01T00:00:00.000Z',+ progress: 40,+ };++ beforeEach(() => {+ rmSync(getTempRoot(), { recursive: true, force: true });+ mkdirSync(join(getTempRoot(), 'digital-twin'), { recursive: true });+ vi.spyOn(console, 'log').mockImplementation(() => {});+ ml.enabled = false;+ vi.mocked(mlReplace).mockClear();+ });++ it('keeps a progress entry added while the LLM call is in flight', async () => {+ writeFileSync(goalsFile(), JSON.stringify({ goals: [activeGoal] }));++ let resolveLLM;+ vi.mocked(callProviderAISimple).mockImplementationOnce(+ () => new Promise((resolve) => { resolveLLM = resolve; })+ );++ const checkInPromise = runGoalCheckIn();++ // Let runGoalCheckIn get past its initial read and into the pending LLM+ // call before the concurrent edit lands.+ await new Promise((r) => setTimeout(r, 10));+ const entry = await addProgressEntry('g1', { date: '2026-06-01', note: 'did the thing', durationMinutes: 30 });+ expect(entry).not.toBeNull();++ resolveLLM({ text: '{"assessment":"ok","recommendations":["keep going"]}' });+ const result = await checkInPromise;+ expect(result.checked).toBe(1);++ const written = JSON.parse(readFileSync(goalsFile(), 'utf8'));+ const goal = written.goals[0];+ expect(goal.checkIns, 'the check-in itself must still land').toHaveLength(1);+ expect(goal.progressLog, 'the concurrent progress entry must not be clobbered').toHaveLength(1);+ expect(goal.progressLog[0].note).toBe('did the thing');+ });++ it('mirrors the check-in to MortalLoom and emits goals:changed when enabled', async () => {+ ml.enabled = true;+ writeFileSync(goalsFile(), JSON.stringify({ goals: [activeGoal] }));++ const changed = new Promise((resolve) => dashboardEvents.once('goals:changed', resolve));+ const result = await runGoalCheckIn();+ expect(result.checked).toBe(1);++ expect(mlReplace).toHaveBeenCalledWith('goals', expect.arrayContaining([+ expect.objectContaining({ id: 'g1', checkIns: expect.arrayContaining([expect.objectContaining({ assessment: 'ok' })]) })+ ]));+ await changed;+ });+});diff --git a/server/services/identity/store.js b/server/services/identity/store.jsindex 185d735aec..d8ca85dd4e 100644--- a/server/services/identity/store.js+++ b/server/services/identity/store.js@@ -3,6 +3,7 @@ import { dashboardEvents } from '../dashboardEvents.js';import { join } from 'path';import { atomicWrite, PATHS, ensureDir, readJSONFileStrict } from '../../lib/fileUtils.js';import { isMortalLoomEnabled, mlArrayIfEnabled, mlReplace } from '../mortalLoomStore.js';+import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';// === Goal normalization defaults ===@@ -156,3 +157,29 @@ export async function saveJSON(filePath, data) {}if (filePath === GOALS_FILE) dashboardEvents.emit('goals:changed');}++// Serializes goals.json read-modify-write across every caller that must run slow+// work (an LLM call per goal, Google Calendar round-trips) BEFORE the write.+// Doing the slow work first, then re-reading goals.json inside `fn` right before+// saving, is what keeps a concurrent edit (a new progress entry, a goal edit or+// create) from being clobbered by a stale snapshot captured before the slow work+// started (#8755). The single shared queue key ('goals') also protects two+// concurrent mutators (e.g. check-in + calendar scheduler) from interleaving+// their own reads/writes.+const goalsQueue = createKeyCachedQueue();++/**+ * @param {(goals: object) => (object | Promise<object>)} fn - receives a freshly+ * loaded goals document (post any earlier slow work in the caller) and returns+ * the document to persist. Run serialized against every other `mutateGoals`+ * call so two in-flight mutations can't race a load/save pair.+ * @returns {Promise<object>} the saved goals document.+ */+export function mutateGoals(fn) {+ return goalsQueue('goals', async () => {+ const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS, { strict: true });+ const next = await fn(goals);+ await saveJSON(GOALS_FILE, next);+ return next;+ });+}diff --git a/server/services/identity/store.test.js b/server/services/identity/store.test.jsindex 0781be0e93..92b08a7369 100644--- a/server/services/identity/store.test.js+++ b/server/services/identity/store.test.js@@ -33,7 +33,7 @@ vi.mock('../taste-questionnaire.js', () => ({getTasteProfile: vi.fn(async () => ({ completedCount: 0, totalSections: 0, lastSessionAt: null })),}));-const { saveJSON, loadJSON, normalizeGoal, GOALS_FILE, LONGEVITY_FILE, DEFAULT_GOALS, DEFAULT_LONGEVITY, PORTOS_GOAL_DEFAULTS } = await import('./store.js');+const { saveJSON, loadJSON, mutateGoals, normalizeGoal, GOALS_FILE, LONGEVITY_FILE, DEFAULT_GOALS, DEFAULT_LONGEVITY, PORTOS_GOAL_DEFAULTS } = await import('./store.js');const { getIdentityStatus } = await import('./status.js');afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));@@ -214,3 +214,52 @@ it('announces goal persistence only after the readable store has changed', asyncdashboardEvents.off('goals:changed', listener);}});++// Regression (#8755): goalCheckIn.js and goalCalendarScheduler.js used to read+// goals.json once, await slow work (an LLM call / a Google Calendar+// round-trip), then write back the stale snapshot — clobbering any concurrent+// edit. `mutateGoals` serializes every read-modify-write against the shared+// 'goals' key so two in-flight mutators can't interleave their load/save+// pairs and always see each other's committed writes.+describe('mutateGoals — serialized read-modify-write (#8755)', () => {+ it('runs each mutator against the freshest goals document, not a stale capture', async () => {+ await saveJSON(GOALS_FILE, { goals: [{ id: 'g1', tag: 'initial' }] });++ // First mutator holds the queue open until we tell it to proceed, so the+ // second mutator's call is definitely queued behind it, not racing it.+ let releaseFirst;+ const firstStarted = new Promise((resolveStarted) => {+ mutateGoals(async (goals) => {+ resolveStarted();+ await new Promise((r) => { releaseFirst = r; });+ goals.goals[0].tag = 'from-first';+ return goals;+ });+ });+ await firstStarted;++ const second = mutateGoals((goals) => {+ // If this ran against a snapshot captured before the first mutator's+ // write landed, it would still see tag: 'initial' here.+ goals.goals[0].seenTag = goals.goals[0].tag;+ return goals;+ });++ releaseFirst();+ await second;++ const final = await loadJSON(GOALS_FILE, DEFAULT_GOALS);+ expect(final.goals[0].tag).toBe('from-first');+ expect(final.goals[0].seenTag, 'second mutator must observe the first mutator\'s committed write').toBe('from-first');+ });++ it('mirrors the result to MortalLoom when enabled, like a direct saveJSON call', async () => {+ ml.goals = [];+ await mutateGoals((goals) => {+ goals.goals.push({ id: 'g1' });+ return goals;+ });+ const { mlReplace } = await import('../mortalLoomStore.js');+ expect(mlReplace).toHaveBeenCalledWith('goals', [expect.objectContaining({ id: 'g1' })]);+ });+});