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([issue-900]): depth-aware autobiography follow-ups + narrative weaving

Adam Eivy71657565c5b7
diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
index 9c323451b8..89d1c8b001 100644
--- a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx
@@ -13,9 +13,11 @@ import {BookOpen,
X,
Sparkles,
Link2,
- MessageCircle} from 'lucide-react';
+ MessageCircle,
+ ScrollText} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import * as api from '../../../services/api';
+import { copyToClipboard } from '../../../lib/clipboard';
import toast from '../../ui/Toast';
export default function AutobiographyTab({ onRefresh }) {
@@ -48,6 +50,10 @@ export default function AutobiographyTab({ onRefresh }) {
const [generatingFollowUps, setGeneratingFollowUps] = useState(false);
const [parentStoryId, setParentStoryId] = useState(null); // when writing a follow-up
+ // Woven-narrative state
+ const [narrative, setNarrative] = useState(null); // { storyId, text, storyCount }
+ const [weavingStoryId, setWeavingStoryId] = useState(null);
+
const loadData = useCallback(async () => {
const [statsData, storiesData, themesData, configData] = await Promise.all([
api.getAutobiographyStats().catch(() => null),
@@ -149,6 +155,23 @@ export default function AutobiographyTab({ onRefresh }) {
setGeneratingFollowUps(false);
};
+ const handleWeaveNarrative = async (storyId) => {
+ setWeavingStoryId(storyId);
+ // request() already toasts on failure; the catch only swallows so the
+ // loading state still resets (avoids the double-toast in CLAUDE.md).
+ const result = await api.weaveAutobiographyNarrative(storyId).catch(() => null);
+ if (result?.narrative) {
+ setNarrative({ storyId, text: result.narrative, storyCount: result.storyCount });
+ }
+ setWeavingStoryId(null);
+ };
+
+ // A story's chain is "weavable" once it links to at least one other story
+ // (it's part of a follow-up chain as either parent or child).
+ const isChainable = useCallback((story) => (
+ !!story.parentStoryId || stories.some(s => s.parentStoryId === story.id)
+ ), [stories]);
+
const startFollowUp = (parentId, questionText, themeId, themeLabel) => {
setParentStoryId(parentId);
setCurrentPrompt({
@@ -510,7 +533,47 @@ export default function AutobiographyTab({ onRefresh }) {
</div>
)}
+ {/* Woven narrative for this chain */}
+ {narrative?.storyId === story.id && (
+ <div className="mt-3 bg-port-bg border border-amber-500/30 rounded-lg p-4 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-amber-300 flex items-center gap-1">
+ <ScrollText size={12} />
+ Woven narrative ({narrative.storyCount} stories)
+ </span>
+ <div className="flex items-center gap-2">
+ <button
+ onClick={() => copyToClipboard(narrative.text, 'Narrative copied')}
+ className="text-xs text-gray-400 hover:text-white transition-colors"
+ >
+ Copy
+ </button>
+ <button
+ onClick={() => setNarrative(null)}
+ className="p-0.5 text-gray-500 hover:text-white"
+ >
+ <X size={12} />
+ </button>
+ </div>
+ </div>
+ <p className="text-sm text-white whitespace-pre-wrap leading-relaxed">
+ {narrative.text}
+ </p>
+ </div>
+ )}
+
<div className="flex items-center gap-2 justify-end pt-2 border-t border-port-border/50">
+ {isChainable(story) && (
+ <button
+ onClick={() => handleWeaveNarrative(story.id)}
+ disabled={weavingStoryId === story.id}
+ 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"
+ title="Weave this chain of stories into one cohesive narrative"
+ >
+ {weavingStoryId === story.id ? <BrailleSpinner /> : <ScrollText size={12} />}
+ Weave
+ </button>
+ )}
{!story.followUpPrompts && (
<button
onClick={() => handleGenerateFollowUps(story.id)}
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index a01fc7cb5b..4256c4c5d4 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -246,6 +246,11 @@ export const generateAutobiographyFollowUps = (storyId, providerId) =>
});
export const getAutobiographyStoryChain = (storyId) =>
request(`/digital-twin/autobiography/stories/${storyId}/chain`);
+export const weaveAutobiographyNarrative = (storyId, providerId) =>
+ request(`/digital-twin/autobiography/stories/${storyId}/weave`, {
+ method: 'POST',
+ body: JSON.stringify({ providerId })
+ });
// Digital Twin - Assessment Analyzer
export const analyzeAssessment = (content, providerId, model) =>
diff --git a/server/routes/autobiography.js b/server/routes/autobiography.js
index 2b5b703fd2..9036df0d7a 100644
--- a/server/routes/autobiography.js
+++ b/server/routes/autobiography.js
@@ -28,6 +28,10 @@ const generateFollowUpsSchema = z.object({
providerId: z.string().optional()
});
+const weaveNarrativeSchema = z.object({
+ providerId: z.string().optional()
+});
+
const updateStorySchema = z.object({
content: z.string().min(1).max(50000)
});
@@ -182,6 +186,19 @@ router.get('/stories/:id/chain', asyncHandler(async (req, res) => {
res.json(chain);
}));
+/**
+ * POST /api/digital-twin/autobiography/stories/:id/weave
+ * Weave the story's full chain into a single cohesive first-person narrative
+ */
+router.post('/stories/:id/weave', asyncHandler(async (req, res) => {
+ const validated = validateRequest(weaveNarrativeSchema, req.body);
+ const result = await autobiographyService.weaveChainNarrative(req.params.id, validated.providerId);
+ if (result.error) {
+ throw new ServerError(result.error, { status: 400, code: 'WEAVE_ERROR' });
+ }
+ res.json(result);
+}));
+
// =============================================================================
// PROMPT TRIGGER
// =============================================================================
diff --git a/server/services/autobiography.js b/server/services/autobiography.js
index 92aedcfb5b..19510acbd5 100644
--- a/server/services/autobiography.js
+++ b/server/services/autobiography.js
@@ -405,9 +405,29 @@ export async function updateConfig(updates) {
return updated;
}
+/**
+ * Map a chain depth to follow-up question guidance. Early in a chain the
+ * questions broaden the scene (who/what/where/sensory); as the chain deepens
+ * they pivot toward emotion, cause-and-effect, and finally reflection and
+ * meaning — so each round builds a progressively richer narrative.
+ */
+export function depthGuidanceForChain(depth) {
+ if (depth <= 1) {
+ return 'Stay close to the scene: draw out concrete people, places, and sensory details they only touched on.';
+ }
+ if (depth === 2) {
+ return 'Go beneath the surface: ask about the emotions, motivations, and relationships behind what they described.';
+ }
+ if (depth === 3) {
+ return 'Probe cause and effect: ask how this moment shaped later choices, beliefs, or who they became.';
+ }
+ return 'Invite reflection and meaning: ask what this thread reveals about them now, looking back, and how it connects to the larger arc of their life.';
+}
+
/**
* Generate LLM-powered follow-up questions for a story.
- * Returns 2-3 deeper questions based on the story content.
+ * Returns 2-3 deeper questions based on the story content. Questions become
+ * progressively more reflective as the chain deepens (see depthGuidanceForChain).
*/
export async function generateFollowUps(storyId, providerId) {
const data = await loadStories();
@@ -435,18 +455,26 @@ export async function generateFollowUps(storyId, providerId) {
`${i === 0 ? 'Original prompt' : `Follow-up #${i}`}: ${s.promptText}\nResponse: ${s.content}`
).join('\n\n');
+ // Depth-aware guidance: the deeper into a chain we are, the more the
+ // questions should shift from gathering new details toward reflection,
+ // meaning, and synthesis — so the narrative grows progressively richer
+ // rather than circling the same surface details.
+ const depth = chainStories.length; // 1 = original story, 2+ = nth follow-up
+ const depthGuidance = depthGuidanceForChain(depth);
+
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}
+This is depth ${depth} in the story chain.
${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
+- Avoid repeating ground already covered earlier in the chain
+- ${depthGuidance}
Return a JSON array of exactly 3 strings, nothing else. Example:
["Question 1?", "Question 2?", "Question 3?"]`;
@@ -509,6 +537,60 @@ export async function getStoryChain(storyId) {
return [...ancestors, story, ...descendants];
}
+/**
+ * Weave a story chain into a single cohesive first-person narrative.
+ *
+ * Takes the full chain for a story (ancestors → story → descendants, the same
+ * ordering as getStoryChain) and asks the LLM to synthesize every prompt/answer
+ * turn into one flowing memoir passage — the "progressively richer narrative"
+ * the chained follow-ups were building toward. The result is returned to the
+ * caller (not persisted as a story) so the user can review or copy it.
+ */
+export async function weaveChainNarrative(storyId, providerId) {
+ const chain = await getStoryChain(storyId);
+ if (chain.length === 0) 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;
+
+ const chainContext = chain.map((s, i) =>
+ `${i === 0 ? 'Opening prompt' : `Follow-up #${i}`}: ${s.promptText}\nResponse: ${s.content}`
+ ).join('\n\n');
+
+ const themeLabel = chain[0]?.themeLabel || 'this period';
+
+ const prompt = `You are a memoir editor. Below is a chain of autobiography prompts and the person's own responses, written over several sittings about ${themeLabel}. Weave them into a single cohesive first-person narrative passage.
+
+${chainContext}
+
+Rules:
+- Write in the first person, in the person's own voice — preserve their phrasing, details, and tone
+- Merge the separate responses into one flowing passage; do not list them as Q&A
+- Keep every concrete detail they shared; do not invent facts, names, or events they did not mention
+- Smooth transitions so the deeper follow-up reflections feel like a natural progression
+- Return only the narrative prose, no preamble, headings, or commentary`;
+
+ const result = await callProviderAISimple(provider, model, prompt, {
+ temperature: 0.6,
+ max_tokens: 2000,
+ op: 'autobiography-weave',
+ opLabel: 'Weaving your story…'
+ });
+
+ if (result.error) return { error: result.error };
+
+ const narrative = (result.text || '').trim();
+ if (!narrative) return { error: 'AI returned an empty narrative' };
+
+ console.log(`📖 Autobiography narrative woven for chain of ${chain.length} stories (root ${chain[0]?.id})`);
+
+ return { narrative, storyCount: chain.length };
+}
+
/**
* 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.
diff --git a/server/services/autobiography.test.js b/server/services/autobiography.test.js
index 7cff7f8ad0..f79be2c39c 100644
--- a/server/services/autobiography.test.js
+++ b/server/services/autobiography.test.js
@@ -27,6 +27,21 @@ vi.mock('../lib/uuid.js', () => ({
v4: () => `test-uuid-${++uuidCounter}`
}));
+// Mock providers + AI provider (LLM calls in generateFollowUps / weaveChainNarrative)
+const mockGetActiveProvider = vi.fn();
+const mockGetProviderById = vi.fn();
+vi.mock('./providers.js', () => ({
+ getActiveProvider: (...args) => mockGetActiveProvider(...args),
+ getProviderById: (...args) => mockGetProviderById(...args)
+}));
+
+const mockCallProviderAISimple = vi.fn();
+vi.mock('../lib/aiProvider.js', () => ({
+ callProviderAISimple: (...args) => mockCallProviderAISimple(...args),
+ // Real-ish JSON extractor good enough for tests
+ parseLLMJSON: (raw) => JSON.parse(raw)
+}));
+
// Mock fileUtils.js
vi.mock('../lib/fileUtils.js', async (importOriginal) => {
const fsPromises = await import('fs/promises');
@@ -55,7 +70,11 @@ import {
getStats,
getConfig,
updateConfig,
- checkAndPrompt
+ checkAndPrompt,
+ depthGuidanceForChain,
+ generateFollowUps,
+ getStoryChain,
+ weaveChainNarrative
} from './autobiography.js';
// Helper: build stories data
@@ -607,3 +626,172 @@ describe('Autobiography - checkAndPrompt', () => {
expect(result.reason).toBe('not_due');
});
});
+
+// =============================================================================
+// FOLLOW-UP CHAINS — depth-aware questions, chain walking, narrative weaving
+// =============================================================================
+
+describe('Autobiography - depthGuidanceForChain', () => {
+ it('keeps shallow chains close to the scene', () => {
+ expect(depthGuidanceForChain(1)).toMatch(/concrete|sensory|scene/i);
+ });
+
+ it('shifts to emotion at depth 2', () => {
+ expect(depthGuidanceForChain(2)).toMatch(/emotion|motivation|relationship/i);
+ });
+
+ it('shifts to cause-and-effect at depth 3', () => {
+ expect(depthGuidanceForChain(3)).toMatch(/shaped|choices|became/i);
+ });
+
+ it('invites reflection and meaning at deep chains', () => {
+ const deep = depthGuidanceForChain(5);
+ expect(deep).toMatch(/reflection|meaning|larger arc|looking back/i);
+ // Progression must differ from the shallow guidance
+ expect(deep).not.toBe(depthGuidanceForChain(1));
+ });
+});
+
+describe('Autobiography - generateFollowUps (depth-aware)', () => {
+ const provider = { id: 'p1', name: 'Test', type: 'api', defaultModel: 'm1' };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetActiveProvider.mockResolvedValue(provider);
+ mockCallProviderAISimple.mockResolvedValue({ text: '["Q1?","Q2?","Q3?"]' });
+ writeFile.mockImplementation(async () => {});
+ });
+
+ it('returns an error when the story is missing', async () => {
+ setupMocks(makeStoriesData(), makeConfigData());
+ const result = await generateFollowUps('nope');
+ expect(result.error).toBe('Story not found');
+ });
+
+ it('returns an error when no provider is available', async () => {
+ mockGetActiveProvider.mockResolvedValue(null);
+ setupMocks(makeStoriesData({ stories: [{ id: 's1', content: 'x', promptText: 'p', themeLabel: 'Childhood' }] }), makeConfigData());
+ const result = await generateFollowUps('s1');
+ expect(result.error).toBe('No AI provider available');
+ });
+
+ it('generates and stores exactly 3 follow-ups for a root story', async () => {
+ let saved = null;
+ writeFile.mockImplementation(async (_p, content) => { saved = JSON.parse(content); });
+ setupMocks(makeStoriesData({ stories: [{ id: 's1', content: 'A vivid childhood memory.', promptText: 'Describe it', themeLabel: 'Childhood' }] }), makeConfigData());
+
+ const result = await generateFollowUps('s1');
+
+ expect(result.followUps).toHaveLength(3);
+ expect(saved.stories[0].followUpPrompts).toEqual(['Q1?', 'Q2?', 'Q3?']);
+ expect(saved.stories[0].followUpsGeneratedAt).toBeTruthy();
+ });
+
+ it('passes shallow (depth-1) guidance for a root story', async () => {
+ setupMocks(makeStoriesData({ stories: [{ id: 's1', content: 'x', promptText: 'p', themeLabel: 'Childhood' }] }), makeConfigData());
+
+ await generateFollowUps('s1');
+
+ const promptArg = mockCallProviderAISimple.mock.calls[0][2];
+ expect(promptArg).toContain('This is depth 1 in the story chain.');
+ expect(promptArg).toContain(depthGuidanceForChain(1));
+ });
+
+ it('passes deeper guidance as the chain grows', async () => {
+ // s1 (root) -> s2 -> s3 ; generating for s3 is depth 3
+ const stories = [
+ { id: 's1', content: 'root', promptText: 'p1', themeLabel: 'Childhood' },
+ { id: 's2', content: 'mid', promptText: 'p2', themeLabel: 'Childhood', parentStoryId: 's1' },
+ { id: 's3', content: 'leaf', promptText: 'p3', themeLabel: 'Childhood', parentStoryId: 's2' }
+ ];
+ setupMocks(makeStoriesData({ stories }), makeConfigData());
+
+ await generateFollowUps('s3');
+
+ const promptArg = mockCallProviderAISimple.mock.calls[0][2];
+ expect(promptArg).toContain('This is depth 3 in the story chain.');
+ expect(promptArg).toContain(depthGuidanceForChain(3));
+ // Earlier responses must be present so questions can build on prior answers
+ expect(promptArg).toContain('root');
+ expect(promptArg).toContain('mid');
+ });
+
+ it('returns an error when the AI response is unparseable', async () => {
+ mockCallProviderAISimple.mockResolvedValue({ text: 'not json' });
+ setupMocks(makeStoriesData({ stories: [{ id: 's1', content: 'x', promptText: 'p', themeLabel: 'Childhood' }] }), makeConfigData());
+
+ const result = await generateFollowUps('s1');
+ expect(result.error).toMatch(/Failed to parse/);
+ });
+});
+
+describe('Autobiography - getStoryChain', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns empty array when story is missing', async () => {
+ setupMocks(makeStoriesData(), makeConfigData());
+ expect(await getStoryChain('nope')).toEqual([]);
+ });
+
+ it('returns ancestors, the story, and descendants in order', async () => {
+ const stories = [
+ { id: 's1', content: 'root', promptText: 'p1', themeLabel: 'Childhood', createdAt: '2026-01-01' },
+ { id: 's2', content: 'mid', promptText: 'p2', themeLabel: 'Childhood', parentStoryId: 's1', createdAt: '2026-01-02' },
+ { id: 's3', content: 'leaf', promptText: 'p3', themeLabel: 'Childhood', parentStoryId: 's2', createdAt: '2026-01-03' }
+ ];
+ setupMocks(makeStoriesData({ stories }), makeConfigData());
+
+ const chain = await getStoryChain('s2');
+ expect(chain.map(s => s.id)).toEqual(['s1', 's2', 's3']);
+ });
+});
+
+describe('Autobiography - weaveChainNarrative', () => {
+ const provider = { id: 'p1', name: 'Test', type: 'api', defaultModel: 'm1' };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetActiveProvider.mockResolvedValue(provider);
+ mockCallProviderAISimple.mockResolvedValue({ text: ' A flowing memoir passage. ' });
+ });
+
+ it('returns an error when the story is missing', async () => {
+ setupMocks(makeStoriesData(), makeConfigData());
+ const result = await weaveChainNarrative('nope');
+ expect(result.error).toBe('Story not found');
+ });
+
+ it('returns an error when no provider is available', async () => {
+ mockGetActiveProvider.mockResolvedValue(null);
+ setupMocks(makeStoriesData({ stories: [{ id: 's1', content: 'x', promptText: 'p', themeLabel: 'Childhood' }] }), makeConfigData());
+ const result = await weaveChainNarrative('s1');
+ expect(result.error).toBe('No AI provider available');
+ });
+
+ it('weaves the full chain into a trimmed narrative and reports the story count', async () => {
+ const stories = [
+ { id: 's1', content: 'root memory', promptText: 'p1', themeLabel: 'Childhood', createdAt: '2026-01-01' },
+ { id: 's2', content: 'deeper memory', promptText: 'p2', themeLabel: 'Childhood', parentStoryId: 's1', createdAt: '2026-01-02' }
+ ];
+ setupMocks(makeStoriesData({ stories }), makeConfigData());
+
+ const result = await weaveChainNarrative('s1');
+
+ expect(result.narrative).toBe('A flowing memoir passage.');
+ expect(result.storyCount).toBe(2);
+ // Both responses must be fed to the weaver
+ const promptArg = mockCallProviderAISimple.mock.calls[0][2];
+ expect(promptArg).toContain('root memory');
+ expect(promptArg).toContain('deeper memory');
+ });
+
+ it('returns an error when the AI returns an empty narrative', async () => {
+ mockCallProviderAISimple.mockResolvedValue({ text: ' ' });
+ setupMocks(makeStoriesData({ stories: [{ id: 's1', content: 'x', promptText: 'p', themeLabel: 'Childhood' }] }), makeConfigData());
+
+ const result = await weaveChainNarrative('s1');
+ expect(result.error).toMatch(/empty narrative/);
+ });
+});