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

address review (codex): coordinate autobiography writers

[._.]/ Adam Eivy9916b4a1b2eb
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index 9f0a14b134..7ee5c9279e 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -9,9 +9,12 @@
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { recordTombstone } from '../lib/tombstones.js';
+import {
+ queueAutobiographyConfigWrite,
+ queueAutobiographyStoriesWrite
+} from './autobiographyFileQueues.js';
import { addNotification, NOTIFICATION_TYPES, exists as notificationExists } from './notifications.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { callProviderAISimple, parseLLMJSON } from './aiProvider.js';
@@ -19,8 +22,6 @@ import { callProviderAISimple, parseLLMJSON } from './aiProvider.js';
const DATA_DIR = join(PATHS.digitalTwin, 'autobiography');
const STORIES_FILE = join(DATA_DIR, 'stories.json');
const CONFIG_FILE = join(DATA_DIR, 'config.json');
-const queueStoriesWrite = createFileWriteQueue();
-const queueConfigWrite = createFileWriteQueue();
// Thematic prompt bank organized by life themes
const PROMPT_THEMES = [
@@ -215,7 +216,7 @@ export function getThemes() {
* @param {string} [excludePromptId] - Prompt ID to exclude (used by skip to avoid returning the same prompt)
*/
export async function getNextPrompt(excludePromptId) {
- return queueStoriesWrite(async () => {
+ return queueAutobiographyStoriesWrite(async () => {
const data = await loadStories();
const usedPrompts = data.usedPrompts || [];
@@ -282,7 +283,7 @@ export function getPromptById(promptId) {
* Save a story for a given prompt
*/
export async function saveStory({ promptId, content, parentStoryId, customPromptText }) {
- return queueStoriesWrite(async () => {
+ return queueAutobiographyStoriesWrite(async () => {
const data = await loadStories();
const prompt = getPromptById(promptId);
@@ -321,7 +322,7 @@ export async function saveStory({ promptId, content, parentStoryId, customPrompt
* Update an existing story
*/
export async function updateStory(storyId, content) {
- return queueStoriesWrite(async () => {
+ return queueAutobiographyStoriesWrite(async () => {
const data = await loadStories();
const story = data.stories.find(s => s.id === storyId);
@@ -350,7 +351,7 @@ export async function updateStory(storyId, content) {
* carries the same id on every peer.
*/
export async function deleteStory(storyId) {
- return queueStoriesWrite(async () => {
+ return queueAutobiographyStoriesWrite(async () => {
const data = await loadStories();
const idx = data.stories.findIndex(s => s.id === storyId);
if (idx === -1) return null;
@@ -426,7 +427,7 @@ export async function getConfig() {
* Update configuration
*/
export async function updateConfig(updates) {
- return queueConfigWrite(async () => {
+ return queueAutobiographyConfigWrite(async () => {
const config = await loadConfig();
const updated = { ...config, ...updates };
await saveConfig(updated);
@@ -524,7 +525,7 @@ Return a JSON array of exactly 3 strings, nothing else. Example:
// Re-read inside the file queue so a story mutation that completed while the
// provider was running is preserved in the write-back.
- const storedFollowUps = await queueStoriesWrite(async () => {
+ const storedFollowUps = await queueAutobiographyStoriesWrite(async () => {
const currentData = await loadStories();
const currentStory = currentData.stories.find(s => s.id === storyId);
if (!currentStory) return null;
@@ -639,51 +640,50 @@ Rules:
* Called by the autonomous job system or can be triggered manually.
*/
export async function checkAndPrompt() {
- const config = await loadConfig();
-
- if (!config.enabled) {
- return { prompted: false, reason: 'disabled' };
- }
+ return queueAutobiographyConfigWrite(async () => {
+ const config = await loadConfig();
- const now = Date.now();
- const intervalMs = (config.intervalHours || 24) * 60 * 60 * 1000;
- const lastPromptTime = config.lastPromptAt ? new Date(config.lastPromptAt).getTime() : 0;
+ if (!config.enabled) {
+ return { prompted: false, reason: 'disabled' };
+ }
- if (now - lastPromptTime < intervalMs) {
- return { prompted: false, reason: 'not_due' };
- }
+ const now = Date.now();
+ const intervalMs = (config.intervalHours || 24) * 60 * 60 * 1000;
+ const lastPromptTime = config.lastPromptAt ? new Date(config.lastPromptAt).getTime() : 0;
- // Check if there's already an unread autobiography notification
- const alreadyNotified = await notificationExists(
- NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT
- );
+ if (now - lastPromptTime < intervalMs) {
+ return { prompted: false, reason: 'not_due' };
+ }
- if (alreadyNotified) {
- return { prompted: false, reason: 'pending_notification' };
- }
+ // Check if there's already an unread autobiography notification
+ const alreadyNotified = await notificationExists(
+ NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT
+ );
- const prompt = await getNextPrompt();
-
- await addNotification({
- type: NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,
- title: '5-Minute Story Time',
- description: `${prompt.themeLabel}: ${prompt.text}`,
- priority: 'low',
- link: `/digital-twin/autobiography?prompt=${prompt.id}`,
- metadata: {
- promptId: prompt.id,
- themeId: prompt.themeId
+ if (alreadyNotified) {
+ return { prompted: false, reason: 'pending_notification' };
}
- });
- await queueConfigWrite(async () => {
- const currentConfig = await loadConfig();
- currentConfig.lastPromptAt = new Date().toISOString();
- currentConfig.lastPromptId = prompt.id;
- await saveConfig(currentConfig);
- });
+ const prompt = await getNextPrompt();
+
+ await addNotification({
+ type: NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,
+ title: '5-Minute Story Time',
+ description: `${prompt.themeLabel}: ${prompt.text}`,
+ priority: 'low',
+ link: `/digital-twin/autobiography?prompt=${prompt.id}`,
+ metadata: {
+ promptId: prompt.id,
+ themeId: prompt.themeId
+ }
+ });
+
+ config.lastPromptAt = new Date().toISOString();
+ config.lastPromptId = prompt.id;
+ await saveConfig(config);
- console.log(`📖 Autobiography prompt sent: ${prompt.themeLabel} - ${prompt.text.substring(0, 50)}...`);
+ console.log(`📖 Autobiography prompt sent: ${prompt.themeLabel} - ${prompt.text.substring(0, 50)}...`);
- return { prompted: true, prompt };
+ return { prompted: true, prompt };
+ });
}
diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.js
index c5bf0e4959..b134a80a0f 100644
--- a/server/services/autobiography.test.js
+++ b/server/services/autobiography.test.js
@@ -672,6 +672,17 @@ describe('Autobiography - checkAndPrompt', () => {
expect(notification.metadata).not.toHaveProperty('type');
});
+ it('creates only one notification across concurrent due checks', async () => {
+ const oldTime = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();
+ setupPersistentMocks(makeStoriesData(), makeConfigData({ lastPromptAt: oldTime }));
+
+ const results = await Promise.all([checkAndPrompt(), checkAndPrompt()]);
+
+ expect(results.filter(result => result.prompted)).toHaveLength(1);
+ expect(results.filter(result => result.reason === 'not_due')).toHaveLength(1);
+ expect(mockAddNotification).toHaveBeenCalledTimes(1);
+ });
+
it('should prompt when lastPromptAt is null (first time)', async () => {
setupMocks(makeStoriesData(), makeConfigData({ lastPromptAt: null }));
diff --git a/server/services/autobiography.tombstone.test.js b/server/services/autobiography.tombstone.test.js
index 725b6daf37..425ede8dc4 100644
--- a/server/services/autobiography.tombstone.test.js
+++ b/server/services/autobiography.tombstone.test.js
@@ -118,6 +118,19 @@ describe('autobiography story tombstones (#3531)', () => {
]));
expect((await getStories()).map((s) => s.id)).toEqual(['peer-story-1']);
});
+
+ it('preserves local and peer stories when their writes start concurrently', async () => {
+ await Promise.all([
+ newStory('A local memory.'),
+ applyDigitalTwinRemote(peerSnapshotWith([
+ { id: 'peer-story-1', themeId: 'family', content: 'A peer memory.', createdAt: '2026-01-01T00:00:00.000Z' },
+ ])),
+ ]);
+
+ const stories = await getStories();
+ expect(stories).toHaveLength(2);
+ expect(stories.map((story) => story.id)).toContain('peer-story-1');
+ });
});
describe('mergeAutobiographyStories tombstones (#3531)', () => {
diff --git a/server/services/autobiographyFileQueues.js b/server/services/autobiographyFileQueues.js
new file mode 100644
index 0000000000..3422948e65
--- /dev/null
+++ b/server/services/autobiographyFileQueues.js
@@ -0,0 +1,6 @@
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+
+// These files have writers in both autobiography.js and digital-twin-sync.js.
+// Sharing the tails keeps every read-modify-write cycle ordered across services.
+export const queueAutobiographyStoriesWrite = createFileWriteQueue();
+export const queueAutobiographyConfigWrite = createFileWriteQueue();
diff --git a/server/services/digital-twin-sync.js b/server/services/digital-twin-sync.js
index 7cae31aa0e..f29386a0e6 100644
--- a/server/services/digital-twin-sync.js
+++ b/server/services/digital-twin-sync.js
@@ -63,6 +63,7 @@ import { atomicWrite, readJSONFile, ensureDir, PATHS } from '../lib/fileUtils.js
import { canonicalStringify, isPlainObject } from '../lib/objects.js';
import { normalizeTombstones, mergeTombstones, isTombstoned, pruneTombstones, tombstonesEqual } from '../lib/tombstones.js';
import { compareNewerWins } from '../lib/lwwTimestamp.js';
+import { queueAutobiographyStoriesWrite } from './autobiographyFileQueues.js';
const DIR = PATHS.digitalTwin;
const IDENTITY_FILE = join(DIR, 'identity.json');
@@ -943,7 +944,9 @@ export async function applyDigitalTwinRemote(remoteData) {
if (isPlainObject(remoteData.autobiography)) {
// stories only — config (prompt schedule) is intentionally machine-local.
- count += await applyMerge(AUTOBIO_STORIES_FILE, remoteData.autobiography.stories, mergeAutobiographyStories, { dir: AUTOBIO_DIR });
+ count += await queueAutobiographyStoriesWrite(() =>
+ applyMerge(AUTOBIO_STORIES_FILE, remoteData.autobiography.stories, mergeAutobiographyStories, { dir: AUTOBIO_DIR })
+ );
}
count += await applySocialAccounts(remoteData.socialAccounts);