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(autobiography): add LLM-powered prompt chains for deeper story exploration

Adam Eivy7dcb254579c4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d5909b7196..3a34c25190 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,6 +24,7 @@
- Genome markers: friendlier card UX with "What this means for you" framing, status-colored backgrounds, and renamed labels (Details, Your Notes, Learn More)
- Voice capture for Brain — microphone button on inbox uses Web Speech API to transcribe speech into thoughts
- Legacy Portrait export format — comprehensive human-readable Markdown document consolidating identity docs, traits, chronotype, taste profile, genome, longevity, goals, autobiography, and social presence
+- Autobiography prompt chains — LLM-generated follow-up questions after saving a story, enabling deeper exploration of life themes with linked story chains
## Changed
diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
index a76dedec70..eebcbfe899 100644
--- a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
@@ -12,7 +12,10 @@ import {
Send,
Settings,
SkipForward,
- X
+ X,
+ Sparkles,
+ Link2,
+ MessageCircle
} from 'lucide-react';
import * as api from '../../../services/api';
import toast from 'react-hot-toast';
@@ -42,6 +45,11 @@ export default function AutobiographyTab({ onRefresh }) {
// Expanded story
const [expandedStory, setExpandedStory] = useState(null);
+ // Follow-up state
+ const [followUps, setFollowUps] = useState(null); // { storyId, prompts[] }
+ const [generatingFollowUps, setGeneratingFollowUps] = useState(false);
+ const [parentStoryId, setParentStoryId] = useState(null); // when writing a follow-up
+
const loadData = useCallback(async () => {
const [statsData, storiesData, themesData, configData] = await Promise.all([
api.getAutobiographyStats().catch(() => null),
@@ -106,7 +114,10 @@ export default function AutobiographyTab({ onRefresh }) {
return;
}
setSaving(true);
- const result = await api.saveAutobiographyStory(currentPrompt.id, storyContent.trim())
+ const opts = parentStoryId
+ ? { parentStoryId, customPromptText: currentPrompt.text }
+ : {};
+ const result = await api.saveAutobiographyStory(currentPrompt.id, storyContent.trim(), opts)
.catch((err) => { toast.error(err.message); return null; });
if (result) {
@@ -114,12 +125,45 @@ export default function AutobiographyTab({ onRefresh }) {
setWriting(false);
setCurrentPrompt(null);
setStoryContent('');
+ setParentStoryId(null);
+ // Show follow-ups from the saved story if it already has them, otherwise offer to generate
+ setFollowUps({ storyId: result.id, prompts: result.followUpPrompts || null });
+ setExpandedStory(result.id);
loadData();
onRefresh?.();
}
setSaving(false);
};
+ const handleGenerateFollowUps = async (storyId) => {
+ setGeneratingFollowUps(true);
+ const result = await api.generateAutobiographyFollowUps(storyId)
+ .catch((err) => { toast.error(err.message); return null; });
+
+ if (result?.followUps) {
+ setFollowUps({ storyId, prompts: result.followUps });
+ // Update the story in local state
+ setStories(prev => prev.map(s =>
+ s.id === storyId ? { ...s, followUpPrompts: result.followUps } : s
+ ));
+ toast.success('Follow-up questions generated');
+ }
+ setGeneratingFollowUps(false);
+ };
+
+ const startFollowUp = (parentId, questionText, themeId, themeLabel) => {
+ setParentStoryId(parentId);
+ setCurrentPrompt({
+ id: `followup-${parentId}`,
+ themeId,
+ themeLabel,
+ text: questionText
+ });
+ setWriting(true);
+ setStoryContent('');
+ setFollowUps(null);
+ };
+
const handleUpdateStory = async (storyId) => {
if (!editContent.trim()) return;
const result = await api.updateAutobiographyStory(storyId, editContent.trim())
@@ -230,18 +274,78 @@ export default function AutobiographyTab({ onRefresh }) {
</div>
)}
+ {/* Follow-up Suggestions (shown after saving a story) */}
+ {followUps && !writing && (
+ <div className="bg-port-card border border-amber-500/30 rounded-lg p-5 space-y-3">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Sparkles className="w-4 h-4 text-amber-400" />
+ <span className="text-sm font-medium text-amber-300">Go Deeper</span>
+ </div>
+ <button
+ onClick={() => setFollowUps(null)}
+ className="p-1 text-gray-500 hover:text-white"
+ >
+ <X size={14} />
+ </button>
+ </div>
+ {followUps.prompts ? (
+ <div className="space-y-2">
+ <p className="text-xs text-gray-400">Click a question to continue writing about this story:</p>
+ {followUps.prompts.map((question, i) => {
+ const story = stories.find(s => s.id === followUps.storyId);
+ return (
+ <button
+ key={i}
+ onClick={() => startFollowUp(
+ followUps.storyId,
+ question,
+ story?.themeId || 'unknown',
+ story?.themeLabel || 'Unknown'
+ )}
+ className="w-full text-left p-3 rounded-lg bg-port-bg border border-port-border hover:border-amber-500/50 transition-colors group"
+ >
+ <div className="flex items-start gap-2">
+ <MessageCircle size={14} className="mt-0.5 text-amber-400/60 group-hover:text-amber-400 shrink-0" />
+ <span className="text-sm text-gray-300 group-hover:text-white">{question}</span>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <button
+ onClick={() => handleGenerateFollowUps(followUps.storyId)}
+ disabled={generatingFollowUps}
+ className="flex items-center gap-2 px-3 py-2 bg-amber-500/10 text-amber-300 rounded text-sm hover:bg-amber-500/20 transition-colors disabled:opacity-50"
+ >
+ {generatingFollowUps
+ ? <RefreshCw size={14} className="animate-spin" />
+ : <Sparkles size={14} />}
+ {generatingFollowUps ? 'Generating...' : 'Generate follow-up questions'}
+ </button>
+ )}
+ </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>
+ {parentStoryId && (
+ <div className="flex items-center gap-1 mb-1">
+ <Link2 size={12} className="text-amber-400" />
+ <span className="text-xs text-amber-400">Follow-up</span>
+ </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(''); }}
+ onClick={() => { setWriting(false); setCurrentPrompt(null); setStoryContent(''); setParentStoryId(null); }}
className="p-1 text-gray-500 hover:text-white"
>
<X size={16} />
@@ -339,6 +443,12 @@ export default function AutobiographyTab({ onRefresh }) {
<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>
+ {story.parentStoryId && (
+ <span className="flex items-center gap-0.5 text-xs text-amber-400">
+ <Link2 size={10} />
+ follow-up
+ </span>
+ )}
<span className="text-xs text-gray-500">{story.wordCount} words</span>
<span className="text-xs text-gray-600">
{new Date(story.createdAt).toLocaleDateString()}
@@ -379,7 +489,40 @@ export default function AutobiographyTab({ onRefresh }) {
<p className="text-sm text-white whitespace-pre-wrap leading-relaxed">
{story.content}
</p>
+
+ {/* Follow-up prompts inline */}
+ {story.followUpPrompts?.length > 0 && (
+ <div className="mt-3 space-y-1.5">
+ <p className="text-xs text-amber-400 flex items-center gap-1">
+ <Sparkles size={12} />
+ Follow-up questions
+ </p>
+ {story.followUpPrompts.map((q, i) => (
+ <button
+ key={i}
+ onClick={() => startFollowUp(story.id, q, story.themeId, story.themeLabel)}
+ className="w-full text-left p-2 rounded bg-port-bg/50 border border-port-border/50 hover:border-amber-500/40 transition-colors group"
+ >
+ <div className="flex items-start gap-2">
+ <MessageCircle size={12} className="mt-0.5 text-amber-400/50 group-hover:text-amber-400 shrink-0" />
+ <span className="text-xs text-gray-400 group-hover:text-gray-200">{q}</span>
+ </div>
+ </button>
+ ))}
+ </div>
+ )}
+
<div className="flex items-center gap-2 justify-end pt-2 border-t border-port-border/50">
+ {!story.followUpPrompts && (
+ <button
+ onClick={() => handleGenerateFollowUps(story.id)}
+ disabled={generatingFollowUps}
+ className="flex items-center gap-1 px-2 py-1 text-xs text-amber-400/70 hover:text-amber-400 transition-colors disabled:opacity-50"
+ >
+ {generatingFollowUps ? <RefreshCw size={12} className="animate-spin" /> : <Sparkles size={12} />}
+ Follow-ups
+ </button>
+ )}
<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"
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 9036e67930..fd738efcef 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1266,10 +1266,11 @@ export const getAutobiographyPrompt = (exclude) =>
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 saveAutobiographyStory = (promptId, content, { parentStoryId, customPromptText } = {}) =>
+ request('/digital-twin/autobiography/stories', {
+ method: 'POST',
+ body: JSON.stringify({ promptId, content, parentStoryId, customPromptText })
+ });
export const updateAutobiographyStory = (id, content) => request(`/digital-twin/autobiography/stories/${id}`, {
method: 'PUT',
body: JSON.stringify({ content })
@@ -1280,6 +1281,13 @@ export const deleteAutobiographyStory = (id) => request(`/digital-twin/autobiogr
export const triggerAutobiographyPrompt = () => request('/digital-twin/autobiography/trigger', {
method: 'POST'
});
+export const generateAutobiographyFollowUps = (storyId, providerId) =>
+ request(`/digital-twin/autobiography/stories/${storyId}/follow-ups`, {
+ method: 'POST',
+ body: JSON.stringify({ providerId })
+ });
+export const getAutobiographyStoryChain = (storyId) =>
+ request(`/digital-twin/autobiography/stories/${storyId}/chain`);
// Digital Twin - Assessment Analyzer
export const analyzeAssessment = (content, providerId, model) =>
diff --git a/server/routes/autobiography.js b/server/routes/autobiography.js
index b1d7c4ed10..2b5b703fd2 100644
--- a/server/routes/autobiography.js
+++ b/server/routes/autobiography.js
@@ -19,7 +19,13 @@ const router = Router();
// Validation schemas
const saveStorySchema = z.object({
promptId: z.string().min(1),
- content: z.string().min(1).max(50000)
+ content: z.string().min(1).max(50000),
+ parentStoryId: z.string().optional(),
+ customPromptText: z.string().optional()
+});
+
+const generateFollowUpsSchema = z.object({
+ providerId: z.string().optional()
});
const updateStorySchema = z.object({
@@ -116,7 +122,12 @@ router.get('/stories', asyncHandler(async (req, res) => {
*/
router.post('/stories', asyncHandler(async (req, res) => {
const validated = validateRequest(saveStorySchema, req.body);
- const story = await autobiographyService.saveStory(validated);
+ const story = await autobiographyService.saveStory({
+ promptId: validated.promptId,
+ content: validated.content,
+ parentStoryId: validated.parentStoryId,
+ customPromptText: validated.customPromptText
+ });
res.json(story);
}));
@@ -145,6 +156,32 @@ router.delete('/stories/:id', asyncHandler(async (req, res) => {
res.json({ success: true, story });
}));
+// =============================================================================
+// FOLLOW-UP CHAINS
+// =============================================================================
+
+/**
+ * POST /api/digital-twin/autobiography/stories/:id/follow-ups
+ * Generate LLM-powered follow-up questions for a story
+ */
+router.post('/stories/:id/follow-ups', asyncHandler(async (req, res) => {
+ const validated = validateRequest(generateFollowUpsSchema, req.body);
+ const result = await autobiographyService.generateFollowUps(req.params.id, validated.providerId);
+ if (result.error) {
+ throw new ServerError(result.error, { status: 400, code: 'FOLLOW_UP_ERROR' });
+ }
+ res.json(result);
+}));
+
+/**
+ * GET /api/digital-twin/autobiography/stories/:id/chain
+ * Get the full chain of stories linked to a story (ancestors + descendants)
+ */
+router.get('/stories/:id/chain', asyncHandler(async (req, res) => {
+ const chain = await autobiographyService.getStoryChain(req.params.id);
+ res.json(chain);
+}));
+
// =============================================================================
// PROMPT TRIGGER
// =============================================================================
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index 5c984a4493..265c15c221 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -12,6 +12,8 @@ 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';
+import { getActiveProvider, getProviderById } from './providers.js';
+import { callProviderAISimple, parseLLMJSON } from '../lib/aiProvider.js';
const DATA_DIR = join(PATHS.digitalTwin, 'autobiography');
const STORIES_FILE = join(DATA_DIR, 'stories.json');
@@ -266,19 +268,24 @@ export function getPromptById(promptId) {
/**
* Save a story for a given prompt
*/
-export async function saveStory({ promptId, content }) {
+export async function saveStory({ promptId, content, parentStoryId, customPromptText }) {
const data = await loadStories();
const prompt = getPromptById(promptId);
+ // For follow-up stories, use custom prompt text from the follow-up question
+ const isFollowUp = !!parentStoryId;
+ const parentStory = isFollowUp ? data.stories.find(s => s.id === parentStoryId) : null;
+
const story = {
id: uuidv4(),
- promptId,
- themeId: prompt?.themeId || 'unknown',
- themeLabel: prompt?.themeLabel || 'Unknown',
- promptText: prompt?.text || '',
+ promptId: isFollowUp ? `followup-${parentStoryId}` : promptId,
+ themeId: isFollowUp ? (parentStory?.themeId || 'unknown') : (prompt?.themeId || 'unknown'),
+ themeLabel: isFollowUp ? (parentStory?.themeLabel || 'Unknown') : (prompt?.themeLabel || 'Unknown'),
+ promptText: customPromptText || prompt?.text || '',
content,
wordCount: content.split(/\s+/).filter(Boolean).length,
- createdAt: new Date().toISOString()
+ createdAt: new Date().toISOString(),
+ ...(parentStoryId && { parentStoryId })
};
data.stories.push(story);
@@ -398,6 +405,109 @@ export async function updateConfig(updates) {
return updated;
}
+/**
+ * Generate LLM-powered follow-up questions for a story.
+ * Returns 2-3 deeper questions based on the story content.
+ */
+export async function generateFollowUps(storyId, providerId) {
+ const data = await loadStories();
+ const story = data.stories.find(s => s.id === storyId);
+ if (!story) return { error: 'Story not found' };
+
+ const provider = providerId
+ ? await getProviderById(providerId)
+ : await getActiveProvider();
+ if (!provider) return { error: 'No AI provider available' };
+
+ const model = provider.defaultModel;
+
+ // Build chain context — include parent stories for deeper follow-ups
+ const chainStories = [];
+ let current = story;
+ while (current) {
+ chainStories.unshift(current);
+ current = current.parentStoryId
+ ? data.stories.find(s => s.id === current.parentStoryId)
+ : null;
+ }
+
+ const chainContext = chainStories.map((s, i) =>
+ `${i === 0 ? 'Original prompt' : `Follow-up #${i}`}: ${s.promptText}\nResponse: ${s.content}`
+ ).join('\n\n');
+
+ const prompt = `You are helping someone write their autobiography by asking thoughtful follow-up questions. Based on the story they just wrote, generate exactly 3 follow-up questions that dig deeper into specific details, emotions, or connections they mentioned.
+
+Theme: ${story.themeLabel}
+
+${chainContext}
+
+Rules:
+- Each question should reference a specific detail from their most recent response
+- Questions should invite rich storytelling, not yes/no answers
+- Go deeper into emotions, sensory details, or cause-and-effect
+- Keep questions under 30 words each
+- If this is a follow-up chain, avoid repeating ground already covered
+
+Return a JSON array of exactly 3 strings, nothing else. Example:
+["Question 1?", "Question 2?", "Question 3?"]`;
+
+ const result = await callProviderAISimple(provider, model, prompt, {
+ temperature: 0.7,
+ max_tokens: 500
+ });
+
+ if (result.error) return { error: result.error };
+
+ const followUps = parseLLMJSON(result.text);
+ if (!Array.isArray(followUps) || followUps.length === 0) {
+ return { error: 'Failed to parse follow-up questions from AI response' };
+ }
+
+ // Store follow-ups on the story
+ story.followUpPrompts = followUps.slice(0, 3);
+ story.followUpsGeneratedAt = new Date().toISOString();
+ await saveStories(data);
+
+ console.log(`📖 Autobiography follow-ups generated for story ${storyId}: ${followUps.length} questions`);
+
+ return { followUps: story.followUpPrompts };
+}
+
+/**
+ * Get the chain of stories linked to a given story (parent + children)
+ */
+export async function getStoryChain(storyId) {
+ const data = await loadStories();
+
+ // Find all ancestors
+ const ancestors = [];
+ let current = data.stories.find(s => s.id === storyId);
+ while (current?.parentStoryId) {
+ const parent = data.stories.find(s => s.id === current.parentStoryId);
+ if (parent) ancestors.unshift(parent);
+ current = parent;
+ }
+
+ // Find the story itself
+ const story = data.stories.find(s => s.id === storyId);
+ if (!story) return [];
+
+ // Find all descendants recursively
+ const descendants = [];
+ const findChildren = (parentId) => {
+ const children = data.stories
+ .filter(s => s.parentStoryId === parentId)
+ .sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
+ for (const child of children) {
+ descendants.push(child);
+ findChildren(child.id);
+ }
+ };
+ findChildren(storyId);
+
+ return [...ancestors, story, ...descendants];
+}
+
/**
* 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.