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

feat(digital-twin): add autobiography story prompt system

Adam Eivy8025e2002202
diff --git a/.changelog/v0.18.x.md b/.changelog/v0.18.x.md
index ac52cba093..2776b96613 100644
--- a/.changelog/v0.18.x.md
+++ b/.changelog/v0.18.x.md
@@ -6,6 +6,16 @@ Released: YYYY-MM-DD
Continued reliability improvements and codebase hardening.
+## Features
+
+### Autobiography Story Prompt System
+- New digital twin feature that prompts the user on a regular basis to write 5-minute autobiographical stories based on thematic prompts — builds a personal autobiography over time
+- 12 life themes with 60 total prompts: Childhood, Family, Friendship, Education, Career, Travel, Challenges, Joy, Love, Identity, Creativity, Turning Points
+- Prompts rotate across themes, balanced to least-written theme first, and never repeat until all are used
+- Configurable prompt interval (12h to weekly) with CoS notification integration — clicking the notification deep-links to the writing UI with the prompt pre-loaded
+- New Autobiography tab in Digital Twin page with writing mode, theme filtering, story editing/deletion, word count, and settings panel
+- Registered as a default autonomous job (`job-autobiography-prompt`) that checks timing and sends notifications when due
+
## Improvements
### Guard remaining unprotected JSON.parse calls (S7 complete)
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.js
index 12be456a83..75309fd348 100644
--- a/client/src/components/digital-twin/constants.js
+++ b/client/src/components/digital-twin/constants.js
@@ -24,7 +24,8 @@ import {
AlertOctagon,
Fingerprint,
Globe,
- Dna
+ Dna,
+ PenLine
} from 'lucide-react';
// Main navigation tabs
@@ -37,6 +38,7 @@ export const TABS = [
{ id: 'accounts', label: 'Accounts', icon: Globe },
{ id: 'genome', label: 'Genome', icon: Dna },
{ id: 'interview', label: 'Interview', icon: MessageSquare },
+ { id: 'autobiography', label: 'Autobiography', icon: PenLine },
{ id: 'import', label: 'Import', icon: Upload },
{ id: 'export', label: 'Export', icon: Download }
];
diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
new file mode 100644
index 0000000000..9a4ce2f903
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
@@ -0,0 +1,407 @@
+import { useState, useEffect, useCallback } from 'react';
+import { useSearchParams } from 'react-router-dom';
+import {
+ BookOpen,
+ PenLine,
+ Clock,
+ ChevronDown,
+ ChevronUp,
+ Trash2,
+ Save,
+ RefreshCw,
+ Send,
+ Settings,
+ SkipForward,
+ X
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from 'react-hot-toast';
+
+export default function AutobiographyTab({ onRefresh }) {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const [stats, setStats] = useState(null);
+ const [stories, setStories] = useState([]);
+ const [themes, setThemes] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [filterTheme, setFilterTheme] = useState(null);
+
+ // Writing state
+ const [currentPrompt, setCurrentPrompt] = useState(null);
+ const [writing, setWriting] = useState(false);
+ const [storyContent, setStoryContent] = useState('');
+ const [saving, setSaving] = useState(false);
+
+ // Config state
+ const [showConfig, setShowConfig] = useState(false);
+ const [config, setConfig] = useState(null);
+
+ // Edit state
+ const [editingStory, setEditingStory] = useState(null);
+ const [editContent, setEditContent] = useState('');
+
+ // Expanded story
+ const [expandedStory, setExpandedStory] = useState(null);
+
+ const loadData = useCallback(async () => {
+ const [statsData, storiesData, themesData, configData] = await Promise.all([
+ api.getAutobiographyStats().catch(() => null),
+ api.getAutobiographyStories(filterTheme).catch(() => []),
+ api.getAutobiographyThemes().catch(() => []),
+ api.getAutobiographyConfig().catch(() => null)
+ ]);
+ setStats(statsData);
+ setStories(storiesData);
+ setThemes(themesData);
+ setConfig(configData);
+ setLoading(false);
+ }, [filterTheme]);
+
+ useEffect(() => {
+ loadData();
+ }, [loadData]);
+
+ // Auto-load prompt from URL param (when arriving from notification)
+ useEffect(() => {
+ const promptParam = searchParams.get('prompt');
+ if (promptParam && !loading) {
+ loadPromptById(promptParam);
+ setSearchParams({}, { replace: true });
+ }
+ }, [loading, searchParams]);
+
+ const loadPromptById = async (promptId) => {
+ const prompt = await api.getAutobiographyPromptById(promptId).catch(() => null);
+ if (prompt) {
+ setCurrentPrompt(prompt);
+ setWriting(true);
+ setStoryContent('');
+ }
+ };
+
+ const startWriting = async () => {
+ const prompt = await api.getAutobiographyPrompt().catch((err) => {
+ toast.error(err.message);
+ return null;
+ });
+ if (prompt) {
+ setCurrentPrompt(prompt);
+ setWriting(true);
+ setStoryContent('');
+ }
+ };
+
+ const skipPrompt = async () => {
+ const prompt = await api.getAutobiographyPrompt().catch(() => null);
+ if (prompt && prompt.id !== currentPrompt?.id) {
+ setCurrentPrompt(prompt);
+ setStoryContent('');
+ } else {
+ toast('No more prompts available right now', { icon: 'ℹ️' });
+ }
+ };
+
+ const saveStory = async () => {
+ if (!storyContent.trim()) {
+ toast.error('Write something before saving');
+ return;
+ }
+ setSaving(true);
+ const result = await api.saveAutobiographyStory(currentPrompt.id, storyContent.trim())
+ .catch((err) => { toast.error(err.message); return null; });
+
+ if (result) {
+ toast.success(`Story saved (${result.wordCount} words)`);
+ setWriting(false);
+ setCurrentPrompt(null);
+ setStoryContent('');
+ loadData();
+ onRefresh?.();
+ }
+ setSaving(false);
+ };
+
+ const handleUpdateStory = async (storyId) => {
+ if (!editContent.trim()) return;
+ const result = await api.updateAutobiographyStory(storyId, editContent.trim())
+ .catch((err) => { toast.error(err.message); return null; });
+ if (result) {
+ toast.success('Story updated');
+ setEditingStory(null);
+ setEditContent('');
+ loadData();
+ }
+ };
+
+ const handleDeleteStory = async (storyId) => {
+ const result = await api.deleteAutobiographyStory(storyId)
+ .catch((err) => { toast.error(err.message); return null; });
+ if (result) {
+ toast.success('Story deleted');
+ loadData();
+ }
+ };
+
+ const handleConfigUpdate = async (updates) => {
+ const result = await api.updateAutobiographyConfig(updates)
+ .catch((err) => { toast.error(err.message); return null; });
+ if (result) {
+ setConfig(result);
+ toast.success('Settings updated');
+ }
+ };
+
+ const wordCount = storyContent.split(/\s+/).filter(Boolean).length;
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-12">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6 max-w-4xl">
+ {/* Header Stats */}
+ <div className="flex flex-wrap items-center gap-4">
+ <div className="flex items-center gap-2">
+ <BookOpen className="w-5 h-5 text-amber-400" />
+ <span className="text-lg font-semibold text-white">Autobiography</span>
+ </div>
+ {stats && (
+ <div className="flex flex-wrap gap-3 text-sm text-gray-400">
+ <span>{stats.totalStories} stories</span>
+ <span>{stats.totalWords.toLocaleString()} words</span>
+ <span>{stats.promptsRemaining} prompts remaining</span>
+ </div>
+ )}
+ <div className="ml-auto flex items-center gap-2">
+ <button
+ onClick={() => setShowConfig(!showConfig)}
+ className="p-2 rounded text-gray-400 hover:text-white hover:bg-port-card transition-colors"
+ title="Settings"
+ >
+ <Settings size={16} />
+ </button>
+ <button
+ onClick={startWriting}
+ className="flex items-center gap-2 px-3 py-2 bg-port-accent text-white rounded text-sm font-medium hover:bg-port-accent/80 transition-colors"
+ >
+ <PenLine size={14} />
+ Write a Story
+ </button>
+ </div>
+ </div>
+
+ {/* Config Panel */}
+ {showConfig && config && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <h3 className="text-sm font-medium text-white">Prompt Settings</h3>
+ <div className="flex flex-wrap items-center gap-4">
+ <label className="flex items-center gap-2 text-sm text-gray-300">
+ <input
+ type="checkbox"
+ checked={config.enabled}
+ onChange={(e) => handleConfigUpdate({ enabled: e.target.checked })}
+ className="rounded border-port-border"
+ />
+ Enable automatic prompts
+ </label>
+ <label className="flex items-center gap-2 text-sm text-gray-300">
+ Prompt every
+ <select
+ value={config.intervalHours}
+ onChange={(e) => handleConfigUpdate({ intervalHours: parseInt(e.target.value, 10) })}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
+ >
+ <option value="12">12 hours</option>
+ <option value="24">24 hours</option>
+ <option value="48">2 days</option>
+ <option value="72">3 days</option>
+ <option value="168">Weekly</option>
+ </select>
+ </label>
+ </div>
+ {config.lastPromptAt && (
+ <p className="text-xs text-gray-500">
+ Last prompt: {new Date(config.lastPromptAt).toLocaleString()}
+ </p>
+ )}
+ </div>
+ )}
+
+ {/* Writing Mode */}
+ {writing && currentPrompt && (
+ <div className="bg-port-card border border-port-accent/30 rounded-lg p-6 space-y-4">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <span className="text-xs font-medium text-port-accent uppercase tracking-wide">
+ {currentPrompt.themeLabel}
+ </span>
+ <p className="text-white text-lg mt-1">{currentPrompt.text}</p>
+ </div>
+ <button
+ onClick={() => { setWriting(false); setCurrentPrompt(null); setStoryContent(''); }}
+ className="p-1 text-gray-500 hover:text-white"
+ >
+ <X size={16} />
+ </button>
+ </div>
+
+ <textarea
+ value={storyContent}
+ onChange={(e) => setStoryContent(e.target.value)}
+ placeholder="Start writing your story... Take about 5 minutes."
+ className="w-full h-64 bg-port-bg border border-port-border rounded-lg p-4 text-white text-sm resize-y focus:outline-none focus:border-port-accent/50 placeholder-gray-600"
+ autoFocus
+ />
+
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3 text-sm text-gray-400">
+ <span>{wordCount} words</span>
+ <Clock size={14} />
+ <span>~{Math.max(1, Math.round(wordCount / 150))} min read</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={skipPrompt}
+ className="flex items-center gap-1 px-3 py-2 text-sm text-gray-400 hover:text-white transition-colors"
+ title="Get a different prompt"
+ >
+ <SkipForward size={14} />
+ Skip
+ </button>
+ <button
+ onClick={saveStory}
+ disabled={saving || !storyContent.trim()}
+ className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded text-sm font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {saving ? <RefreshCw size={14} className="animate-spin" /> : <Send size={14} />}
+ Save Story
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Theme Filter */}
+ {stories.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ <button
+ onClick={() => setFilterTheme(null)}
+ className={`px-3 py-1 rounded-full text-xs font-medium transition-colors ${
+ !filterTheme
+ ? 'bg-port-accent text-white'
+ : 'bg-port-card text-gray-400 hover:text-white border border-port-border'
+ }`}
+ >
+ All
+ </button>
+ {themes.map((theme) => (
+ <button
+ key={theme.id}
+ onClick={() => setFilterTheme(filterTheme === theme.id ? null : theme.id)}
+ className={`px-3 py-1 rounded-full text-xs font-medium transition-colors ${
+ filterTheme === theme.id
+ ? 'bg-port-accent text-white'
+ : 'bg-port-card text-gray-400 hover:text-white border border-port-border'
+ }`}
+ >
+ {theme.label}
+ {stats?.byTheme?.[theme.id] ? ` (${stats.byTheme[theme.id]})` : ''}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {/* Stories List */}
+ {stories.length === 0 && !writing && (
+ <div className="text-center py-12 text-gray-500">
+ <BookOpen className="w-12 h-12 mx-auto mb-3 opacity-50" />
+ <p className="text-lg">No stories yet</p>
+ <p className="text-sm mt-1">Click "Write a Story" to get your first prompt</p>
+ </div>
+ )}
+
+ {stories.map((story) => {
+ const isExpanded = expandedStory === story.id;
+ const isEditing = editingStory === story.id;
+
+ return (
+ <div
+ key={story.id}
+ className="bg-port-card border border-port-border rounded-lg overflow-hidden"
+ >
+ <button
+ onClick={() => setExpandedStory(isExpanded ? null : story.id)}
+ className="w-full flex items-center justify-between p-4 text-left hover:bg-port-bg/50 transition-colors"
+ >
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1">
+ <span className="text-xs font-medium text-port-accent">{story.themeLabel}</span>
+ <span className="text-xs text-gray-500">{story.wordCount} words</span>
+ <span className="text-xs text-gray-600">
+ {new Date(story.createdAt).toLocaleDateString()}
+ </span>
+ </div>
+ <p className="text-sm text-gray-300 truncate">{story.promptText}</p>
+ </div>
+ {isExpanded ? <ChevronUp size={16} className="text-gray-500 flex-shrink-0" /> : <ChevronDown size={16} className="text-gray-500 flex-shrink-0" />}
+ </button>
+
+ {isExpanded && (
+ <div className="border-t border-port-border p-4 space-y-3">
+ {isEditing ? (
+ <>
+ <textarea
+ value={editContent}
+ onChange={(e) => setEditContent(e.target.value)}
+ className="w-full h-48 bg-port-bg border border-port-border rounded p-3 text-white text-sm resize-y focus:outline-none focus:border-port-accent/50"
+ />
+ <div className="flex items-center gap-2 justify-end">
+ <button
+ onClick={() => { setEditingStory(null); setEditContent(''); }}
+ className="px-3 py-1.5 text-sm text-gray-400 hover:text-white"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={() => handleUpdateStory(story.id)}
+ className="flex items-center gap-1 px-3 py-1.5 bg-port-accent text-white rounded text-sm hover:bg-port-accent/80"
+ >
+ <Save size={12} />
+ Save
+ </button>
+ </div>
+ </>
+ ) : (
+ <>
+ <p className="text-sm text-white whitespace-pre-wrap leading-relaxed">
+ {story.content}
+ </p>
+ <div className="flex items-center gap-2 justify-end pt-2 border-t border-port-border/50">
+ <button
+ onClick={() => { setEditingStory(story.id); setEditContent(story.content); }}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-white transition-colors"
+ >
+ <PenLine size={12} />
+ Edit
+ </button>
+ <button
+ onClick={() => handleDeleteStory(story.id)}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-gray-400 hover:text-red-400 transition-colors"
+ >
+ <Trash2 size={12} />
+ Delete
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index a120dfae51..aa05ea5a7a 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -13,6 +13,7 @@ import TasteTab from '../components/digital-twin/tabs/TasteTab';
import AccountsTab from '../components/digital-twin/tabs/AccountsTab';
import InterviewTab from '../components/digital-twin/tabs/InterviewTab';
import GenomeTab from '../components/digital-twin/tabs/GenomeTab';
+import AutobiographyTab from '../components/digital-twin/tabs/AutobiographyTab';
import ImportTab from '../components/digital-twin/tabs/ImportTab';
import ExportTab from '../components/digital-twin/tabs/ExportTab';
@@ -63,6 +64,8 @@ export default function DigitalTwin() {
return <GenomeTab />;
case 'interview':
return <InterviewTab onRefresh={fetchData} />;
+ case 'autobiography':
+ return <AutobiographyTab onRefresh={fetchData} />;
case 'import':
return <ImportTab onRefresh={fetchData} />;
case 'export':
diff --git a/client/src/services/api.js b/client/src/services/api.js
index e1d4952cb4..28b70ce4b8 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1076,6 +1076,33 @@ export const resetTasteSection = (section) => request(`/digital-twin/taste/${sec
method: 'DELETE'
});
+// Digital Twin - Autobiography
+export const getAutobiographyStats = () => request('/digital-twin/autobiography');
+export const getAutobiographyConfig = () => request('/digital-twin/autobiography/config');
+export const updateAutobiographyConfig = (config) => request('/digital-twin/autobiography/config', {
+ method: 'PUT',
+ body: JSON.stringify(config)
+});
+export const getAutobiographyThemes = () => request('/digital-twin/autobiography/themes');
+export const getAutobiographyPrompt = () => request('/digital-twin/autobiography/prompt');
+export const getAutobiographyPromptById = (id) => request(`/digital-twin/autobiography/prompt/${id}`);
+export const getAutobiographyStories = (theme = null) =>
+ request(`/digital-twin/autobiography/stories${theme ? `?theme=${theme}` : ''}`);
+export const saveAutobiographyStory = (promptId, content) => request('/digital-twin/autobiography/stories', {
+ method: 'POST',
+ body: JSON.stringify({ promptId, content })
+});
+export const updateAutobiographyStory = (id, content) => request(`/digital-twin/autobiography/stories/${id}`, {
+ method: 'PUT',
+ body: JSON.stringify({ content })
+});
+export const deleteAutobiographyStory = (id) => request(`/digital-twin/autobiography/stories/${id}`, {
+ method: 'DELETE'
+});
+export const triggerAutobiographyPrompt = () => request('/digital-twin/autobiography/trigger', {
+ method: 'POST'
+});
+
// Digital Twin - Assessment Analyzer
export const analyzeAssessment = (content, providerId, model) =>
request('/digital-twin/interview/analyze', {
diff --git a/server/index.js b/server/index.js
index 86d52a8987..37ee2a9d9b 100644
--- a/server/index.js
+++ b/server/index.js
@@ -39,6 +39,7 @@ import browserRoutes from './routes/browser.js';
import moltworldToolsRoutes from './routes/moltworldTools.js';
import moltworldWsRoutes from './routes/moltworldWs.js';
import jiraRoutes from './routes/jira.js';
+import autobiographyRoutes from './routes/autobiography.js';
import { initSocket } from './services/socket.js';
import { initScriptRunner } from './services/scriptRunner.js';
import { errorMiddleware, setupProcessErrorHandlers, asyncHandler } from './lib/errorHandler.js';
@@ -202,6 +203,7 @@ app.use('/api/brain', brainRoutes);
app.use('/api/media', mediaRoutes);
app.use('/api/digital-twin/social-accounts', socialAccountsRoutes);
app.use('/api/digital-twin/genome', genomeRoutes);
+app.use('/api/digital-twin/autobiography', autobiographyRoutes);
app.use('/api/digital-twin', digitalTwinRoutes);
app.use('/api/lmstudio', lmstudioRoutes);
app.use('/api/browser', browserRoutes);
diff --git a/server/routes/autobiography.js b/server/routes/autobiography.js
new file mode 100644
index 0000000000..bf1d0f1801
--- /dev/null
+++ b/server/routes/autobiography.js
@@ -0,0 +1,161 @@
+/**
+ * Autobiography API Routes
+ *
+ * Handles endpoints for the autobiography story prompt feature:
+ * - Get themes, prompts, stories
+ * - Save and update stories
+ * - Configuration for prompt frequency
+ * - Manual prompt trigger
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import * as autobiographyService from '../services/autobiography.js';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+
+const router = Router();
+
+// Validation schemas
+const saveStorySchema = z.object({
+ promptId: z.string().min(1),
+ content: z.string().min(1).max(50000)
+});
+
+const updateStorySchema = z.object({
+ content: z.string().min(1).max(50000)
+});
+
+const updateConfigSchema = z.object({
+ enabled: z.boolean().optional(),
+ intervalHours: z.number().min(1).max(168).optional()
+});
+
+// =============================================================================
+// STATS & CONFIG
+// =============================================================================
+
+/**
+ * GET /api/digital-twin/autobiography
+ * Get autobiography stats and configuration
+ */
+router.get('/', asyncHandler(async (req, res) => {
+ const stats = await autobiographyService.getStats();
+ res.json(stats);
+}));
+
+/**
+ * GET /api/digital-twin/autobiography/config
+ * Get configuration
+ */
+router.get('/config', asyncHandler(async (req, res) => {
+ const config = await autobiographyService.getConfig();
+ res.json(config);
+}));
+
+/**
+ * PUT /api/digital-twin/autobiography/config
+ * Update configuration
+ */
+router.put('/config', asyncHandler(async (req, res) => {
+ const validated = validateRequest(updateConfigSchema, req.body);
+ const config = await autobiographyService.updateConfig(validated);
+ res.json(config);
+}));
+
+// =============================================================================
+// THEMES & PROMPTS
+// =============================================================================
+
+/**
+ * GET /api/digital-twin/autobiography/themes
+ * Get all available themes
+ */
+router.get('/themes', asyncHandler(async (req, res) => {
+ const themes = autobiographyService.getThemes();
+ res.json(themes);
+}));
+
+/**
+ * GET /api/digital-twin/autobiography/prompt
+ * Get the next prompt
+ */
+router.get('/prompt', asyncHandler(async (req, res) => {
+ const prompt = await autobiographyService.getNextPrompt();
+ res.json(prompt);
+}));
+
+/**
+ * GET /api/digital-twin/autobiography/prompt/:id
+ * Get a specific prompt by ID
+ */
+router.get('/prompt/:id', asyncHandler(async (req, res) => {
+ const prompt = autobiographyService.getPromptById(req.params.id);
+ if (!prompt) {
+ throw new ServerError('Prompt not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(prompt);
+}));
+
+// =============================================================================
+// STORIES
+// =============================================================================
+
+/**
+ * GET /api/digital-twin/autobiography/stories
+ * Get all stories, optionally filtered by theme
+ */
+router.get('/stories', asyncHandler(async (req, res) => {
+ const stories = await autobiographyService.getStories(req.query.theme || null);
+ res.json(stories);
+}));
+
+/**
+ * POST /api/digital-twin/autobiography/stories
+ * Save a new story
+ */
+router.post('/stories', asyncHandler(async (req, res) => {
+ const validated = validateRequest(saveStorySchema, req.body);
+ const story = await autobiographyService.saveStory(validated);
+ res.json(story);
+}));
+
+/**
+ * PUT /api/digital-twin/autobiography/stories/:id
+ * Update an existing story
+ */
+router.put('/stories/:id', asyncHandler(async (req, res) => {
+ const validated = validateRequest(updateStorySchema, req.body);
+ const story = await autobiographyService.updateStory(req.params.id, validated.content);
+ if (!story) {
+ throw new ServerError('Story not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(story);
+}));
+
+/**
+ * DELETE /api/digital-twin/autobiography/stories/:id
+ * Delete a story
+ */
+router.delete('/stories/:id', asyncHandler(async (req, res) => {
+ const story = await autobiographyService.deleteStory(req.params.id);
+ if (!story) {
+ throw new ServerError('Story not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json({ success: true, story });
+}));
+
+// =============================================================================
+// PROMPT TRIGGER
+// =============================================================================
+
+/**
+ * POST /api/digital-twin/autobiography/trigger
+ * Manually trigger a story prompt notification
+ */
+router.post('/trigger', asyncHandler(async (req, res) => {
+ const result = await autobiographyService.checkAndPrompt();
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
new file mode 100644
index 0000000000..015686b4b5
--- /dev/null
+++ b/server/services/autobiography.js
@@ -0,0 +1,448 @@
+/**
+ * Autobiography Service
+ *
+ * Prompts the user on a regular basis to write 5-minute life stories
+ * based on thematic prompts, building an autobiography over time.
+ *
+ * Stories are stored as part of the digital twin data.
+ */
+
+import { writeFile } from 'fs/promises';
+import { join } from 'path';
+import { v4 as uuidv4 } from 'uuid';
+import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { addNotification, NOTIFICATION_TYPES, exists as notificationExists } from './notifications.js';
+
+const DATA_DIR = join(PATHS.digitalTwin, 'autobiography');
+const STORIES_FILE = join(DATA_DIR, 'stories.json');
+const CONFIG_FILE = join(DATA_DIR, 'config.json');
+
+// Thematic prompt bank organized by life themes
+const PROMPT_THEMES = [
+ {
+ id: 'childhood',
+ label: 'Childhood',
+ prompts: [
+ 'Describe the house or neighborhood you grew up in. What sounds, smells, or textures come back to you?',
+ 'What was your favorite game or activity as a child? Who did you play with?',
+ 'Tell the story of a childhood birthday or holiday that stands out in your memory.',
+ 'What was a rule your parents had that you didn\'t understand until later?',
+ 'Describe a moment when you felt truly free as a kid.'
+ ]
+ },
+ {
+ id: 'family',
+ label: 'Family',
+ prompts: [
+ 'Tell the story of a family tradition that shaped who you are.',
+ 'Describe a conversation with a parent or grandparent that you still think about.',
+ 'What\'s a story your family tells about you that you don\'t remember firsthand?',
+ 'Write about a family meal that represents something larger about your upbringing.',
+ 'Describe a moment of unexpected connection or understanding with a family member.'
+ ]
+ },
+ {
+ id: 'friendship',
+ label: 'Friendship',
+ prompts: [
+ 'Tell the story of how you met your closest friend.',
+ 'Describe a time a friend showed up for you when you really needed it.',
+ 'Write about a friendship that ended and what it taught you.',
+ 'What\'s the funniest thing that ever happened with a friend?',
+ 'Describe a moment when a stranger became a friend.'
+ ]
+ },
+ {
+ id: 'education',
+ label: 'Education & Learning',
+ prompts: [
+ 'Tell the story of a teacher who changed how you think.',
+ 'Describe a moment when you suddenly understood something that had confused you.',
+ 'Write about a time you taught someone else something important.',
+ 'What\'s the hardest thing you ever had to learn? What made it click?',
+ 'Describe a book, lecture, or conversation that opened a new world for you.'
+ ]
+ },
+ {
+ id: 'career',
+ label: 'Career & Work',
+ prompts: [
+ 'Tell the story of your first real job. What surprised you about the working world?',
+ 'Describe a project or accomplishment you\'re proud of. What made it meaningful?',
+ 'Write about a professional failure that redirected your path for the better.',
+ 'Describe the moment you realized what kind of work energizes you.',
+ 'Tell the story of a mentor or colleague who shaped your professional identity.'
+ ]
+ },
+ {
+ id: 'travel',
+ label: 'Travel & Places',
+ prompts: [
+ 'Describe a place you visited that changed your perspective on the world.',
+ 'Tell the story of getting lost somewhere — literally or figuratively.',
+ 'Write about a meal in a foreign place that you still remember vividly.',
+ 'Describe leaving home for the first time. What did you carry with you?',
+ 'Tell the story of a journey where the getting there mattered more than arriving.'
+ ]
+ },
+ {
+ id: 'challenge',
+ label: 'Overcoming Challenges',
+ prompts: [
+ 'Describe the hardest decision you ever had to make. How did you decide?',
+ 'Tell the story of a time you were afraid but did it anyway.',
+ 'Write about a period of your life when everything felt uncertain.',
+ 'Describe a failure that you\'re now grateful for.',
+ 'Tell the story of rebuilding something — a relationship, a career, your confidence.'
+ ]
+ },
+ {
+ id: 'joy',
+ label: 'Moments of Joy',
+ prompts: [
+ 'Describe a moment of pure, uncomplicated happiness.',
+ 'Tell the story of a surprise that delighted you.',
+ 'Write about a time you laughed so hard you couldn\'t breathe.',
+ 'Describe a small, ordinary moment that filled you with gratitude.',
+ 'Tell the story of an achievement that made you feel truly alive.'
+ ]
+ },
+ {
+ id: 'love',
+ label: 'Love & Relationships',
+ prompts: [
+ 'Describe the moment you knew you loved someone.',
+ 'Tell the story of a relationship that taught you what you needed.',
+ 'Write about a gesture of love — given or received — that was understated but powerful.',
+ 'Describe a heartbreak and what it revealed about what you value.',
+ 'Tell the story of an unexpected act of kindness from someone you love.'
+ ]
+ },
+ {
+ id: 'identity',
+ label: 'Identity & Self-Discovery',
+ prompts: [
+ 'Describe a moment when you realized you were different from who you thought you were.',
+ 'Tell the story of a habit or belief you outgrew.',
+ 'Write about a time when you stood up for something that mattered to you, even when it was hard.',
+ 'Describe the person you were five years ago. What would surprise them about you now?',
+ 'Tell the story of finding something you\'re passionate about.'
+ ]
+ },
+ {
+ id: 'creativity',
+ label: 'Creativity & Expression',
+ prompts: [
+ 'Describe the first time you made something you were proud of.',
+ 'Tell the story of a creative project that took on a life of its own.',
+ 'Write about a time when art, music, or writing helped you process something difficult.',
+ 'Describe your creative process — what does it feel like when ideas are flowing?',
+ 'Tell the story of sharing something you created with the world for the first time.'
+ ]
+ },
+ {
+ id: 'turning_point',
+ label: 'Turning Points',
+ prompts: [
+ 'Describe a single day that divided your life into "before" and "after".',
+ 'Tell the story of a choice that seemed small at the time but turned out to be pivotal.',
+ 'Write about a time someone said something that changed the course of your thinking.',
+ 'Describe the moment you committed to a major life change.',
+ 'Tell the story of an ending that was also a beginning.'
+ ]
+ }
+];
+
+const DEFAULT_CONFIG = {
+ intervalHours: 24,
+ enabled: true,
+ lastPromptAt: null,
+ lastPromptId: null
+};
+
+const DEFAULT_DATA = {
+ version: 1,
+ stories: [],
+ usedPrompts: []
+};
+
+async function ensureDataDir() {
+ await ensureDir(DATA_DIR);
+}
+
+async function loadStories() {
+ await ensureDataDir();
+ return readJSONFile(STORIES_FILE, DEFAULT_DATA);
+}
+
+async function saveStories(data) {
+ await ensureDataDir();
+ await writeFile(STORIES_FILE, JSON.stringify(data, null, 2));
+}
+
+async function loadConfig() {
+ await ensureDataDir();
+ return readJSONFile(CONFIG_FILE, DEFAULT_CONFIG);
+}
+
+async function saveConfig(config) {
+ await ensureDataDir();
+ await writeFile(CONFIG_FILE, JSON.stringify(config, null, 2));
+}
+
+/**
+ * Get all available themes with their prompt counts
+ */
+export function getThemes() {
+ return PROMPT_THEMES.map(theme => ({
+ id: theme.id,
+ label: theme.label,
+ promptCount: theme.prompts.length
+ }));
+}
+
+/**
+ * Pick the next prompt, cycling through themes and avoiding repeats
+ */
+export async function getNextPrompt() {
+ const data = await loadStories();
+ const usedPrompts = data.usedPrompts || [];
+
+ // Build flat list of all prompts with IDs
+ const allPrompts = PROMPT_THEMES.flatMap(theme =>
+ theme.prompts.map((text, idx) => ({
+ id: `${theme.id}-${idx}`,
+ themeId: theme.id,
+ themeLabel: theme.label,
+ text
+ }))
+ );
+
+ // Filter out used prompts
+ let available = allPrompts.filter(p => !usedPrompts.includes(p.id));
+
+ // If all prompts used, reset and start over
+ if (available.length === 0) {
+ data.usedPrompts = [];
+ await saveStories(data);
+ available = allPrompts;
+ }
+
+ // Pick from the least-used theme to keep balance
+ const themeCounts = {};
+ for (const story of data.stories) {
+ themeCounts[story.themeId] = (themeCounts[story.themeId] || 0) + 1;
+ }
+
+ // Sort available prompts by theme usage (least written first)
+ available.sort((a, b) => (themeCounts[a.themeId] || 0) - (themeCounts[b.themeId] || 0));
+
+ return available[0];
+}
+
+/**
+ * Get a specific prompt by ID
+ */
+export function getPromptById(promptId) {
+ for (const theme of PROMPT_THEMES) {
+ const idx = theme.prompts.findIndex((_, i) => `${theme.id}-${i}` === promptId);
+ if (idx !== -1) {
+ return {
+ id: promptId,
+ themeId: theme.id,
+ themeLabel: theme.label,
+ text: theme.prompts[idx]
+ };
+ }
+ }
+ return null;
+}
+
+/**
+ * Save a story for a given prompt
+ */
+export async function saveStory({ promptId, content }) {
+ const data = await loadStories();
+ const prompt = getPromptById(promptId);
+
+ const story = {
+ id: uuidv4(),
+ promptId,
+ themeId: prompt?.themeId || 'unknown',
+ themeLabel: prompt?.themeLabel || 'Unknown',
+ promptText: prompt?.text || '',
+ content,
+ wordCount: content.split(/\s+/).filter(Boolean).length,
+ createdAt: new Date().toISOString()
+ };
+
+ data.stories.push(story);
+
+ // Mark prompt as used
+ if (!data.usedPrompts) data.usedPrompts = [];
+ if (!data.usedPrompts.includes(promptId)) {
+ data.usedPrompts.push(promptId);
+ }
+
+ await saveStories(data);
+ console.log(`📖 Autobiography story saved: ${story.themeLabel} (${story.wordCount} words)`);
+
+ return story;
+}
+
+/**
+ * Update an existing story
+ */
+export async function updateStory(storyId, content) {
+ const data = await loadStories();
+ const story = data.stories.find(s => s.id === storyId);
+
+ if (!story) return null;
+
+ story.content = content;
+ story.wordCount = content.split(/\s+/).filter(Boolean).length;
+ story.updatedAt = new Date().toISOString();
+
+ await saveStories(data);
+ console.log(`📖 Autobiography story updated: ${story.themeLabel} (${story.wordCount} words)`);
+
+ return story;
+}
+
+/**
+ * Delete a story
+ */
+export async function deleteStory(storyId) {
+ const data = await loadStories();
+ const idx = data.stories.findIndex(s => s.id === storyId);
+ if (idx === -1) return null;
+
+ const removed = data.stories.splice(idx, 1)[0];
+ await saveStories(data);
+ console.log(`📖 Autobiography story deleted: ${removed.themeLabel}`);
+
+ return removed;
+}
+
+/**
+ * Get all stories, optionally filtered by theme
+ */
+export async function getStories(themeId = null) {
+ const data = await loadStories();
+ let stories = data.stories;
+
+ if (themeId) {
+ stories = stories.filter(s => s.themeId === themeId);
+ }
+
+ // Sort newest first
+ stories.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
+
+ return stories;
+}
+
+/**
+ * Get autobiography stats
+ */
+export async function getStats() {
+ const data = await loadStories();
+ const config = await loadConfig();
+
+ const totalStories = data.stories.length;
+ const totalWords = data.stories.reduce((sum, s) => sum + (s.wordCount || 0), 0);
+
+ // Count stories per theme
+ const byTheme = {};
+ for (const story of data.stories) {
+ byTheme[story.themeId] = (byTheme[story.themeId] || 0) + 1;
+ }
+
+ const totalPrompts = PROMPT_THEMES.reduce((sum, t) => sum + t.prompts.length, 0);
+ const usedPrompts = (data.usedPrompts || []).length;
+
+ return {
+ totalStories,
+ totalWords,
+ byTheme,
+ totalPrompts,
+ usedPrompts,
+ promptsRemaining: totalPrompts - usedPrompts,
+ config: {
+ enabled: config.enabled,
+ intervalHours: config.intervalHours,
+ lastPromptAt: config.lastPromptAt
+ }
+ };
+}
+
+/**
+ * Get configuration
+ */
+export async function getConfig() {
+ return loadConfig();
+}
+
+/**
+ * Update configuration
+ */
+export async function updateConfig(updates) {
+ const config = await loadConfig();
+ const updated = { ...config, ...updates };
+ await saveConfig(updated);
+ console.log(`📖 Autobiography config updated: interval=${updated.intervalHours}h, enabled=${updated.enabled}`);
+ return updated;
+}
+
+/**
+ * Check if a new story prompt is due and create a notification if so.
+ * 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' };
+ }
+
+ const now = Date.now();
+ const intervalMs = (config.intervalHours || 24) * 60 * 60 * 1000;
+ const lastPromptTime = config.lastPromptAt ? new Date(config.lastPromptAt).getTime() : 0;
+
+ if (now - lastPromptTime < intervalMs) {
+ return { prompted: false, reason: 'not_due' };
+ }
+
+ // Check if there's already an unread autobiography notification
+ const alreadyNotified = await notificationExists(
+ NOTIFICATION_TYPES.AUTOBIOGRAPHY_PROMPT,
+ 'type',
+ 'autobiography_prompt'
+ );
+
+ if (alreadyNotified) {
+ return { prompted: false, reason: 'pending_notification' };
+ }
+
+ 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: {
+ type: 'autobiography_prompt',
+ 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)}...`);
+
+ return { prompted: true, prompt };
+}
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index 341eae0d0d..36850d0a50 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -36,7 +36,8 @@ const JOB_SKILL_MAP = {
'job-brain-processing': 'brain-processing',
'job-project-review': 'project-review',
'job-moltworld-exploration': 'moltworld-exploration',
- 'job-jira-app-maintenance': 'jira-app-maintenance'
+ 'job-jira-app-maintenance': 'jira-app-maintenance',
+ 'job-autobiography-prompt': 'autobiography-prompt'
}
// Time constants
@@ -231,6 +232,28 @@ Focus on moving tickets forward. Don't just report - take action by improving ti
runCount: 0,
createdAt: null,
updatedAt: null
+ },
+ {
+ id: 'job-autobiography-prompt',
+ name: 'Autobiography Story Prompt',
+ description: 'Send a notification prompting the user to write a 5-minute autobiographical story based on a thematic prompt.',
+ category: 'autobiography-prompt',
+ interval: 'daily',
+ intervalMs: DAY,
+ enabled: true,
+ priority: 'LOW',
+ autonomyLevel: 'assistant',
+ promptTemplate: `[Autonomous Job] Autobiography Story Prompt
+
+This job triggers a notification asking the user to write a short autobiographical story.
+
+Call POST /api/digital-twin/autobiography/trigger to check if a prompt is due and send a notification.
+
+This is a lightweight job — it simply checks timing and sends a notification if due. No AI processing needed.`,
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
}
]
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index ea5a864628..63030df9f2 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -125,7 +125,8 @@ describe('autonomousJobs', () => {
// Verify only expected test jobs plus any default jobs are present
const testJobIds = new Set(['job-test-1', 'job-1', 'job-2'])
- const unexpectedJobs = due.filter(j => !testJobIds.has(j.id) && !j.id.startsWith('job-github-'))
+ const defaultJobPrefixes = ['job-github-', 'job-brain-', 'job-daily-', 'job-project-', 'job-moltworld-', 'job-jira-', 'job-autobiography-']
+ const unexpectedJobs = due.filter(j => !testJobIds.has(j.id) && !defaultJobPrefixes.some(p => j.id.startsWith(p)))
expect(unexpectedJobs).toHaveLength(0)
})
})
diff --git a/server/services/notifications.js b/server/services/notifications.js
index 6f14cabbb5..9faad329c9 100644
--- a/server/services/notifications.js
+++ b/server/services/notifications.js
@@ -29,7 +29,8 @@ export const NOTIFICATION_TYPES = {
TASK_APPROVAL: 'task_approval',
CODE_REVIEW: 'code_review',
HEALTH_ISSUE: 'health_issue',
- BRIEFING_READY: 'briefing_ready'
+ BRIEFING_READY: 'briefing_ready',
+ AUTOBIOGRAPHY_PROMPT: 'autobiography_prompt'
};
// Priority levels