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: serialize all goal document mutations (#8842)

[._.]/ Adam Eivy7f5623c8e84a
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 001a5e3a0b..5e7b56f61e 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -412,37 +412,37 @@ async function getGoalsSnapshot() {
}
async function applyGoalsRemote(remoteData) {
- const local = await readJSONFile(GOALS_FILE, { goals: [] }, { strict: true });
-
- // Merge goals array by ID with LWW on updatedAt
- const { merged: mergedGoals, changed: goalsChanged } = mergeArraysByKey(
- local.goals || [],
- remoteData.goals || [],
- 'id',
- 'updatedAt'
- );
-
- // Merge top-level metadata (birthDate, lifeExpectancy, timeHorizons) via LWW
- // Use the most recent goal's updatedAt as proxy for file freshness
- const localMaxTs = (local.goals || []).reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);
- const remoteMaxTs = (remoteData.goals || []).reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);
- const metaSource = remoteMaxTs > localMaxTs ? remoteData : local;
+ const { editGoals } = await import('./identity/store.js');
+ return editGoals(local => {
+ // Merge goals array by ID with LWW on updatedAt
+ const { merged: mergedGoals, changed: goalsChanged } = mergeArraysByKey(
+ local.goals || [],
+ remoteData.goals || [],
+ 'id',
+ 'updatedAt'
+ );
- const merged = {
- ...local,
- birthDate: metaSource.birthDate ?? local.birthDate,
- lifeExpectancy: metaSource.lifeExpectancy ?? local.lifeExpectancy,
- timeHorizons: metaSource.timeHorizons ?? local.timeHorizons,
- goals: mergedGoals
- };
+ // Merge top-level metadata (birthDate, lifeExpectancy, timeHorizons) via LWW
+ // Use the most recent goal's updatedAt as proxy for file freshness
+ const localMaxTs = (local.goals || []).reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);
+ const remoteMaxTs = (remoteData.goals || []).reduce((max, g) => Math.max(max, new Date(g.updatedAt || 0).getTime()), 0);
+ const metaSource = remoteMaxTs > localMaxTs ? remoteData : local;
+
+ const merged = {
+ ...local,
+ birthDate: metaSource.birthDate ?? local.birthDate,
+ lifeExpectancy: metaSource.lifeExpectancy ?? local.lifeExpectancy,
+ timeHorizons: metaSource.timeHorizons ?? local.timeHorizons,
+ goals: mergedGoals
+ };
- if (goalsChanged || remoteMaxTs > localMaxTs) {
- await atomicWrite(GOALS_FILE, merged);
- dashboardEvents.emit('goals:changed');
- console.log(`🔄 Goals sync: merged ${mergedGoals.length} goals`);
- return { applied: true, count: mergedGoals.length };
- }
- return { applied: false, count: 0 };
+ if (goalsChanged || remoteMaxTs > localMaxTs) {
+ Object.assign(local, merged);
+ console.log(`🔄 Goals sync: merged ${mergedGoals.length} goals`);
+ return { applied: true, count: mergedGoals.length };
+ }
+ return { applied: false, count: 0 };
+ });
}
// --- Category: Character ---
diff --git a/server/services/identity/goalMutations.test.js b/server/services/identity/goalMutations.test.js
new file mode 100644
index 0000000000..fe5a949b0c
--- /dev/null
+++ b/server/services/identity/goalMutations.test.js
@@ -0,0 +1,146 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { setImmediate } from 'node:timers/promises';
+
+const h = vi.hoisted(() => ({ document: null, readBarrier: null, aiBarrier: null, mirror: null }));
+// Detached snapshots reproduce real read/modify/write races without touching a
+// filesystem, database, provider, or the user's MortalLoom store.
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { digitalTwin: '/isolated-test/digital-twin' },
+ ensureDir: async () => {},
+ readJSONFileStrict: async path => {
+ const value = path.endsWith('goals.json') ? structuredClone(h.document) : {};
+ const barrier = path.endsWith('goals.json') && h.readBarrier;
+ if (barrier) {
+ h.readBarrier = null;
+ barrier.entered.resolve();
+ await barrier.release.promise;
+ }
+ return { ok: true, value };
+ },
+ readJSONFile: async () => structuredClone(h.document),
+ atomicWrite: vi.fn(async (_path, value) => { h.document = structuredClone(value); })
+}));
+vi.mock('../mortalLoomStore.js', () => ({
+ isMortalLoomEnabled: async () => h.mirror !== null,
+ mlArrayIfEnabled: async () => structuredClone(h.mirror),
+ mlReplace: vi.fn(async (_key, goals) => { h.mirror = structuredClone(goals); })
+}));
+vi.mock('../meatspaceCalendar.js', () => ({ getActivities: async () => [] }));
+vi.mock('../genome.js', () => ({ getGenomeSummary: async () => null }));
+vi.mock('../providers.js', () => ({ getActiveProvider: async () => ({ defaultModel: 'example' }), getProviderById: async () => null }));
+vi.mock('../aiProvider.js', () => ({
+ parseLLMJSON: JSON.parse,
+ callProviderAISimple: async () => {
+ h.aiBarrier.entered.resolve();
+ await h.aiBarrier.release.promise;
+ return { text: JSON.stringify({ status: 'on-track', assessment: 'Example assessment' }) };
+ }
+}));
+
+import { atomicWrite } from '../../lib/fileUtils.js';
+import { mutateGoals } from './store.js';
+import * as goals from './goals.js';
+import * as todos from './todos.js';
+
+const barrier = () => ({ entered: Promise.withResolvers(), release: Promise.withResolvers() });
+const goal = () => ({ id: 'example', title: 'Example goal', status: 'active', milestones: [], progress: 0, todos: [] });
+beforeEach(() => {
+ h.document = { goals: [goal()] };
+ h.readBarrier = null;
+ h.aiBarrier = null;
+ h.mirror = null;
+ vi.clearAllMocks();
+});
+
+describe('shared goal document writers', () => {
+ it('retains todo and goal edits behind an overlapping progress/check-in write', async () => {
+ const held = barrier();
+ const progressing = mutateGoals(async doc => {
+ held.entered.resolve();
+ await held.release.promise;
+ doc.goals[0].progress = 40;
+ doc.goals[0].checkIns = [{ id: 'queued-check-in' }];
+ return doc;
+ });
+ await held.entered.promise;
+ const adding = todos.addTodo('example', { title: 'Practice' });
+ const editing = goals.updateGoal('example', { title: 'Updated goal' });
+ // Flush ready I/O on the isolated adapter while the first writer is held.
+ await setImmediate();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ held.release.resolve();
+ const [, todo] = await Promise.all([progressing, adding, editing]);
+ expect(h.document.goals[0]).toMatchObject({
+ title: 'Updated goal', progress: 40,
+ checkIns: [{ id: 'queued-check-in' }], todos: [{ id: todo.id, title: 'Practice' }]
+ });
+ await Promise.all([
+ todos.updateTodo('example', todo.id, { status: 'done' }),
+ goals.addProgressEntry('example', { date: '2026-01-01', note: 'Example progress' })
+ ]);
+ expect(h.document.goals[0].todos[0]).toMatchObject({ status: 'done', completedAt: expect.any(String) });
+ expect(h.document.goals[0].progressLog).toHaveLength(1);
+ await Promise.all([todos.deleteTodo('example', todo.id), goals.updateGoalProgress('example', 60)]);
+ expect(h.document.goals[0]).toMatchObject({ todos: [], progress: 60 });
+ });
+
+ it('re-reads lazy normalization after a concurrent progress write and then stays read-only', async () => {
+ h.readBarrier = barrier();
+ const held = h.readBarrier;
+ const reading = goals.getGoals();
+ await held.entered.promise;
+ await goals.addProgressEntry('example', { date: '2026-01-01', note: 'Retain me' });
+ await goals.updateGoal('example', { title: 'Retain title' });
+ held.release.resolve();
+ expect((await reading).goals[0]).toMatchObject({ title: 'Retain title', progressLog: [{ note: 'Retain me' }], tags: [] });
+ atomicWrite.mockClear();
+ await goals.getGoals();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ });
+
+ it('keeps slow AI work outside the queue and appends to the latest goal', async () => {
+ h.aiBarrier = barrier();
+ const checking = goals.checkInGoal('example');
+ await h.aiBarrier.entered.promise;
+ await Promise.all([
+ goals.updateGoal('example', { title: 'Edited during AI' }),
+ todos.addTodo('example', { title: 'Added during AI' }),
+ goals.updateGoalProgress('example', 25)
+ ]);
+ h.aiBarrier.release.resolve();
+ const checkIn = await checking;
+ expect(h.document.goals[0]).toMatchObject({ title: 'Edited during AI', progress: 25,
+ todos: [{ title: 'Added during AI' }], checkIns: [{ id: checkIn.id }] });
+ });
+
+ it('does not resurrect a goal deleted during an AI check-in', async () => {
+ h.aiBarrier = barrier();
+ const checking = goals.checkInGoal('example');
+ await h.aiBarrier.entered.promise;
+ await goals.deleteGoal('example');
+ h.aiBarrier.release.resolve();
+ await expect(checking).rejects.toMatchObject({ status: 404, code: 'NOT_FOUND' });
+ expect(h.document.goals).toEqual([]);
+ });
+
+ it('preserves missing-record results without writing or mirroring', async () => {
+ expect(await todos.addTodo('missing', { title: 'Absent' })).toBeNull();
+ expect(await todos.updateTodo('example', 'missing', { title: 'Absent' })).toBeNull();
+ expect(await todos.deleteTodo('example', 'missing')).toBeNull();
+ expect(await goals.completeMilestoneTask('example', 'missing', 'missing')).toBeNull();
+ expect(atomicWrite).not.toHaveBeenCalled();
+ await expect(goals.acceptGoalPhases('missing', [])).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+
+ it('mirrors the serialized final document and keeps explicit imports local', async () => {
+ h.mirror = [goal()];
+ await Promise.all([todos.addTodo('example', { title: 'Mirrored todo' }), goals.updateGoalProgress('example', 50)]);
+ expect(h.mirror[0]).toMatchObject({ progress: 50, todos: [{ title: 'Mirrored todo' }] });
+ await mutateGoals(doc => {
+ doc.goals.push({ id: 'imported' });
+ return doc;
+ }, { localOnly: true });
+ expect(h.document.goals.map(g => g.id)).toEqual(['example', 'imported']);
+ expect(h.mirror.map(g => g.id)).toEqual(['example']);
+ });
+});
diff --git a/server/services/identity/goals.js b/server/services/identity/goals.js
index 9da35e3f01..fec85da65e 100644
--- a/server/services/identity/goals.js
+++ b/server/services/identity/goals.js
@@ -13,7 +13,7 @@ import {
DEFAULT_GOALS,
DEFAULT_LONGEVITY,
loadJSON,
- saveJSON,
+ editGoals,
mutateGoals
} from './store.js';
import { applyFreshTimeHorizons, deriveLongevity } from './longevity.js';
@@ -186,19 +186,7 @@ function hasAncestorCycle(goals, goalId, newParentId) {
// === Service Functions ===
-/**
- * @param {{ strict?: boolean }} [options] - `strict: true` throws when goals.json is
- * present-but-unreadable/corrupt rather than reporting it as "no goals filed"
- * (#2726). Off by default — every existing caller wants the empty fallback.
- */
-export async function getGoals(options) {
- const data = await loadJSON(GOALS_FILE, DEFAULT_GOALS, options);
- // A goals.json that parsed but carries no goals array is as untrustworthy as one
- // that failed to parse — validate before the count downstream trusts it. Only
- // under strict: the non-strict path keeps its existing behavior for this shape.
- if (options?.strict && !Array.isArray(data?.goals)) {
- throw new Error(`Goals malformed: ${GOALS_FILE}`);
- }
+function normalizeGoals(data) {
// Lazy migration: backfill parentId, tags, linkedActivities on goals missing them
let needsSave = false;
for (const goal of data.goals) {
@@ -222,7 +210,29 @@ export async function getGoals(options) {
if (!Array.isArray(ms.tasks)) { ms.tasks = []; needsSave = true; }
}
}
- if (needsSave) await saveJSON(GOALS_FILE, data);
+ return needsSave;
+}
+
+/**
+ * @param {{ strict?: boolean }} [options] - `strict: true` throws when goals.json is
+ * present-but-unreadable/corrupt rather than reporting it as "no goals filed"
+ * (#2726). Off by default — every existing caller wants the empty fallback.
+ */
+export async function getGoals(options) {
+ let data = await loadJSON(GOALS_FILE, DEFAULT_GOALS, options);
+ // A goals.json that parsed but carries no goals array is as untrustworthy as one
+ // that failed to parse — validate before the count downstream trusts it. Only
+ // under strict: the non-strict path keeps its existing behavior for this shape.
+ if (options?.strict && !Array.isArray(data?.goals)) {
+ throw new Error(`Goals malformed: ${GOALS_FILE}`);
+ }
+ if (normalizeGoals(data)) {
+ // Re-read under the writer queue; never save the snapshot from this read.
+ data = await mutateGoals(fresh => {
+ normalizeGoals(fresh);
+ return fresh;
+ });
+ }
// Urgency is only *persisted* when a goal is written or a birth date is set, so the
// stored value is as old as that write — and it ranks off `timeHorizons.yearsRemaining`,
@@ -246,140 +256,146 @@ export async function getGoals(options) {
}
export async function setBirthDate(birthDate) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- goals.birthDate = birthDate;
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
+ let goals = await mutateGoals(goals => {
+ goals.birthDate = birthDate;
+ goals.updatedAt = new Date().toISOString();
+ return goals;
+ });
- // Sync to meatspace config (canonical source), skip goals sync since we just wrote it
+ // External work stays outside the goal queue.
const { updateBirthDate } = await import('../meatspace.js');
await updateBirthDate(birthDate, { syncGoals: false });
-
- // Re-derive longevity with new birth date
const longevity = await deriveLongevity(birthDate);
- // Recalculate urgency for all active goals
if (longevity.timeHorizons) {
- for (const goal of goals.goals) {
- if (goal.status === 'active') {
- goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);
+ goals = await mutateGoals(fresh => {
+ // A newer birth-date edit owns its own derived metadata.
+ if (fresh.birthDate !== birthDate) return fresh;
+ for (const goal of fresh.goals) {
+ if (goal.status === 'active') goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);
}
- }
- goals.lifeExpectancy = longevity.lifeExpectancy;
- goals.timeHorizons = longevity.timeHorizons;
- await saveJSON(GOALS_FILE, goals);
+ fresh.lifeExpectancy = longevity.lifeExpectancy;
+ fresh.timeHorizons = longevity.timeHorizons;
+ return fresh;
+ });
}
-
return goals;
}
export async function createGoal({ title, description, horizon, category, goalType, parentId, tags, targetDate, timeBlockConfig, featureAreas }) {
- // getGoals() already refreshed `goals.timeHorizons` against today, so read it from
- // there rather than paying for a second longevity load.
- const goals = await getGoals();
-
- // Validate parentId references an existing goal
- if (parentId && !goals.goals.find(g => g.id === parentId)) {
- throw new ServerError('Parent goal not found', { status: 400, code: 'INVALID_PARENT' });
- }
+ return editGoals(async goals => {
+ // Refresh horizons against the document read inside the writer queue.
+ normalizeGoals(goals);
+ const longevity = await loadLongevityFor(goals);
+ if (longevity.timeHorizons) goals.timeHorizons = longevity.timeHorizons;
+
+ // Validate parentId references an existing goal
+ if (parentId && !goals.goals.find(g => g.id === parentId)) {
+ throw new ServerError('Parent goal not found', { status: 400, code: 'INVALID_PARENT' });
+ }
- const id = `goal-${uuidv4()}`;
- const goal = {
- id,
- title,
- description: description || '',
- horizon: horizon || '5-year',
- category: category || 'mastery',
- goalType: goalType || 'standard',
- parentId: parentId || null,
- tags: [...new Set((tags || []).map(t => t.trim()).filter(Boolean))],
- linkedActivities: [],
- linkedCalendars: [],
- featureAreas: Array.isArray(featureAreas) ? featureAreas : [],
- targetDate: targetDate || null,
- timeBlockConfig: timeBlockConfig || null,
- scheduledEvents: [],
- checkIns: [],
- urgency: null,
- status: 'active',
- milestones: [],
- progress: 0,
- progressHistory: [],
- todos: [],
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString()
- };
+ const id = `goal-${uuidv4()}`;
+ const goal = {
+ id,
+ title,
+ description: description || '',
+ horizon: horizon || '5-year',
+ category: category || 'mastery',
+ goalType: goalType || 'standard',
+ parentId: parentId || null,
+ tags: [...new Set((tags || []).map(t => t.trim()).filter(Boolean))],
+ linkedActivities: [],
+ linkedCalendars: [],
+ featureAreas: Array.isArray(featureAreas) ? featureAreas : [],
+ targetDate: targetDate || null,
+ timeBlockConfig: timeBlockConfig || null,
+ scheduledEvents: [],
+ checkIns: [],
+ urgency: null,
+ status: 'active',
+ milestones: [],
+ progress: 0,
+ progressHistory: [],
+ todos: [],
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ };
- // Calculate urgency if time horizons available
- if (goals.timeHorizons) {
- goal.urgency = computeGoalUrgency(goal, goals.timeHorizons);
- }
+ // Calculate urgency if time horizons available
+ if (goals.timeHorizons) {
+ goal.urgency = computeGoalUrgency(goal, goals.timeHorizons);
+ }
- goals.goals.push(goal);
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
+ goals.goals.push(goal);
+ goals.updatedAt = new Date().toISOString();
- console.log(`🎯 Goal created: "${title}" (${horizon}, urgency: ${goal.urgency ?? 'n/a'})`);
- return goal;
+ console.log(`🎯 Goal created: "${title}" (${horizon}, urgency: ${goal.urgency ?? 'n/a'})`);
+ return goal;
+ });
}
export async function updateGoal(goalId, updates) {
- const goals = await getGoals();
- const idx = goals.goals.findIndex(g => g.id === goalId);
- if (idx === -1) return null;
-
- const goal = goals.goals[idx];
+ return editGoals(async goals => {
+ normalizeGoals(goals);
+ const longevity = await loadLongevityFor(goals);
+ if (longevity.timeHorizons) goals.timeHorizons = longevity.timeHorizons;
+ const idx = goals.goals.findIndex(g => g.id === goalId);
+ if (idx === -1) return null;
+
+ const goal = goals.goals[idx];
+
+ // Validate parentId doesn't create a cycle
+ if (updates.parentId !== undefined && updates.parentId !== null) {
+ if (!goals.goals.find(g => g.id === updates.parentId)) {
+ throw new ServerError('Parent goal not found', { status: 400, code: 'INVALID_PARENT' });
+ }
+ if (hasAncestorCycle(goals.goals, goalId, updates.parentId)) {
+ throw new ServerError('Cannot set parent: would create a cycle', { status: 400, code: 'CYCLE_DETECTED' });
+ }
+ }
- // Validate parentId doesn't create a cycle
- if (updates.parentId !== undefined && updates.parentId !== null) {
- if (!goals.goals.find(g => g.id === updates.parentId)) {
- throw new ServerError('Parent goal not found', { status: 400, code: 'INVALID_PARENT' });
+ const allowed = ['title', 'description', 'horizon', 'category', 'goalType', 'status', 'parentId', 'tags', 'targetDate', 'timeBlockConfig', 'featureAreas'];
+ for (const key of allowed) {
+ if (updates[key] !== undefined) goal[key] = updates[key];
}
- if (hasAncestorCycle(goals.goals, goalId, updates.parentId)) {
- throw new ServerError('Cannot set parent: would create a cycle', { status: 400, code: 'CYCLE_DETECTED' });
+ // Normalize tags: deduplicate and trim
+ if (goal.tags) {
+ goal.tags = [...new Set(goal.tags.map(t => t.trim()).filter(Boolean))];
}
- }
+ goal.updatedAt = new Date().toISOString();
- const allowed = ['title', 'description', 'horizon', 'category', 'goalType', 'status', 'parentId', 'tags', 'targetDate', 'timeBlockConfig', 'featureAreas'];
- for (const key of allowed) {
- if (updates[key] !== undefined) goal[key] = updates[key];
- }
- // Normalize tags: deduplicate and trim
- if (goal.tags) {
- goal.tags = [...new Set(goal.tags.map(t => t.trim()).filter(Boolean))];
- }
- goal.updatedAt = new Date().toISOString();
-
- // Recalculate urgency if horizon changed — against the horizons getGoals() already
- // refreshed, not a second longevity load.
- if (goals.timeHorizons) {
- goal.urgency = computeGoalUrgency(goal, goals.timeHorizons);
- }
+ // Recalculate urgency against the refreshed horizons.
+ if (goals.timeHorizons) {
+ goal.urgency = computeGoalUrgency(goal, goals.timeHorizons);
+ }
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return goal;
+ goals.updatedAt = new Date().toISOString();
+ return goal;
+ });
}
export async function deleteGoal(goalId) {
- const goals = await getGoals();
- const idx = goals.goals.findIndex(g => g.id === goalId);
- if (idx === -1) return false;
-
- const deletedGoal = goals.goals[idx];
- // Orphan children: reparent to deleted goal's parent (or root)
- const now = new Date().toISOString();
- for (const goal of goals.goals) {
- if (goal.parentId === goalId) {
- goal.parentId = deletedGoal.parentId || null;
- goal.updatedAt = now;
+ return editGoals(async goals => {
+ normalizeGoals(goals);
+ const longevity = await loadLongevityFor(goals);
+ if (longevity.timeHorizons) goals.timeHorizons = longevity.timeHorizons;
+ const idx = goals.goals.findIndex(g => g.id === goalId);
+ if (idx === -1) return false;
+
+ const deletedGoal = goals.goals[idx];
+ // Orphan children: reparent to deleted goal's parent (or root)
+ const now = new Date().toISOString();
+ for (const goal of goals.goals) {
+ if (goal.parentId === goalId) {
+ goal.parentId = deletedGoal.parentId || null;
+ goal.updatedAt = now;
+ }
}
- }
- goals.goals.splice(idx, 1);
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return true;
+ goals.goals.splice(idx, 1);
+ goals.updatedAt = new Date().toISOString();
+ return true;
+ });
}
export async function getGoalsTree() {
@@ -430,65 +446,71 @@ export async function getGoalsTree() {
}
export async function linkActivity(goalId, { activityName, requiredFrequency, note }) {
- const goals = await getGoals();
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
-
- // Prevent duplicates
- if (goal.linkedActivities.some(l => l.activityName === activityName)) {
- // Update existing link
- const link = goal.linkedActivities.find(l => l.activityName === activityName);
- if (requiredFrequency !== undefined) link.requiredFrequency = requiredFrequency;
- if (note !== undefined) link.note = note;
- } else {
- goal.linkedActivities.push({
- activityName,
- requiredFrequency: requiredFrequency || null,
- note: note || ''
- });
- }
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- console.log(`🔗 Activity "${activityName}" linked to goal "${goal.title}"`);
- return goal;
+ return editGoals(async goals => {
+ normalizeGoals(goals);
+ const longevity = await loadLongevityFor(goals);
+ if (longevity.timeHorizons) goals.timeHorizons = longevity.timeHorizons;
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
+
+ // Prevent duplicates
+ if (goal.linkedActivities.some(l => l.activityName === activityName)) {
+ // Update existing link
+ const link = goal.linkedActivities.find(l => l.activityName === activityName);
+ if (requiredFrequency !== undefined) link.requiredFrequency = requiredFrequency;
+ if (note !== undefined) link.note = note;
+ } else {
+ goal.linkedActivities.push({
+ activityName,
+ requiredFrequency: requiredFrequency || null,
+ note: note || ''
+ });
+ }
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ console.log(`🔗 Activity "${activityName}" linked to goal "${goal.title}"`);
+ return goal;
+ });
}
export async function unlinkActivity(goalId, activityName) {
- const goals = await getGoals();
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
+ return editGoals(async goals => {
+ normalizeGoals(goals);
+ const longevity = await loadLongevityFor(goals);
+ if (longevity.timeHorizons) goals.timeHorizons = longevity.timeHorizons;
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- const idx = goal.linkedActivities.findIndex(l => l.activityName === activityName);
- if (idx === -1) return goal;
+ const idx = goal.linkedActivities.findIndex(l => l.activityName === activityName);
+ if (idx === -1) return goal;
- goal.linkedActivities.splice(idx, 1);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- console.log(`🔗 Activity "${activityName}" unlinked from goal "${goal.title}"`);
- return goal;
+ goal.linkedActivities.splice(idx, 1);
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ console.log(`🔗 Activity "${activityName}" unlinked from goal "${goal.title}"`);
+ return goal;
+ });
}
export async function addMilestone(goalId, { title, targetDate }) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
-
- const milestone = {
- id: `ms-${uuidv4()}`,
- title,
- targetDate: targetDate || null,
- completedAt: null,
- tasks: [],
- createdAt: new Date().toISOString()
- };
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- goal.milestones.push(milestone);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return milestone;
+ const milestone = {
+ id: `ms-${uuidv4()}`,
+ title,
+ targetDate: targetDate || null,
+ completedAt: null,
+ tasks: [],
+ createdAt: new Date().toISOString()
+ };
+
+ goal.milestones.push(milestone);
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ return milestone;
+ });
}
export async function addProgressEntry(goalId, { date, note, durationMinutes }) {
@@ -561,63 +583,63 @@ export async function reconcileCalendarProgress(sourceKey, { goalId, date, note,
}
export async function completeMilestone(goalId, milestoneId) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- const milestone = goal.milestones.find(m => m.id === milestoneId);
- if (!milestone) return null;
+ const milestone = goal.milestones.find(m => m.id === milestoneId);
+ if (!milestone) return null;
- milestone.completedAt = new Date().toISOString();
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return milestone;
+ milestone.completedAt = new Date().toISOString();
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ return milestone;
+ });
}
export async function linkCalendarToGoal(goalId, { subcalendarId, subcalendarName, matchPattern }) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
-
- if (!goal.linkedCalendars) goal.linkedCalendars = [];
-
- // Prevent duplicates
- const existing = goal.linkedCalendars.find(lc => lc.subcalendarId === subcalendarId);
- if (existing) {
- existing.subcalendarName = subcalendarName;
- existing.matchPattern = matchPattern || '';
- } else {
- goal.linkedCalendars.push({
- subcalendarId,
- subcalendarName,
- matchPattern: matchPattern || '',
- linkedAt: new Date().toISOString()
- });
- }
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- console.log(`📅 Calendar "${subcalendarName}" linked to goal "${goal.title}"`);
- return goal;
+ if (!goal.linkedCalendars) goal.linkedCalendars = [];
+
+ // Prevent duplicates
+ const existing = goal.linkedCalendars.find(lc => lc.subcalendarId === subcalendarId);
+ if (existing) {
+ existing.subcalendarName = subcalendarName;
+ existing.matchPattern = matchPattern || '';
+ } else {
+ goal.linkedCalendars.push({
+ subcalendarId,
+ subcalendarName,
+ matchPattern: matchPattern || '',
+ linkedAt: new Date().toISOString()
+ });
+ }
+
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ console.log(`📅 Calendar "${subcalendarName}" linked to goal "${goal.title}"`);
+ return goal;
+ });
}
export async function unlinkCalendarFromGoal(goalId, subcalendarId) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
-
- if (!goal.linkedCalendars) return goal;
- const idx = goal.linkedCalendars.findIndex(lc => lc.subcalendarId === subcalendarId);
- if (idx === -1) return goal;
-
- goal.linkedCalendars.splice(idx, 1);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- console.log(`📅 Calendar unlinked from goal "${goal.title}"`);
- return goal;
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
+
+ if (!goal.linkedCalendars) return goal;
+ const idx = goal.linkedCalendars.findIndex(lc => lc.subcalendarId === subcalendarId);
+ if (idx === -1) return goal;
+
+ goal.linkedCalendars.splice(idx, 1);
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ console.log(`📅 Calendar unlinked from goal "${goal.title}"`);
+ return goal;
+ });
}
export async function getGoalCalendarEvents(goalId, startDate, endDate) {
@@ -715,27 +737,27 @@ Respond with a JSON array only (no markdown fences, no explanation). Each elemen
}
export async function acceptGoalPhases(goalId, phases) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
- assertNoScheduledEvents(goal);
-
- goal.milestones = phases.map((phase, idx) => ({
- id: `ms-${uuidv4()}`,
- title: phase.title,
- description: phase.description || '',
- targetDate: phase.targetDate || null,
- order: phase.order ?? idx,
- completedAt: null,
- tasks: [],
- createdAt: new Date().toISOString()
- }));
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
+ assertNoScheduledEvents(goal);
+
+ goal.milestones = phases.map((phase, idx) => ({
+ id: `ms-${uuidv4()}`,
+ title: phase.title,
+ description: phase.description || '',
+ targetDate: phase.targetDate || null,
+ order: phase.order ?? idx,
+ completedAt: null,
+ tasks: [],
+ createdAt: new Date().toISOString()
+ }));
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- console.log(`🎯 Accepted ${phases.length} phases for goal "${goal.title}"`);
- return goal;
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ console.log(`🎯 Accepted ${phases.length} phases for goal "${goal.title}"`);
+ return goal;
+ });
}
// =============================================================================
@@ -803,58 +825,58 @@ ${goal.targetDate ? '- "targetDate": string (YYYY-MM-DD format)\n' : ''}- "order
// tasks into the stored shape (mirrors acceptGoalPhases). Overwrites
// goal.milestones — the proposal is the new plan.
export async function acceptGoalDecomposition(goalId, milestones) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
- assertNoScheduledEvents(goal);
-
- const now = new Date().toISOString();
- goal.milestones = milestones.map((ms, idx) => ({
- id: `ms-${uuidv4()}`,
- title: ms.title,
- description: ms.description || '',
- targetDate: ms.targetDate || null,
- order: ms.order ?? idx,
- completedAt: null,
- tasks: (Array.isArray(ms.tasks) ? ms.tasks : []).map(t => ({
- id: `ms-task-${uuidv4()}`,
- title: t.title,
- priority: t.priority || 'medium',
- estimateMinutes: t.estimateMinutes ?? null,
- status: 'pending',
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
+ assertNoScheduledEvents(goal);
+
+ const now = new Date().toISOString();
+ goal.milestones = milestones.map((ms, idx) => ({
+ id: `ms-${uuidv4()}`,
+ title: ms.title,
+ description: ms.description || '',
+ targetDate: ms.targetDate || null,
+ order: ms.order ?? idx,
completedAt: null,
+ tasks: (Array.isArray(ms.tasks) ? ms.tasks : []).map(t => ({
+ id: `ms-task-${uuidv4()}`,
+ title: t.title,
+ priority: t.priority || 'medium',
+ estimateMinutes: t.estimateMinutes ?? null,
+ status: 'pending',
+ completedAt: null,
+ createdAt: now
+ })),
createdAt: now
- })),
- createdAt: now
- }));
+ }));
- goal.updatedAt = now;
- goals.updatedAt = now;
- await saveJSON(GOALS_FILE, goals);
- const taskCount = goal.milestones.reduce((sum, ms) => sum + ms.tasks.length, 0);
- console.log(`🧩 Accepted decomposition for "${goal.title}": ${goal.milestones.length} milestones / ${taskCount} tasks`);
- return goal;
+ goal.updatedAt = now;
+ goals.updatedAt = now;
+ const taskCount = goal.milestones.reduce((sum, ms) => sum + ms.tasks.length, 0);
+ console.log(`🧩 Accepted decomposition for "${goal.title}": ${goal.milestones.length} milestones / ${taskCount} tasks`);
+ return goal;
+ });
}
// Toggles a milestone task's done state (mirrors updateTodo's done/pending flip).
export async function completeMilestoneTask(goalId, milestoneId, taskId) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- const milestone = goal.milestones?.find(m => m.id === milestoneId);
- if (!milestone) return null;
+ const milestone = goal.milestones?.find(m => m.id === milestoneId);
+ if (!milestone) return null;
- const task = milestone.tasks?.find(t => t.id === taskId);
- if (!task) return null;
+ const task = milestone.tasks?.find(t => t.id === taskId);
+ if (!task) return null;
- const done = task.status === 'done';
- task.status = done ? 'pending' : 'done';
- task.completedAt = done ? null : new Date().toISOString();
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return task;
+ const done = task.status === 'done';
+ task.status = done ? 'pending' : 'done';
+ task.completedAt = done ? null : new Date().toISOString();
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ return task;
+ });
}
// =============================================================================
@@ -933,46 +955,47 @@ Respond with JSON only (no markdown fences). The response must be an object with
}
export async function applyGoalOrganization(organization) {
- const goals = await getGoals();
- const now = new Date().toISOString();
- const goalMap = new Map(goals.goals.map(g => [g.id, g]));
- let changed = 0;
+ return editGoals(async goals => {
+ normalizeGoals(goals);
+ const longevity = await loadLongevityFor(goals);
+ if (longevity.timeHorizons) goals.timeHorizons = longevity.timeHorizons;
+ const now = new Date().toISOString();
+ const goalMap = new Map(goals.goals.map(g => [g.id, g]));
+ let changed = 0;
- for (const item of organization) {
- const goal = goalMap.get(item.id);
- if (!goal) continue;
+ for (const item of organization) {
+ const goal = goalMap.get(item.id);
+ if (!goal) continue;
- let goalChanged = false;
+ let goalChanged = false;
- if (item.goalType && goalTypeEnum.options.includes(item.goalType)) {
- if (goal.goalType !== item.goalType) {
- goal.goalType = item.goalType;
- goalChanged = true;
+ if (item.goalType && goalTypeEnum.options.includes(item.goalType)) {
+ if (goal.goalType !== item.goalType) {
+ goal.goalType = item.goalType;
+ goalChanged = true;
+ }
}
- }
- if (item.suggestedParentId !== undefined) {
- const newParentId = item.suggestedParentId;
- if (newParentId === null || goalMap.has(newParentId)) {
- if (!newParentId || !hasAncestorCycle(goals.goals, goal.id, newParentId)) {
- if (goal.parentId !== newParentId) {
- goal.parentId = newParentId;
- goalChanged = true;
+ if (item.suggestedParentId !== undefined) {
+ const newParentId = item.suggestedParentId;
+ if (newParentId === null || goalMap.has(newParentId)) {
+ if (!newParentId || !hasAncestorCycle(goals.goals, goal.id, newParentId)) {
+ if (goal.parentId !== newParentId) {
+ goal.parentId = newParentId;
+ goalChanged = true;
+ }
}
}
}
+ if (goalChanged) {
+ goal.updatedAt = now;
+ changed++;
+ }
}
- if (goalChanged) {
- goal.updatedAt = now;
- changed++;
- }
- }
- if (changed > 0) {
- goals.updatedAt = now;
- await saveJSON(GOALS_FILE, goals);
- }
- console.log(`🎯 Applied organization to ${changed} goals`);
- return { applied: changed };
+ if (changed > 0) goals.updatedAt = now;
+ console.log(`🎯 Applied organization to ${changed} goals`);
+ return { applied: changed };
+ });
}
// =============================================================================
@@ -1065,11 +1088,13 @@ Respond with JSON only (no markdown fences). The response must be an object with
createdAt: new Date().toISOString()
};
- if (!Array.isArray(goal.checkIns)) goal.checkIns = [];
- goal.checkIns.push(checkIn);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
+ await mutateGoals(fresh => {
+ const current = fresh.goals.find(g => g.id === goalId);
+ if (!current) throw new ServerError('Goal not found', { status: 404, code: 'NOT_FOUND' });
+ (current.checkIns ||= []).push(checkIn);
+ current.updatedAt = fresh.updatedAt = new Date().toISOString();
+ return fresh;
+ });
console.log(`📋 Check-in for "${goal.title}": ${checkIn.status} (${goal.progress}%${expectedProgress != null ? ` vs ${expectedProgress}% expected` : ''})`);
return checkIn;
@@ -1080,30 +1105,30 @@ Respond with JSON only (no markdown fences). The response must be an object with
// =============================================================================
export async function updateGoalProgress(goalId, value) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
-
- const prev = goal.progress ?? 0;
- goal.progress = value;
- if (!goal.progressHistory) goal.progressHistory = [];
-
- // Only log if value changed; deduplicate same-day entries to prevent bloat
- if (prev !== value) {
- const today = new Date().toISOString().slice(0, 10);
- const lastEntry = goal.progressHistory[goal.progressHistory.length - 1];
- if (lastEntry?.date === today) {
- lastEntry.value = value;
- lastEntry.timestamp = new Date().toISOString();
- } else {
- goal.progressHistory.push({ date: today, value, timestamp: new Date().toISOString() });
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
+
+ const prev = goal.progress ?? 0;
+ goal.progress = value;
+ if (!goal.progressHistory) goal.progressHistory = [];
+
+ // Only log if value changed; deduplicate same-day entries to prevent bloat
+ if (prev !== value) {
+ const today = new Date().toISOString().slice(0, 10);
+ const lastEntry = goal.progressHistory[goal.progressHistory.length - 1];
+ if (lastEntry?.date === today) {
+ lastEntry.value = value;
+ lastEntry.timestamp = new Date().toISOString();
+ } else {
+ goal.progressHistory.push({ date: today, value, timestamp: new Date().toISOString() });
+ }
}
- }
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
- console.log(`📊 Progress for "${goal.title}": ${prev}% → ${value}%`);
- return goal;
+ console.log(`📊 Progress for "${goal.title}": ${prev}% → ${value}%`);
+ return goal;
+ });
}
diff --git a/server/services/identity/goals.test.js b/server/services/identity/goals.test.js
index 561b4b62f2..24f8710585 100644
--- a/server/services/identity/goals.test.js
+++ b/server/services/identity/goals.test.js
@@ -5,6 +5,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const h = vi.hoisted(() => ({ goalsData: null, aiText: '' }));
vi.mock('./store.js', () => ({
+ editGoals: vi.fn(async fn => fn(h.goalsData)),
+ mutateGoals: vi.fn(async fn => {
+ h.goalsData = await fn(h.goalsData);
+ return h.goalsData;
+ }),
GOALS_FILE: 'goals.json',
LONGEVITY_FILE: 'longevity.json',
DEFAULT_GOALS: { goals: [], birthDate: null },
diff --git a/server/services/identity/longevity.test.js b/server/services/identity/longevity.test.js
index ef988f8c6c..a43b41e244 100644
--- a/server/services/identity/longevity.test.js
+++ b/server/services/identity/longevity.test.js
@@ -9,6 +9,11 @@ const birthDateYearsAgo = years => new Date(Date.now() - years * YEAR_MS).toISOS
const h = vi.hoisted(() => ({ goalsData: null, longevityData: null }));
vi.mock('./store.js', () => ({
+ editGoals: vi.fn(async fn => fn(h.goalsData)),
+ mutateGoals: vi.fn(async fn => {
+ h.goalsData = await fn(h.goalsData);
+ return h.goalsData;
+ }),
GOALS_FILE: 'goals.json',
LONGEVITY_FILE: 'longevity.json',
DEFAULT_GOALS: { goals: [], birthDate: null, lifeExpectancy: null, timeHorizons: null },
diff --git a/server/services/identity/store.js b/server/services/identity/store.js
index d8ca85dd4e..430a7f246b 100644
--- a/server/services/identity/store.js
+++ b/server/services/identity/store.js
@@ -1,7 +1,7 @@
import { meatspaceEvents } from '../meatspaceEvents.js';
import { dashboardEvents } from '../dashboardEvents.js';
import { join } from 'path';
-import { atomicWrite, PATHS, ensureDir, readJSONFileStrict } from '../../lib/fileUtils.js';
+import { atomicWrite, PATHS, ensureDir, readJSONFileStrict, readJSONFile } from '../../lib/fileUtils.js';
import { isMortalLoomEnabled, mlArrayIfEnabled, mlReplace } from '../mortalLoomStore.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
@@ -142,17 +142,17 @@ export async function loadJSON(filePath, defaultVal, { strict = false } = {}) {
// costs no goals, so reporting Strategist "unavailable" off it would be a lie in
// the opposite direction: the goals were right there and readable.
if (strict && !ok && !mlGoals) {
- throw new Error(`Unreadable identity file: ${filePath}`);
+ throw Object.assign(new Error(`Unreadable identity file: ${filePath}`), { code: 'UNREADABLE_STORE' });
}
return data;
}
-export async function saveJSON(filePath, data) {
+export async function saveJSON(filePath, data, { mirrorGoals = true } = {}) {
await ensureIdentityDir();
await atomicWrite(filePath, data);
if (filePath === LONGEVITY_FILE) meatspaceEvents.emit('death-clock:changed', {});
// Mirror goals array into MortalLoom.json so iOS/macOS app sees the change.
- if (filePath === GOALS_FILE && (await isMortalLoomEnabled()) && Array.isArray(data.goals)) {
+ if (filePath === GOALS_FILE && mirrorGoals && (await isMortalLoomEnabled()) && Array.isArray(data.goals)) {
await mlReplace('goals', data.goals);
}
if (filePath === GOALS_FILE) dashboardEvents.emit('goals:changed');
@@ -173,13 +173,31 @@ const goalsQueue = createKeyCachedQueue();
* 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.
+ * Unchanged documents are not written or mirrored. `localOnly` is reserved for
+ * MortalLoom's explicit import: merge into the local mirror without sourcing
+ * from, or replacing, the imported iCloud store. It still shares the same queue.
* @returns {Promise<object>} the saved goals document.
*/
-export function mutateGoals(fn) {
+export function mutateGoals(fn, { localOnly = false } = {}) {
return goalsQueue('goals', async () => {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS, { strict: true });
+ const goals = localOnly
+ ? await readJSONFile(GOALS_FILE, structuredClone(DEFAULT_GOALS), { strict: true })
+ : await loadJSON(GOALS_FILE, DEFAULT_GOALS, { strict: true });
+ const before = JSON.stringify(goals);
const next = await fn(goals);
- await saveJSON(GOALS_FILE, next);
+ if (JSON.stringify(next) !== before) {
+ await saveJSON(GOALS_FILE, next, { mirrorGoals: !localOnly });
+ }
return next;
});
}
+
+/** Edit the fresh document in place while returning a caller-specific result. */
+export async function editGoals(fn, options) {
+ let result;
+ await mutateGoals(async goals => {
+ result = await fn(goals);
+ return goals;
+ }, options);
+ return result;
+}
diff --git a/server/services/identity/todos.js b/server/services/identity/todos.js
index 3182dccc12..17fad822ea 100644
--- a/server/services/identity/todos.js
+++ b/server/services/identity/todos.js
@@ -1,69 +1,69 @@
import { v4 as uuidv4 } from '../../lib/uuid.js';
-import { GOALS_FILE, DEFAULT_GOALS, loadJSON, saveJSON } from './store.js';
+import { editGoals } from './store.js';
export async function addTodo(goalId, { title, priority, estimateMinutes }) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- if (!goal.todos) goal.todos = [];
+ if (!goal.todos) goal.todos = [];
- const todo = {
- id: `todo-${uuidv4()}`,
- title,
- status: 'pending',
- priority: priority || 'medium',
- estimateMinutes: estimateMinutes || null,
- createdAt: new Date().toISOString(),
- completedAt: null
- };
+ const todo = {
+ id: `todo-${uuidv4()}`,
+ title,
+ status: 'pending',
+ priority: priority || 'medium',
+ estimateMinutes: estimateMinutes || null,
+ createdAt: new Date().toISOString(),
+ completedAt: null
+ };
- goal.todos.push(todo);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
+ goal.todos.push(todo);
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
- console.log(`✅ Todo added to "${goal.title}": "${title}"`);
- return todo;
+ console.log(`✅ Todo added to "${goal.title}": "${title}"`);
+ return todo;
+ });
}
export async function updateTodo(goalId, todoId, updates) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- const todo = (goal.todos || []).find(t => t.id === todoId);
- if (!todo) return null;
+ const todo = (goal.todos || []).find(t => t.id === todoId);
+ if (!todo) return null;
- const allowed = ['title', 'status', 'priority', 'estimateMinutes'];
- for (const key of allowed) {
- if (updates[key] !== undefined) todo[key] = updates[key];
- }
+ const allowed = ['title', 'status', 'priority', 'estimateMinutes'];
+ for (const key of allowed) {
+ if (updates[key] !== undefined) todo[key] = updates[key];
+ }
- // Auto-set completedAt when marked done
- if (updates.status === 'done' && !todo.completedAt) {
- todo.completedAt = new Date().toISOString();
- } else if (updates.status && updates.status !== 'done') {
- todo.completedAt = null;
- }
+ // Auto-set completedAt when marked done
+ if (updates.status === 'done' && !todo.completedAt) {
+ todo.completedAt = new Date().toISOString();
+ } else if (updates.status && updates.status !== 'done') {
+ todo.completedAt = null;
+ }
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return todo;
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ return todo;
+ });
}
export async function deleteTodo(goalId, todoId) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
+ return editGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return null;
- const idx = (goal.todos || []).findIndex(t => t.id === todoId);
- if (idx === -1) return null;
+ const idx = (goal.todos || []).findIndex(t => t.id === todoId);
+ if (idx === -1) return null;
- goal.todos.splice(idx, 1);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return { deleted: true };
+ goal.todos.splice(idx, 1);
+ goal.updatedAt = new Date().toISOString();
+ goals.updatedAt = new Date().toISOString();
+ return { deleted: true };
+ });
}
diff --git a/server/services/meatspace.js b/server/services/meatspace.js
index e05b3d094d..c83d940024 100644
--- a/server/services/meatspace.js
+++ b/server/services/meatspace.js
@@ -330,9 +330,12 @@ export async function updateBirthDate(birthDate, { syncGoals = true } = {}) {
// Keep goals.json in sync for backward compatibility
if (goals) {
- goals.birthDate = birthDate;
- goals.updatedAt = new Date().toISOString();
- await atomicWrite(GOALS_FILE, goals);
+ const { mutateGoals } = await import('./identity/store.js');
+ await mutateGoals(fresh => {
+ fresh.birthDate = birthDate;
+ fresh.updatedAt = new Date().toISOString();
+ return fresh;
+ });
}
await mlPatchProfileIfEnabled({ birthDate });
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index a8f9217f2e..b3bf494586 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -823,21 +823,20 @@ export async function importToPortOS() {
};
// Goals live in a wrapper object, not a bare array
- const goalsPath = dataPath('digital-twin', 'goals.json');
- const localGoals = await readJSONFile(goalsPath, { goals: [] }, { strict: true });
- const seenGoalIds = new Set((localGoals.goals || []).map(g => g.id));
- let gAdded = 0, gSkipped = 0;
- for (const g of (store.goals || [])) {
- if (seenGoalIds.has(g.id)) { gSkipped++; continue; }
- localGoals.goals.push(g); gAdded++;
- }
- if (gAdded > 0) {
- await ensureDir(dataPath('digital-twin'));
- localGoals.updatedAt = new Date().toISOString();
- await atomicWrite(goalsPath, localGoals);
- dashboardEvents.emit('goals:changed');
- }
- report.added.goals = gAdded; report.skipped.goals = gSkipped;
+ const { editGoals } = await import('./identity/store.js');
+ await editGoals(localGoals => {
+ const seenGoalIds = new Set((localGoals.goals || []).map(g => g.id));
+ let added = 0, skipped = 0;
+ for (const goal of (store.goals || [])) {
+ if (seenGoalIds.has(goal.id)) { skipped++; continue; }
+ localGoals.goals.push(goal);
+ seenGoalIds.add(goal.id);
+ added++;
+ }
+ if (added > 0) localGoals.updatedAt = new Date().toISOString();
+ report.added.goals = added;
+ report.skipped.goals = skipped;
+ }, { localOnly: true });
for (const { mlKey, mlArr, localPath, local } of collections) {
if (mlArr.length === 0) { report.added[mlKey] = 0; report.skipped[mlKey] = 0; continue; }
diff --git a/server/services/personalStoreReadSafety.test.js b/server/services/personalStoreReadSafety.test.js
index afdec1fced..5c71b93a5d 100644
--- a/server/services/personalStoreReadSafety.test.js
+++ b/server/services/personalStoreReadSafety.test.js
@@ -220,3 +220,22 @@ it('preflights MortalLoom import destinations and preserves repaired records on
expect(JSON.parse(await readFile(goalsPath, 'utf8')).goals.map(goal => goal.id)).toEqual(['retained-goal', 'incoming-goal']);
expect(JSON.parse(await readFile(alcoholPath, 'utf8')).map(drink => drink.id)).toEqual(['retained-drink', 'incoming-drink']);
});
+
+it('keeps goal edits while importing MortalLoom records and updating the birth-date mirror', async () => {
+ const { mutateGoals } = await import('./identity/store.js');
+ const source = join(PATHS.data, 'mortal-source.json');
+ const goalsPath = join(PATHS.digitalTwin, 'goals.json');
+ await seed(source, JSON.stringify({ goals: [{ id: 'incoming-goal' }] }));
+ await seed(goalsPath, JSON.stringify({ goals: [{ id: 'retained-goal', progress: 0 }] }));
+ await Promise.all([
+ importToPortOS(),
+ updateBirthDate('2000-01-01'),
+ mutateGoals(doc => {
+ doc.goals.find(goal => goal.id === 'retained-goal').progress = 60;
+ return doc;
+ })
+ ]);
+ expect(JSON.parse(await readFile(goalsPath, 'utf8'))).toMatchObject({
+ birthDate: '2000-01-01', goals: [{ id: 'retained-goal', progress: 60 }, { id: 'incoming-goal' }]
+ });
+});
diff --git a/server/services/sharingDurability.test.js b/server/services/sharingDurability.test.js
index 5479187bdb..bcfe5a4d7a 100644
--- a/server/services/sharingDurability.test.js
+++ b/server/services/sharingDurability.test.js
@@ -380,3 +380,19 @@ it('does not register a bucket whose existing identity cannot be read', async ()
expect(await readFile(registryPath, 'utf8')).toBe(before);
expect(await readFile(identityPath, 'utf8')).toBe('{"id":');
});
+
+it('merges federated goals without dropping a queued local edit', async () => {
+ const { mutateGoals } = await import('./identity/store.js');
+ const goalsPath = join(PATHS.digitalTwin, 'goals.json');
+ await seed(goalsPath, { goals: [{ id: 'local', progress: 0 }] });
+ await Promise.all([
+ dataSync.applyRemote('goals', { goals: [{ id: 'remote', updatedAt: '2026-01-01' }] }),
+ mutateGoals(doc => {
+ doc.goals.find(goal => goal.id === 'local').progress = 50;
+ return doc;
+ })
+ ]);
+ expect(JSON.parse(await readFile(goalsPath, 'utf8')).goals).toEqual([
+ { id: 'local', progress: 50 }, { id: 'remote', updatedAt: '2026-01-01' }
+ ]);
+});