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: recover calendar confirmations without duplicating goal progress (#8837)

[._.]/ Adam Eivyae6d424eb996
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 3473a775f2..8c75dfc163 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -119,6 +119,25 @@ Coordinator ownership and cancellation share one exclusive durable claim. Once o
A cancelled unowned accepted operation moves to `data/database-maintenance-cancelled/<operation-id>/` as local recovery evidence. These records remain filesystem-backed and included in backups; they are not a growing application collection. Restoring an active journal deliberately restores its fence: do not delete it merely to make startup succeed. See [database maintenance admission](BACKUP.md#database-maintenance-admission) for the operator contract and current limitations.
+### Calendar daily-review recovery
+
+Daily reviews remain in the existing `data/calendar/daily-reviews/<date>.json`
+file-primary store. An optional `pendingOperation` records the desired confirmation,
+its stable date/event `sourceKey`, and prior goal link before goal effects run.
+Only a successful goal-store write publishes the confirmation and clears the intent.
+An explicit daily-review read or confirmation retry replays pending work locally;
+history stays a read-only projection of completed confirmations. No recovery path
+calls an AI or calendar provider.
+
+Goal progress carries the same optional `sourceKey` in the existing identity goal
+store (including its MortalLoom mirror). A serialized goal mutation replaces or
+removes only matching entries, preserving manual and legacy progress. These are
+additive optional fields: old reviews and goal logs are read unchanged, with no
+backfill, seed, or install migration, because historical free-form entries cannot
+be safely assigned provenance. The journal stays machine-local; no new peer sync
+category is introduced. Existing filesystem backups cover the review intents and
+goal data together; interrupted intents remain retryable after restore.
+
## `asset-file-db-indexed` — bytes on disk, metadata in DB
**Definition.** Large binary payloads (images, video, audio, model weights) stay on disk as bytes, while their **searchable metadata** — provenance, gen params, favorites, notes, lineage, collection membership — lives in PostgreSQL as asset rows that reference the file by a stable key.
diff --git a/server/routes/calendar.test.js b/server/routes/calendar.test.js
index f57764bb67..392996a9ff 100644
--- a/server/routes/calendar.test.js
+++ b/server/routes/calendar.test.js
@@ -66,6 +66,7 @@ import calendarRoutes from './calendar.js';
import * as calendarAccounts from '../services/calendarAccounts.js';
import * as calendarSync from '../services/calendarSync.js';
import { getUserTimezone } from '../services/userTimezone.js';
+import * as dailyReview from '../services/dailyReview.js';
import * as calendarGoogleSync from '../services/calendarGoogleSync.js';
import * as calendarGoogleApiSync from '../services/calendarGoogleApiSync.js';
import * as googleAuth from '../services/googleAuth.js';
@@ -88,6 +89,14 @@ describe('Calendar Routes — normalized error handling', () => {
});
describe('thrown ServerErrors map to the standard JSON envelope', () => {
+ it('POST /review/:date/confirm preserves typed missing-goal errors', async () => {
+ dailyReview.confirmEvent.mockRejectedValue(new ServerError('Goal not found', { status: 404, code: 'GOAL_NOT_FOUND' }));
+ const response = await request(app).post('/api/calendar/review/2026-01-02/confirm')
+ .send({ eventId: 'event-a', happened: true, goalId: 'goal-a', durationMinutes: 30 });
+ expect(response.status).toBe(404);
+ expect(response.body.code).toBe('GOAL_NOT_FOUND');
+ });
+
it('POST /sync/:accountId surfaces a 409 sync-lock conflict', async () => {
calendarSync.syncAccount.mockRejectedValue(new ServerError('Sync already in progress', { status: 409 }));
diff --git a/server/services/dailyReview.js b/server/services/dailyReview.js
index 5861bb5a10..89f7e2c6d3 100644
--- a/server/services/dailyReview.js
+++ b/server/services/dailyReview.js
@@ -2,9 +2,11 @@ import { join } from 'path';
import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import * as calendarSync from './calendarSync.js';
import * as calendarAccounts from './calendarAccounts.js';
-import { addProgressEntry, getGoals } from './identity.js';
+import { getGoals, reconcileCalendarProgress } from './identity.js';
+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
const REVIEW_DIR = join(PATHS.calendar, 'daily-reviews');
+const reviewQueue = createKeyCachedQueue();
async function loadReview(date) {
await ensureDir(REVIEW_DIR);
@@ -16,12 +18,17 @@ async function saveReview(date, data) {
}
export async function getDailyReview(date) {
+ // Recover a durable intent before projecting confirmations or goal progress.
+ const existing = await reviewQueue(date, async () => {
+ const review = await loadReview(date) || { confirmations: {}, updatedAt: null };
+ await finishPendingReview(date, review);
+ return review;
+ });
// Get all events for this date across all accounts
const startDate = `${date}T00:00:00`;
const endDate = `${date}T23:59:59`;
- const [{ events }, existing, accounts, goalsData] = await Promise.all([
+ const [{ events }, accounts, goalsData] = await Promise.all([
calendarSync.getEvents({ startDate, endDate, limit: 200 }),
- loadReview(date).then(r => r || { confirmations: {}, updatedAt: null }),
calendarAccounts.listAccounts(),
getGoals()
]);
@@ -96,34 +103,50 @@ export async function getDailyReview(date) {
};
}
-export async function confirmEvent(date, { eventId, happened, goalId, durationMinutes, note }) {
- const existing = await loadReview(date) || { confirmations: {}, updatedAt: null };
-
- existing.confirmations[eventId] = {
- happened,
- goalId: goalId || null,
- durationMinutes: durationMinutes || null,
- note: note || '',
- confirmedAt: new Date().toISOString()
- };
- existing.updatedAt = new Date().toISOString();
-
- await saveReview(date, existing);
-
- // If event happened and linked to a goal, auto-create progress entry
- let progressEntry = null;
- if (happened && goalId) {
- const entryNote = note || 'Calendar event confirmed';
- progressEntry = await addProgressEntry(goalId, {
- date,
- note: entryNote,
- ...(durationMinutes ? { durationMinutes } : {})
- });
- console.log(`📅 Auto-logged progress for goal ${goalId} from daily review`);
- }
+// The intent is saved before goal effects; only completed effects publish a
+// confirmation. Replaying after either write failed uses the same source key.
+async function finishPendingReview(date, review) {
+ const pending = review.pendingOperation;
+ if (!pending) return null;
+ const { eventId, confirmation, sourceKey } = pending;
+ const progressEntry = await reconcileCalendarProgress(sourceKey, {
+ goalId: confirmation.happened ? confirmation.goalId : null,
+ date,
+ note: confirmation.note || 'Calendar event confirmed',
+ durationMinutes: confirmation.durationMinutes
+ });
+ review.confirmations[eventId] = confirmation;
+ review.updatedAt = confirmation.confirmedAt;
+ delete review.pendingOperation;
+ await saveReview(date, review);
+ return progressEntry;
+}
- console.log(`📅 Event ${eventId} ${happened ? 'confirmed' : 'skipped'} for ${date}`);
- return { confirmation: existing.confirmations[eventId], progressEntry };
+export function confirmEvent(date, { eventId, happened, goalId, durationMinutes, note }) {
+ return reviewQueue(date, async () => {
+ const review = await loadReview(date) || { confirmations: {}, updatedAt: null };
+ // A new desired state for the SAME event may supersede an interrupted intent
+ // (including a goal that was deleted). Other events must finish theirs first.
+ if (review.pendingOperation?.eventId !== eventId) await finishPendingReview(date, review);
+ const sourceKey = `calendar-review:${date}:${eventId}`;
+ review.pendingOperation = {
+ eventId,
+ sourceKey,
+ priorGoalId: review.pendingOperation?.priorGoalId ?? review.confirmations[eventId]?.goalId ?? null,
+ confirmation: {
+ happened,
+ goalId: goalId || null,
+ durationMinutes: durationMinutes || null,
+ note: note || '',
+ sourceKey,
+ confirmedAt: new Date().toISOString()
+ }
+ };
+ await saveReview(date, review);
+ const progressEntry = await finishPendingReview(date, review);
+ console.log(`📅 Event ${eventId} ${happened ? 'confirmed' : 'skipped'} for ${date}`);
+ return { confirmation: review.confirmations[eventId], progressEntry };
+ });
}
export async function getDailyReviewHistory(startDate, endDate) {
diff --git a/server/services/dailyReview.test.js b/server/services/dailyReview.test.js
new file mode 100644
index 0000000000..4c20dda703
--- /dev/null
+++ b/server/services/dailyReview.test.js
@@ -0,0 +1,141 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { dirname, join } from 'node:path';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const fault = vi.hoisted(() => ({ kind: null, countdown: 0 }));
+vi.mock('../lib/fileUtils.js', async original => {
+ const actual = await original();
+ return makePathsProxy(actual, {
+ dataRoot: () => lazyTempDataRoot('portos-review-recovery-'),
+ overrides: {
+ atomicWrite: async (path, ...args) => {
+ const kind = path.endsWith('goals.json') ? 'goals' : 'review';
+ if (kind === fault.kind && --fault.countdown === 0) throw new Error('injected write failure');
+ return actual.atomicWrite(path, ...args);
+ }
+ }
+ });
+});
+vi.mock('./mortalLoomStore.js', () => ({
+ isMortalLoomEnabled: async () => false,
+ mlArrayIfEnabled: async () => null,
+ mlReplace: vi.fn()
+}));
+vi.mock('./calendarSync.js', () => ({ getEvents: async () => ({ events: [{ id: 'event-a' }] }) }));
+vi.mock('./calendarAccounts.js', () => ({ listAccounts: async () => [] }));
+vi.mock('./aiProvider.js', () => ({ callProviderAISimple: vi.fn(), parseLLMJSON: vi.fn() }));
+vi.mock('./meatspaceCalendar.js', () => ({ getActivities: async () => [] }));
+vi.mock('./identity.js', async () => {
+ const goals = await import('./identity/goals.js');
+ const store = await import('./identity/store.js');
+ return { ...goals, getGoals: () => store.loadJSON(store.GOALS_FILE, store.DEFAULT_GOALS, { strict: true }) };
+});
+
+import { PATHS } from '../lib/fileUtils.js';
+const date = '2026-01-02';
+const reviewPath = join(PATHS.calendar, 'daily-reviews', `${date}.json`);
+const goalsPath = join(PATHS.digitalTwin, 'goals.json');
+const input = { eventId: 'event-a', happened: true, goalId: 'goal-a', durationMinutes: 30, note: 'Practice' };
+const read = async path => JSON.parse(await readFile(path, 'utf8'));
+const write = async (path, value) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, JSON.stringify(value)); };
+let review;
+let goals;
+beforeEach(async () => {
+ fault.kind = null;
+ vi.resetModules();
+ await rm(PATHS.calendar, { force: true, recursive: true });
+ await write(goalsPath, { goals: [
+ { id: 'goal-a', progressLog: [{ id: 'manual', date, note: 'Manual', durationMinutes: 15 }] },
+ { id: 'goal-b', progressLog: [] }
+ ] });
+ review = await import('./dailyReview.js');
+ goals = await import('./identity/goals.js');
+});
+afterAll(cleanupTempDataRoots);
+
+const allProgress = async () => (await read(goalsPath)).goals.flatMap(goal => goal.progressLog || []);
+
+describe('calendar confirmation persistence workflow', () => {
+ it('replays a lost response, edits and moves one owned entry, then skips without removing manual progress', async () => {
+ const first = await review.confirmEvent(date, input);
+ const replay = await review.confirmEvent(date, input);
+ expect(replay.progressEntry.id).toBe(first.progressEntry.id);
+ expect(await allProgress()).toHaveLength(2);
+ const edited = await review.confirmEvent(date, { ...input, durationMinutes: 45, note: 'Updated' });
+ expect(edited.progressEntry).toMatchObject({ id: first.progressEntry.id, durationMinutes: 45, note: 'Updated' });
+ await review.confirmEvent(date, { ...input, goalId: 'goal-b' });
+ const saved = await read(goalsPath);
+ expect(saved.goals[0].progressLog.map(entry => entry.id)).toEqual(['manual']);
+ expect(saved.goals[1].progressLog).toEqual([expect.objectContaining({ id: first.progressEntry.id })]);
+ await review.confirmEvent(date, { ...input, goalId: 'goal-b', happened: false });
+ expect(await allProgress()).toEqual([expect.objectContaining({ id: 'manual' })]);
+ expect((await read(reviewPath)).confirmations['event-a'].happened).toBe(false);
+ });
+
+ it('serializes different events, different dates and manual writes against the shared goal store', async () => {
+ await Promise.all([
+ review.confirmEvent(date, input),
+ review.confirmEvent(date, { ...input, eventId: 'event-b' }),
+ review.confirmEvent('2026-01-03', input),
+ goals.addProgressEntry('goal-a', { date, note: 'Concurrent manual', durationMinutes: 10 })
+ ]);
+ expect(Object.keys((await read(reviewPath)).confirmations).sort()).toEqual(['event-a', 'event-b']);
+ expect(await allProgress()).toHaveLength(5);
+ expect((await allProgress()).filter(entry => entry.sourceKey)).toHaveLength(3);
+ });
+
+ it.each([
+ ['review', 1, false], // intent never persisted
+ ['goals', 1, true], // intent persisted, goal write failed
+ ['review', 2, true] // goal committed, confirmation commit failed
+ ])('recovers a %s write failure at step %s on retry after a restart', async (kind, countdown, pending) => {
+ fault.kind = kind;
+ fault.countdown = countdown;
+ await expect(review.confirmEvent(date, input)).rejects.toThrow('injected write failure');
+ if (pending) {
+ const interrupted = await read(reviewPath);
+ expect(interrupted.confirmations).toEqual({});
+ expect(interrupted.pendingOperation.sourceKey).toBe(`calendar-review:${date}:event-a`);
+ } else {
+ await expect(readFile(reviewPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ }
+ fault.kind = null;
+ vi.resetModules();
+ review = await import('./dailyReview.js');
+ await review.confirmEvent(date, input);
+ expect((await allProgress()).filter(entry => entry.sourceKey)).toHaveLength(1);
+ expect((await read(reviewPath)).pendingOperation).toBeUndefined();
+ });
+
+ it('an explicit read completes an interrupted intent without provider calls', async () => {
+ fault.kind = 'review';
+ fault.countdown = 2;
+ await expect(review.confirmEvent(date, input)).rejects.toThrow('injected write failure');
+ fault.kind = null;
+ vi.resetModules();
+ review = await import('./dailyReview.js');
+ const recovered = await review.getDailyReview(date);
+ expect(recovered.confirmations['event-a'].happened).toBe(true);
+ expect(recovered.progressEntries.filter(entry => entry.sourceKey)).toHaveLength(1);
+ const { callProviderAISimple } = await import('./aiProvider.js');
+ expect(callProviderAISimple).not.toHaveBeenCalled();
+ });
+
+ it('rejects missing goals before completing, and allows the same event to supersede that pending intent', async () => {
+ await expect(review.confirmEvent(date, { ...input, goalId: 'missing' }))
+ .rejects.toMatchObject({ status: 404, code: 'GOAL_NOT_FOUND' });
+ expect((await read(reviewPath)).confirmations).toEqual({});
+ expect(await allProgress()).toEqual([expect.objectContaining({ id: 'manual' })]);
+ await review.confirmEvent(date, { ...input, happened: false });
+ expect((await read(reviewPath)).pendingOperation).toBeUndefined();
+ });
+
+ it('preserves legacy confirmation fields and never infers ownership from date or free-form notes', async () => {
+ const legacy = { happened: true, goalId: 'goal-a', note: 'Manual', confirmedAt: '2025-12-01T00:00:00Z' };
+ await write(reviewPath, { confirmations: { legacy, 'event-a': legacy }, updatedAt: null });
+ await review.confirmEvent(date, { ...input, happened: false });
+ expect((await read(reviewPath)).confirmations.legacy).toEqual(legacy);
+ expect(await allProgress()).toEqual([expect.objectContaining({ id: 'manual' })]);
+ });
+});
diff --git a/server/services/identity.js b/server/services/identity.js
index 218bed6b99..8269a5abed 100644
--- a/server/services/identity.js
+++ b/server/services/identity.js
@@ -52,6 +52,7 @@ export {
unlinkActivity,
addMilestone,
addProgressEntry,
+ reconcileCalendarProgress,
deleteProgressEntry,
completeMilestone,
linkCalendarToGoal,
diff --git a/server/services/identity/goals.js b/server/services/identity/goals.js
index 32d58bfd86..9da35e3f01 100644
--- a/server/services/identity/goals.js
+++ b/server/services/identity/goals.js
@@ -13,7 +13,8 @@ import {
DEFAULT_GOALS,
DEFAULT_LONGEVITY,
loadJSON,
- saveJSON
+ saveJSON,
+ mutateGoals
} from './store.js';
import { applyFreshTimeHorizons, deriveLongevity } from './longevity.js';
@@ -491,42 +492,72 @@ export async function addMilestone(goalId, { title, targetDate }) {
}
export async function addProgressEntry(goalId, { date, note, durationMinutes }) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
-
- if (!goal.progressLog) goal.progressLog = [];
-
- const entry = {
- id: `prog-${uuidv4()}`,
- date,
- note,
- durationMinutes: durationMinutes || null,
- createdAt: new Date().toISOString()
- };
-
- goal.progressLog.push(entry);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
-
- console.log(`📝 Progress logged for "${goal.title}": ${note} (${durationMinutes ? durationMinutes + 'min' : 'no duration'})`);
+ let entry = null;
+ await mutateGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ if (!goal) return goals;
+ entry = {
+ id: `prog-${uuidv4()}`,
+ date,
+ note,
+ durationMinutes: durationMinutes || null,
+ createdAt: new Date().toISOString()
+ };
+ (goal.progressLog ||= []).push(entry);
+ goal.updatedAt = goals.updatedAt = new Date().toISOString();
+ return goals;
+ });
return entry;
}
export async function deleteProgressEntry(goalId, entryId) {
- const goals = await loadJSON(GOALS_FILE, DEFAULT_GOALS);
- const goal = goals.goals.find(g => g.id === goalId);
- if (!goal) return null;
-
- const idx = (goal.progressLog || []).findIndex(e => e.id === entryId);
- if (idx === -1) return null;
+ let result = null;
+ await mutateGoals(goals => {
+ const goal = goals.goals.find(g => g.id === goalId);
+ const idx = (goal?.progressLog || []).findIndex(e => e.id === entryId);
+ if (idx === -1) return goals;
+ goal.progressLog.splice(idx, 1);
+ goal.updatedAt = goals.updatedAt = new Date().toISOString();
+ result = { deleted: true };
+ return goals;
+ });
+ return result;
+}
- goal.progressLog.splice(idx, 1);
- goal.updatedAt = new Date().toISOString();
- goals.updatedAt = new Date().toISOString();
- await saveJSON(GOALS_FILE, goals);
- return { deleted: true };
+/** Reconcile only progress owned by one calendar review; manual/legacy logs stay intact. */
+export async function reconcileCalendarProgress(sourceKey, { goalId, date, note, durationMinutes }) {
+ let entry = null;
+ await mutateGoals(goals => {
+ const target = goalId ? goals.goals.find(goal => goal.id === goalId) : null;
+ if (goalId && !target) {
+ throw new ServerError('Goal not found', { status: 404, code: 'GOAL_NOT_FOUND' });
+ }
+ const previous = goals.goals.flatMap(goal => goal.progressLog || [])
+ .find(progress => progress.sourceKey === sourceKey);
+ const now = new Date().toISOString();
+ // One store mutation moves the owned entry across goals atomically. Scanning
+ // by provenance also repairs a retry after the old link changed on disk.
+ for (const goal of goals.goals) {
+ if (!goal.progressLog?.some(progress => progress.sourceKey === sourceKey)) continue;
+ goal.progressLog = goal.progressLog.filter(progress => progress.sourceKey !== sourceKey);
+ goal.updatedAt = now;
+ }
+ if (target) {
+ entry = {
+ id: previous?.id || `prog-${uuidv4()}`,
+ sourceKey,
+ date,
+ note,
+ durationMinutes: durationMinutes || null,
+ createdAt: previous?.createdAt || now
+ };
+ (target.progressLog ||= []).push(entry);
+ target.updatedAt = now;
+ }
+ goals.updatedAt = now;
+ return goals;
+ });
+ return entry;
}
export async function completeMilestone(goalId, milestoneId) {
diff --git a/server/services/personalStoreReadSafety.test.js b/server/services/personalStoreReadSafety.test.js
index f3a81241ba..afdec1fced 100644
--- a/server/services/personalStoreReadSafety.test.js
+++ b/server/services/personalStoreReadSafety.test.js
@@ -37,7 +37,7 @@ vi.mock('./obsidian.js', () => ({}));
vi.mock('./notifications.js', () => ({ addNotification: vi.fn(), NOTIFICATION_TYPES: {}, exists: async () => false }));
vi.mock('./calendarSync.js', () => ({}));
vi.mock('./calendarAccounts.js', () => ({}));
-vi.mock('./identity.js', () => ({ addProgressEntry: vi.fn(), getGoals: async () => ({ goals: [] }) }));
+vi.mock('./identity.js', () => ({ reconcileCalendarProgress: vi.fn(), getGoals: async () => ({ goals: [] }) }));
vi.mock('./settings.js', async () => {
const { EventEmitter } = await import('events');