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

add Digital Twin Avatar Bio tab for live-avatar personas

[._.]/ Adam Eivy907ee57b428c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 37cd7e623f..d2cda4387b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,6 +20,8 @@
## Added
+- **Digital Twin → Avatar Bio: copy-ready persona for live avatars.** A new **Avatar Bio** tab (reachable via ⌘K and voice) assembles a concise three-part persona — **Who I Am / How I Speak / What I Know** — sized for live-avatar platforms (HeyGen, Tavus, Simli, ElevenLabs conversational agents) whose persona/knowledge fields want a tight blurb, not the full soul-document dump that Export produces. The bio is built **deterministically** from your existing twin data (SOUL/COMMUNICATION/PERSONALITY/COGNITIVE/TECHNICAL/CREATIVE/VALUES docs + stored voice traits + goals) with graceful per-section fallbacks, so it renders instantly on tab load with **no LLM call** (never trips the no-cold-bootstrap policy). A length toggle (Blurb / Persona / Knowledge) tunes verbosity; each section and the combined bio have their own **Copy** button. An optional **Refine with AI** action rewrites the draft into first-person prose via a chosen provider, preserving every fact and inventing nothing. When no numeric voice profile has been generated yet, a nudge banner links to the Personality and Voice tabs so the "How I Speak" section can be enriched with cadence and verbal markers. New service `server/services/digital-twin-avatar-bio.js` (`buildAvatarBio` deterministic + `polishAvatarBio` provider path) and routes `GET /api/digital-twin/avatar-bio` + `POST /api/digital-twin/avatar-bio/polish`, unit-tested.
+
- **[issue-2664] Holistic "Review this series" flow.** The series detail page gains a **Review this series** panel (above Autonomous mode) that runs every read-only check at once — the foundation judge (world/characters/arc/craft quality), the full editorial-checks pass, editorial health + readiness, and canon descriptive-integrity — and composes them into a single verdict (`ready` / `issues`) with signal chips (Foundation, Health, Canon) and every finding grouped by the issue it'd be patched at, each deep-linked to that section and to a per-finding **Fix here** in the manuscript editor. An optional free-text note ("Volume 1 looks complete but nothing develops") is routed by an LLM to the best issue/section and seeded as an anchored finding, so your own observation lands where it can be fixed. When issues are found, an inline confirm (no `window.confirm`) asks whether the story is good to move forward — **Looks good** dismisses, **Fix these issues** drives the existing Series Autopilot revision cycle (reusing the CoS-domain autonomy gate + budget + SSE — no second orchestrator) to patch findings at their anchors. The review performs no manuscript writes (safe to run repeatedly) and streams progress over SSE; with the CoS auto-run domain off it degrades gracefully — review still works read-only and each finding is fixable by hand. New service `server/services/pipeline/seriesReview.js` + `POST/GET /api/pipeline/series/:id/review`, both unit-tested.
- **[issue-2656] SongBook per-instrument view with chord voicings.** The song viewer's play mode gains a Guitar/Ukulele/Piano toggle (URL-addressable via `?view=`, defaulting to the song's own instrument — bass/voice/other render guitar shapes) that swaps how chords are visualized without touching the record. Every chord token in the sheet is now tappable/keyboard-accessible and opens a viewport-clamped popover with the voicing for the active instrument: an SVG fretbox (nut, finger dots, open/muted markers, and a fret-window label for barre shapes) for guitar and ukulele, or spelled note chips (letter-accurate — the 3rd of E is G#, never Ab) for piano. Slash chords voice the base chord and show the bass separately; unknown chords degrade to "no diagram" without crashing. A collapsible "Chords used" strip above the sheet shows a mini diagram for each unique chord in first-appearance order, diagrams follow the transpose control's chord names, and guitar-specific tab staffs collapse to a one-line note (with an inline "show" expand) in the ukulele/piano views. New pure lib `client/src/lib/chordShapes.js` (curated first-position guitar shapes + movable E-/A-form barre templates, an exact lowest-position search for ukulele GCEA, interval math for piano) and `ChordDiagram` component, both unit-tested.
diff --git a/PLAN.md b/PLAN.md
index 97c2455b41..8804ecfe72 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -73,3 +73,5 @@ by `/do:replan --issues`:
- [ ] **Broaden series-review snapshot invalidation beyond the findings store.** `getSeriesReview` now stamps `stale` when the live open-finding set diverges from the snapshot's `findingIds` (covers accept/dismiss via a "Fix here" link). It does NOT detect edits to manuscript text, canon, or foundation made through other paths (the verdict's foundation/canon/health dimensions can go stale silently). Follow the `foundationJudge` pattern: stamp a `sourceInputsHash` on the review snapshot and recompute-vs-current on GET so any reviewed-source change flips `stale`. Deferred from #2664 review (codex r3, P1) as a broader pre-existing-pattern change.
- [ ] **Series-review: reject conflicting in-flight review options instead of silently coalescing.** `startSeriesReviewRun` coalesces by seriesId, so a second start with different feedback/provider/force/gate gets the running run's id and its options are dropped. Single-user/single-tab this is rare (the button disables while reviewing) and the client no longer clears the note on an `alreadyRunning` response — but a `createSseRunner` `sig`-based conflict (like storyBuilderRunner) would surface it. Deferred from #2664 review (codex r3, P2) — competing-actor/multi-tab hardening the single-user trust model largely excludes.
+
+- [ ] **Make Avatar Bio extraction tolerant of free-form twin documents.** `server/services/digital-twin-avatar-bio.js` extracts facts with helpers keyed to the shipped canonical doc structure (`**Name:**`, `## Core Purpose`, `## Reasoning Defaults`, the enrichment `### Question?` headings, etc.). Installs whose enabled Markdown does not use those exact labels/headings fall through to the "No … data yet" fallbacks even when the twin is richly populated (the document CRUD schema accepts arbitrary Markdown, and `data.reference/digital-twin` ships no enforced body template). Current behavior degrades gracefully (safe fallbacks, no crash, no wrong data) and the LLM-polish path is an escape hatch, so this was deferred from the #avatar-bio review (codex P1). Options: (a) feed the raw enabled-doc text to `polishAvatarBio` so the LLM can synthesize regardless of structure; (b) introduce and migrate a versioned canonical body format for the core docs; (c) add a light LLM-backed extraction fallback when structured parsing yields empty sections.
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.js
index 52a2a31891..9d3389b2d1 100644
--- a/client/src/components/digital-twin/constants.js
+++ b/client/src/components/digital-twin/constants.js
@@ -29,7 +29,8 @@ import {
Drama,
Mic,
Camera,
- Package
+ Package,
+ UserRound
} from 'lucide-react';
// Main navigation tabs
@@ -49,6 +50,7 @@ export const TABS = [
{ id: 'appearance', label: 'Appearance', icon: Camera },
{ id: 'autobiography', label: 'Autobiography', icon: PenLine },
{ id: 'import', label: 'Import', icon: Upload },
+ { id: 'avatar-bio', label: 'Avatar Bio', icon: UserRound },
{ id: 'export', label: 'Export', icon: Download },
{ id: 'legacy', label: 'Legacy', icon: Package },
{ id: 'time-capsule', label: 'Time Capsule', icon: Archive }
diff --git a/client/src/components/digital-twin/tabs/AvatarBioTab.jsx b/client/src/components/digital-twin/tabs/AvatarBioTab.jsx
new file mode 100644
index 0000000000..a6d3492a36
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/AvatarBioTab.jsx
@@ -0,0 +1,281 @@
+import { useState, useEffect, useCallback, useRef } from 'react';
+import { useNavigate } from 'react-router-dom';
+import useMounted from '../../../hooks/useMounted';
+import {
+ UserRound,
+ Mic,
+ BookOpen,
+ Copy,
+ Check,
+ Sparkles,
+ RefreshCw,
+ AlertCircle
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
+import BrailleSpinner from '../../BrailleSpinner';
+import useProviderModels from '../../../hooks/useProviderModels';
+import ProviderModelSelector from '../../ProviderModelSelector';
+import { copyToClipboard } from '../../../lib/clipboard';
+
+const LENGTHS = [
+ { id: 'blurb', label: 'Blurb', hint: 'One tight paragraph per section' },
+ { id: 'persona', label: 'Persona', hint: 'Balanced, avatar-ready' },
+ { id: 'knowledge', label: 'Knowledge', hint: 'Fuller detail per section' }
+];
+
+const SECTION_META = [
+ { key: 'whoIAm', title: 'Who I Am', icon: UserRound, accent: 'text-pink-400' },
+ { key: 'howISpeak', title: 'How I Speak', icon: Mic, accent: 'text-port-accent' },
+ { key: 'whatIKnow', title: 'What I Know', icon: BookOpen, accent: 'text-emerald-400' }
+];
+
+function CopyButton({ getText, label = 'Copy' }) {
+ const [copied, setCopied] = useState(false);
+ const onCopy = async () => {
+ const ok = await copyToClipboard(getText(), 'Copied to clipboard');
+ if (ok) {
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ }
+ };
+ return (
+ <button
+ onClick={onCopy}
+ className="flex items-center gap-1.5 px-2.5 py-1.5 min-h-[36px] text-xs text-gray-400 hover:text-white rounded-md border border-port-border hover:border-gray-500 transition-colors"
+ title={label}
+ >
+ {copied ? <Check size={14} className="text-port-success" /> : <Copy size={14} />}
+ {copied ? 'Copied' : label}
+ </button>
+ );
+}
+
+export default function AvatarBioTab() {
+ const navigate = useNavigate();
+ const {
+ providers, selectedProviderId, selectedModel, availableModels,
+ setSelectedProviderId, setSelectedModel, loading: providersLoading
+ } = useProviderModels();
+
+ const [length, setLength] = useState('persona');
+ const [bio, setBio] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ const [polishing, setPolishing] = useState(false);
+ const [polished, setPolished] = useState(null);
+
+ // Each length change starts a new generation. A slow in-flight load or refine
+ // from a prior length bails on the generation check so its result can't
+ // overwrite the current selection (leaving `polished`/`bio` mismatched with
+ // the visible draft). `mountedRef` (via useMounted, which resets to true on
+ // mount so StrictMode's mount→cleanup→remount doesn't strand it false) stops a
+ // late resolution writing after unmount.
+ const genRef = useRef(0);
+ const mountedRef = useMounted();
+
+ const loadBio = useCallback(async (len, gen) => {
+ setLoading(true);
+ // The deterministic build owns its own error UI here; silence the helper toast.
+ const result = await api.getAvatarBio(len, { silent: true }).catch((err) => ({ error: err.message }));
+ if (!mountedRef.current || gen !== genRef.current) return; // superseded by a newer length
+ if (result?.error) {
+ toast.error(result.error);
+ setBio(null);
+ } else {
+ setBio(result);
+ }
+ setLoading(false);
+ }, []);
+
+ useEffect(() => {
+ // New generation: reset the polish panel and reload the draft for this length.
+ const gen = ++genRef.current;
+ setPolished(null);
+ setPolishing(false);
+ loadBio(length, gen);
+ }, [length, loadBio]);
+
+ const handlePolish = async () => {
+ if (!selectedProviderId || !selectedModel) {
+ toast.error('Select a provider and model');
+ return;
+ }
+ const gen = genRef.current;
+ setPolishing(true);
+ setPolished(null);
+ const res = await api.polishAvatarBio(selectedProviderId, selectedModel, length, { silent: true })
+ .catch((err) => ({ error: err.message }));
+
+ if (!mountedRef.current || gen !== genRef.current) return; // length changed mid-refine — drop stale result
+ if (res?.error && res.rawResponse) {
+ setPolished(res); // surface the unparseable-response notice inline
+ } else if (res?.error) {
+ toast.error(res.error);
+ } else {
+ setPolished(res);
+ toast.success('Avatar bio refined');
+ }
+ setPolishing(false);
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <BrailleSpinner text="Loading" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6 max-w-4xl mx-auto">
+ {/* Intro */}
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <div className="flex items-start gap-3 mb-4">
+ <UserRound className="w-6 h-6 text-pink-500 shrink-0 mt-0.5" />
+ <div>
+ <h2 className="text-lg font-semibold text-white">Live Avatar Bio</h2>
+ <p className="text-sm text-gray-400">
+ A concise, copy-ready persona for live-avatar platforms (HeyGen, Tavus, Simli,
+ ElevenLabs agents). Assembled from your Digital Twin — no AI call needed. Optionally
+ refine it into first-person prose with a provider.
+ </p>
+ </div>
+ </div>
+
+ {/* Length selector */}
+ <div className="flex flex-wrap items-center gap-2">
+ {LENGTHS.map(({ id, label, hint }) => (
+ <button
+ key={id}
+ onClick={() => setLength(id)}
+ title={hint}
+ className={`px-3 py-1.5 min-h-[36px] rounded-md text-sm border transition-colors ${
+ length === id
+ ? 'border-port-accent bg-port-accent/10 text-port-accent'
+ : 'border-port-border text-gray-400 hover:border-gray-500 hover:text-white'
+ }`}
+ >
+ {label}
+ </button>
+ ))}
+ {bio && (
+ <span className="text-xs text-gray-500 ml-auto">~{bio.tokenEstimate?.toLocaleString()} tokens</span>
+ )}
+ </div>
+ </div>
+
+ {/* Voice-traits nudge */}
+ {bio && !bio.hasVoiceTraits && (
+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-4 flex items-start gap-3">
+ <AlertCircle className="w-5 h-5 text-port-warning shrink-0 mt-0.5" />
+ <div className="text-sm text-gray-300">
+ <p className="font-medium text-white mb-1">Voice profile not yet captured</p>
+ <p className="mb-2">
+ The <span className="text-white">How I Speak</span> section is qualitative only. For an avatar,
+ cadence and verbal markers matter — generate a numeric voice profile to enrich it.
+ </p>
+ <div className="flex flex-wrap gap-2">
+ <button
+ onClick={() => navigate('/digital-twin/personality')}
+ className="px-3 py-1.5 min-h-[36px] text-xs rounded-md border border-port-border hover:border-gray-500 text-gray-300 hover:text-white"
+ >
+ Analyze Personality
+ </button>
+ <button
+ onClick={() => navigate('/digital-twin/voice')}
+ className="px-3 py-1.5 min-h-[36px] text-xs rounded-md border border-port-border hover:border-gray-500 text-gray-300 hover:text-white"
+ >
+ Compare Voice & Style
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Section cards */}
+ {bio && (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wide">Draft</h3>
+ <CopyButton getText={() => bio.combined} label="Copy all" />
+ </div>
+
+ {SECTION_META.map(({ key, title, icon: Icon, accent }) => (
+ <div key={key} className="bg-port-card rounded-lg border border-port-border p-5">
+ <div className="flex items-center justify-between mb-3">
+ <h4 className={`flex items-center gap-2 text-sm font-semibold ${accent}`}>
+ <Icon size={16} /> {title}
+ </h4>
+ <CopyButton getText={() => bio.sections[key]} />
+ </div>
+ <p className="text-sm text-gray-300 whitespace-pre-wrap leading-relaxed">
+ {bio.sections[key]}
+ </p>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* AI polish */}
+ <div className="bg-port-card rounded-lg border border-port-border p-6 space-y-4">
+ <div className="flex items-center gap-2">
+ <Sparkles className="w-5 h-5 text-port-accent" />
+ <h3 className="text-base font-semibold text-white">Refine with AI (optional)</h3>
+ </div>
+ <p className="text-sm text-gray-400">
+ Rewrite the draft into natural first-person prose. Only facts from your twin are used —
+ nothing is invented.
+ </p>
+
+ {!providersLoading && providers.length > 0 && (
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={setSelectedProviderId}
+ onModelChange={setSelectedModel}
+ disabled={polishing}
+ />
+ )}
+
+ <div className="flex justify-end">
+ <button
+ onClick={handlePolish}
+ disabled={polishing || !selectedProviderId || !selectedModel}
+ className="flex items-center gap-2 px-6 py-3 min-h-[48px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {polishing ? (
+ <><RefreshCw size={18} className="animate-spin" /> Refining...</>
+ ) : (
+ <><Sparkles size={18} /> Refine with AI</>
+ )}
+ </button>
+ </div>
+
+ {polished && polished.content && (
+ <div className="bg-port-bg rounded-lg border border-port-success/30 p-5 space-y-3">
+ <div className="flex items-center justify-between">
+ <h4 className="text-sm font-semibold text-port-success">Refined bio</h4>
+ <div className="flex items-center gap-3">
+ <span className="text-xs text-gray-500">~{polished.tokenEstimate?.toLocaleString()} tokens</span>
+ <CopyButton getText={() => polished.content} />
+ </div>
+ </div>
+ <pre className="text-sm text-gray-300 whitespace-pre-wrap font-sans leading-relaxed">
+ {polished.content}
+ </pre>
+ </div>
+ )}
+
+ {polished && polished.error && polished.rawResponse && (
+ <div className="flex items-center gap-3 text-sm text-gray-400">
+ <AlertCircle size={16} className="text-port-warning" />
+ The model response could not be parsed as an avatar bio.
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index b7b5f56004..3c0bf52863 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -26,6 +26,7 @@ const PersonasTab = lazy(() => import('../components/digital-twin/tabs/PersonasT
const GoalsTab = lazy(() => import('../components/digital-twin/tabs/GoalsTab'));
const AutobiographyTab = lazy(() => import('../components/digital-twin/tabs/AutobiographyTab'));
const ImportTab = lazy(() => import('../components/digital-twin/tabs/ImportTab'));
+const AvatarBioTab = lazy(() => import('../components/digital-twin/tabs/AvatarBioTab'));
const ExportTab = lazy(() => import('../components/digital-twin/tabs/ExportTab'));
const LegacyExportTab = lazy(() => import('../components/digital-twin/tabs/LegacyExportTab'));
const TimeCapsuleTab = lazy(() => import('../components/digital-twin/tabs/TimeCapsuleTab'));
@@ -88,6 +89,8 @@ export default function DigitalTwin() {
return <AutobiographyTab onRefresh={refetch} />;
case 'import':
return <ImportTab onRefresh={refetch} />;
+ case 'avatar-bio':
+ return <AvatarBioTab />;
case 'export':
return <ExportTab onRefresh={refetch} />;
case 'legacy':
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index 10efd58ee9..7542d310bd 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -77,6 +77,17 @@ export const exportDigitalTwin = (format, documentIds = null, includeDisabled =
body: JSON.stringify({ format, documentIds, includeDisabled })
});
+// Digital Twin - Live Avatar Bio. GET is deterministic (no LLM, safe on load);
+// polish is an explicit provider call that rewrites the draft into first-person.
+export const getAvatarBio = (length = 'persona', options = {}) =>
+ request(`/digital-twin/avatar-bio?length=${encodeURIComponent(length)}`, options);
+export const polishAvatarBio = (providerId, model, length = 'persona', options = {}) =>
+ request('/digital-twin/avatar-bio/polish', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model, length }),
+ ...options
+ });
+
// Legacy Export (portable identity bundle) — #901 Phase 1 server foundation:
// `GET /api/legacy-export/preview` + `POST /api/legacy-export`. The preview is
// cheap enough to call on page load; the bundle build streams a zip attachment.
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index 32ca12ed0a..1c57399cec 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -387,6 +387,22 @@ export const exportInputSchema = z.object({
includeDisabled: z.boolean().optional().default(false)
});
+// Live Avatar Bio — length preset shared by the deterministic build and the
+// optional LLM polish. Kept in sync with AVATAR_BIO_LENGTHS in the service.
+export const avatarBioLengthEnum = z.enum(['blurb', 'persona', 'knowledge']);
+
+// Optional length query for the deterministic GET (defaults to 'persona').
+export const avatarBioQuerySchema = z.object({
+ length: avatarBioLengthEnum.optional().default('persona')
+});
+
+// LLM-polish input — explicit user-triggered provider call.
+export const avatarBioPolishInputSchema = z.object({
+ providerId: z.string().min(1),
+ model: z.string().min(1),
+ length: avatarBioLengthEnum.optional().default('persona')
+});
+
// Settings update input
export const settingsUpdateInputSchema = partialWithoutDefaults(soulSettingsSchema);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index da5c573213..5169679974 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -124,6 +124,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.twin.appearance', path: '/digital-twin/appearance', label: 'Appearance', section: 'Identity', aliases: ['twin-appearance', 'appearance', 'photo'], keywords: ['image', 'photo', 'vision', 'face', 'identity', 'presentation', 'look', 'avatar'] },
{ id: 'nav.ask', path: '/ask', label: 'Ask Yourself', section: 'Identity', aliases: ['ask', 'ask-yourself', 'twin-chat'], keywords: ['chat', 'twin', 'conversation', 'advise', 'draft'] },
{ id: 'nav.twin.autobiography', path: '/digital-twin/autobiography', label: 'Autobiography', section: 'Identity', aliases: ['twin-autobiography', 'autobiography'] },
+ { id: 'nav.twin.avatar-bio', path: '/digital-twin/avatar-bio', label: 'Avatar Bio', section: 'Identity', aliases: ['avatar-bio', 'twin-avatar-bio', 'avatar', 'live-avatar'], keywords: ['heygen', 'tavus', 'simli', 'elevenlabs', 'persona', 'bio', 'voice', 'live avatar', 'who i am', 'how i speak', 'what i know'] },
{ id: 'nav.character', path: '/character', label: 'Character', section: 'Identity', aliases: ['character'] },
{ id: 'nav.twin.documents', path: '/digital-twin/documents', label: 'Documents', section: 'Identity', aliases: ['twin-documents'] },
{ id: 'nav.twin.enrich', path: '/digital-twin/enrich', label: 'Enrich', section: 'Identity', aliases: ['twin-enrich'] },
diff --git a/server/routes/digital-twin/avatar-bio.js b/server/routes/digital-twin/avatar-bio.js
new file mode 100644
index 0000000000..1d82f21c1a
--- /dev/null
+++ b/server/routes/digital-twin/avatar-bio.js
@@ -0,0 +1,38 @@
+/**
+ * Digital Twin — Live Avatar Bio.
+ *
+ * A concise, copy-ready "Who I am / How I speak / What I know" persona for live
+ * avatar platforms. GET builds it deterministically (no LLM); POST /polish is an
+ * explicit, user-triggered provider call that rewrites it into first-person prose.
+ */
+
+import { Router } from 'express';
+import * as digitalTwinService from '../../services/digital-twin.js';
+import { asyncHandler } from '../../lib/errorHandler.js';
+import { validateRequest } from '../../lib/validation.js';
+import { avatarBioQuerySchema, avatarBioPolishInputSchema } from '../../lib/digitalTwinValidation.js';
+
+const router = Router();
+
+/**
+ * GET /api/digital-twin/avatar-bio?length=persona
+ * Deterministic three-part avatar bio. Safe to call on tab load (no LLM).
+ */
+router.get('/avatar-bio', asyncHandler(async (req, res) => {
+ const { length } = validateRequest(avatarBioQuerySchema, req.query);
+ const bio = await digitalTwinService.buildAvatarBio({ length });
+ res.json(bio);
+}));
+
+/**
+ * POST /api/digital-twin/avatar-bio/polish
+ * Rewrite the deterministic draft into first-person avatar-ready prose via an
+ * AI provider (explicit user action).
+ */
+router.post('/avatar-bio/polish', asyncHandler(async (req, res) => {
+ const { providerId, model, length } = validateRequest(avatarBioPolishInputSchema, req.body);
+ const result = await digitalTwinService.polishAvatarBio({ providerId, model, length });
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/routes/digital-twin/index.js b/server/routes/digital-twin/index.js
index 4c30dbd904..8e13363f0e 100644
--- a/server/routes/digital-twin/index.js
+++ b/server/routes/digital-twin/index.js
@@ -11,6 +11,7 @@
* tests — behavioral / values-alignment / adversarial / multi-turn suites + generate
* enrichment — enrichment questionnaire (categories, progress, question/answer, lists)
* export — export formats + export
+ * avatarBio — live-avatar bio (deterministic build + optional LLM polish)
* settings — GET/PUT settings
* personas — persona CRUD + active pointer (M34 P7)
* analysis — validate, writing/style analysis, identity image, traits, confidence, gaps, assessment
@@ -33,6 +34,7 @@ import documentRoutes from './documents.js';
import testRoutes from './tests.js';
import enrichmentRoutes from './enrichment.js';
import exportRoutes from './export.js';
+import avatarBioRoutes from './avatar-bio.js';
import settingsRoutes from './settings.js';
import personaRoutes from './personas.js';
import analysisRoutes from './analysis.js';
@@ -49,6 +51,7 @@ router.use(documentRoutes);
router.use(testRoutes);
router.use(enrichmentRoutes);
router.use(exportRoutes);
+router.use(avatarBioRoutes);
router.use(settingsRoutes);
router.use(personaRoutes);
router.use(analysisRoutes);
diff --git a/server/services/digital-twin-avatar-bio.js b/server/services/digital-twin-avatar-bio.js
new file mode 100644
index 0000000000..52aa4213d4
--- /dev/null
+++ b/server/services/digital-twin-avatar-bio.js
@@ -0,0 +1,323 @@
+/**
+ * Digital Twin — Live Avatar Bio.
+ *
+ * Assembles a concise, three-part persona ("Who I am / How I speak / What I
+ * know") sized for live-avatar platforms (HeyGen, Tavus, Simli, ElevenLabs
+ * conversational agents, etc.) whose persona/knowledge fields want a tight
+ * blurb, not the full soul-document dump that Export produces.
+ *
+ * Two paths:
+ * - buildAvatarBio() — DETERMINISTIC. Pure assembly from the twin documents +
+ * stored traits + goals. No LLM call, so it is safe to run on tab load and
+ * never trips the "no cold-bootstrap LLM calls" policy.
+ * - polishAvatarBio() — explicit, user-triggered provider call that rewrites
+ * the deterministic draft into first-person, avatar-ready prose.
+ */
+
+import { readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { DIGITAL_TWIN_DIR, callProviderAI } from './digital-twin-helpers.js';
+import { loadMeta } from './digital-twin-meta.js';
+import { getTraits } from './digital-twin-analysis.js';
+import { getGoals } from './identity.js';
+import { getProviderById } from './providers.js';
+import { estimateTokens } from '../lib/contextBudget.js';
+
+// Bio length presets. `blurb` is a single paragraph per section (avatar persona
+// fields are often short); `persona` is the balanced default; `knowledge` keeps
+// more detail for platforms that accept a longer knowledge-base document.
+export const AVATAR_BIO_LENGTHS = ['blurb', 'persona', 'knowledge'];
+export const DEFAULT_AVATAR_BIO_LENGTH = 'persona';
+
+async function readDoc(filename) {
+ const filePath = join(DIGITAL_TWIN_DIR, filename);
+ if (!existsSync(filePath)) return null;
+ return readFile(filePath, 'utf-8').catch(() => null);
+}
+
+/**
+ * Pull a single `**Label:** value` line out of a markdown block (the SOUL.md
+ * identity list uses this shape). Returns the trimmed value or null.
+ */
+function pullLabeledLine(md, label) {
+ if (!md) return null;
+ const m = md.match(new RegExp(`\\*\\*${label}:\\*\\*\\s*(.+)`));
+ return m ? m[1].trim() : null;
+}
+
+/**
+ * Extract the body of a `## Heading` (or `### Heading`) section — everything up
+ * to the next heading of the same-or-higher level (or end of document). Returns
+ * trimmed text or null. Line-based rather than a single regex so a section that
+ * runs to EOF (no trailing heading) still resolves.
+ */
+function extractSection(md, heading) {
+ if (!md) return null;
+ const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ const headingRe = new RegExp(`^(#{2,3})\\s+${escaped}\\s*$`, 'i');
+ const lines = md.split('\n');
+ let start = -1;
+ let level = 0;
+ for (let i = 0; i < lines.length; i++) {
+ const m = lines[i].match(headingRe);
+ if (m) { start = i + 1; level = m[1].length; break; }
+ }
+ if (start === -1) return null;
+ const body = [];
+ for (let j = start; j < lines.length; j++) {
+ const hm = lines[j].match(/^(#{1,6})\s/);
+ if (hm && hm[1].length <= level) break; // next same-or-higher-level heading
+ body.push(lines[j]);
+ }
+ const text = body.join('\n').trim();
+ return text || null;
+}
+
+/**
+ * Pull the answer text that follows a `### Question?` heading in the enrichment
+ * docs (VALUES.md, PERSONALITY.md, NON_NEGOTIABLES.md). Matches the first
+ * heading that *contains* `needle` (case-insensitive). Returns the first
+ * non-empty line of the answer, or null.
+ */
+function pullEnrichmentAnswer(md, needle) {
+ if (!md) return null;
+ const lines = md.split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ if (/^#{2,4}\s/.test(lines[i]) && lines[i].toLowerCase().includes(needle.toLowerCase())) {
+ for (let j = i + 1; j < lines.length; j++) {
+ const t = lines[j].trim();
+ if (/^#{1,4}\s/.test(t)) break; // hit the next heading — no answer
+ if (t) return t;
+ }
+ }
+ }
+ return null;
+}
+
+/** Strip markdown backslash-escapes (e.g. `\[._.]/` → `[._.]/`) and trim. */
+function unescapeMd(str) {
+ return str == null ? str : str.replace(/\\([[\]._./*])/g, '$1').trim();
+}
+
+/** Drop trailing sentence punctuation/whitespace so callers can re-add one `.`. */
+function stripTrailingPunct(str) {
+ return str == null ? str : str.replace(/[.;,\s]+$/, '');
+}
+
+/**
+ * Collapse a markdown bullet block into a compact `a; b; c` phrase. Only real
+ * bullet lines (`-`/`*`) are taken — plain prose lines that happen to sit inside
+ * the section (e.g. a trailing "Tone target:" lead-in) are skipped.
+ */
+function bulletsToPhrase(block, max = 8) {
+ if (!block) return null;
+ const items = block
+ .split('\n')
+ .filter(l => /^\s*[-*]\s+/.test(l))
+ .map(l => l.replace(/^\s*[-*]\s*/, '').replace(/\*\*/g, '').trim())
+ .filter(Boolean)
+ .slice(0, max);
+ return items.length ? items.join('; ') : null;
+}
+
+function formalityWord(n) {
+ if (n == null) return null;
+ if (n <= 3) return 'casual';
+ if (n <= 6) return 'balanced';
+ return 'formal';
+}
+function verbosityWord(n) {
+ if (n == null) return null;
+ if (n <= 3) return 'terse';
+ if (n <= 6) return 'measured';
+ return 'elaborate';
+}
+
+/**
+ * Build the deterministic three-part avatar bio.
+ *
+ * Every fact is pulled from real twin data with a graceful fallback — a missing
+ * document or section simply omits its contribution rather than throwing. When
+ * the whole twin is empty the sections come back with a single "no data yet"
+ * note so the UI can still render and point the user at enrichment.
+ */
+export async function buildAvatarBio({ length = DEFAULT_AVATAR_BIO_LENGTH } = {}) {
+ const useLength = AVATAR_BIO_LENGTHS.includes(length) ? length : DEFAULT_AVATAR_BIO_LENGTH;
+
+ // Honor the same disabled-document boundary as getDigitalTwinForPrompt and
+ // exportDigitalTwin: a doc the user turned off must not surface in the bio (and
+ // must never be transmitted to an external provider on Refine). Only a doc that
+ // is explicitly disabled in meta is excluded; untracked/ambient files still read.
+ const meta = await loadMeta().catch(() => ({ documents: [] }));
+ const disabled = new Set(
+ (Array.isArray(meta.documents) ? meta.documents : [])
+ .filter(d => d && d.enabled === false)
+ .map(d => d.filename)
+ );
+ const readEnabled = (filename) => (disabled.has(filename) ? Promise.resolve(null) : readDoc(filename));
+
+ const [soul, communication, personality, cognitive, technical, creative, values, nonNegotiables, traits, goalsData] =
+ await Promise.all([
+ readEnabled('SOUL.md'),
+ readEnabled('COMMUNICATION.md'),
+ readEnabled('PERSONALITY.md'),
+ readEnabled('COGNITIVE.md'),
+ readEnabled('TECHNICAL.md'),
+ readEnabled('CREATIVE.md'),
+ readEnabled('VALUES.md'),
+ readEnabled('NON_NEGOTIABLES.md'),
+ getTraits().catch(() => null),
+ getGoals().catch(() => ({ goals: [] })),
+ ]);
+
+ const name = unescapeMd(pullLabeledLine(soul, 'Name')) || 'the user';
+ const aliases = unescapeMd(pullLabeledLine(soul, 'Aliases'));
+ const orientation = pullLabeledLine(soul, 'Orientation');
+ const primaryMode = pullLabeledLine(soul, 'Primary Mode');
+ const topValues = pullEnrichmentAnswer(values, 'top three values') || pullEnrichmentAnswer(values, 'values that guide');
+
+ const comm = traits?.communicationProfile || null;
+ const hasVoiceTraits = Boolean(comm && (comm.formality != null || comm.verbosity != null ||
+ comm.preferredTone || (Array.isArray(comm.distinctiveMarkers) && comm.distinctiveMarkers.length)));
+
+ const goals = Array.isArray(goalsData?.goals) ? goalsData.goals : [];
+ const activeGoals = goals
+ .filter(g => g.status && g.status !== 'abandoned' && g.status !== 'completed')
+ .sort((a, b) => (b.priority === 'high' ? 1 : 0) - (a.priority === 'high' ? 1 : 0));
+ const topGoalTitles = activeGoals.slice(0, useLength === 'blurb' ? 3 : 6).map(g => g.title).filter(Boolean);
+
+ // ---- WHO I AM ----
+ const whoLines = [];
+ const idBits = [name, aliases ? `also known as ${aliases}` : null].filter(Boolean).join(', ');
+ if (primaryMode || orientation) {
+ whoLines.push(`${idBits}${primaryMode ? ` — ${primaryMode.toLowerCase()}` : ''}${orientation ? `. ${orientation}` : ''}.`);
+ } else if (idBits && idBits !== 'the user') {
+ whoLines.push(`${idBits}.`);
+ }
+ const corePurpose = extractSection(soul, 'Core Purpose');
+ const purposeLead = corePurpose ? corePurpose.split('\n').map(l => l.trim()).find(l => l && !/^#/.test(l)) : null;
+ if (purposeLead) whoLines.push(purposeLead);
+ if (topValues) whoLines.push(`Core values: ${topValues}.`);
+ const refuseTopic = pullEnrichmentAnswer(nonNegotiables, 'absolutely refuse');
+ if (refuseTopic && useLength !== 'blurb') whoLines.push(`Will not engage with: ${refuseTopic}.`);
+ if (topGoalTitles.length) whoLines.push(`Current goals: ${topGoalTitles.join('; ')}.`);
+
+ // ---- HOW I SPEAK ----
+ const howLines = [];
+ const toneTarget = soul?.match(/Tone target:\s*\n>\s*(.+)/i)?.[1]?.trim();
+ if (toneTarget) howLines.push(`Tone: ${stripTrailingPunct(toneTarget)}.`);
+ const commPrefs = bulletsToPhrase(extractSection(soul, 'Communication Preferences'));
+ if (commPrefs) howLines.push(`Style: ${commPrefs}.`);
+ const feedbackPref = pullEnrichmentAnswer(communication, 'critical feedback');
+ if (feedbackPref) howLines.push(`Prefers ${feedbackPref} feedback.`);
+ const mbti = pullEnrichmentAnswer(personality, 'Myers-Briggs');
+ if (mbti) howLines.push(`Personality type: ${mbti}.`);
+ if (hasVoiceTraits) {
+ const bits = [];
+ const fw = formalityWord(comm.formality);
+ const vw = verbosityWord(comm.verbosity);
+ if (fw) bits.push(`${fw} formality (${comm.formality}/10)`);
+ if (vw) bits.push(`${vw} verbosity (${comm.verbosity}/10)`);
+ if (comm.avgSentenceLength) bits.push(`~${Math.round(comm.avgSentenceLength)}-word sentences`);
+ if (bits.length) howLines.push(`Cadence: ${bits.join(', ')}.`);
+ if (Array.isArray(comm.distinctiveMarkers) && comm.distinctiveMarkers.length) {
+ howLines.push(`Verbal markers: ${comm.distinctiveMarkers.join('; ')}.`);
+ }
+ }
+ // Humor lists "acceptable when" bullets then an "Avoid:" block — keep only the
+ // positive half so the bio doesn't read as if slapstick IS the user's humor.
+ const humorBlock = useLength !== 'blurb' ? extractSection(soul, 'Humor') : null;
+ const humor = humorBlock ? bulletsToPhrase(humorBlock.split(/^avoid\b/im)[0]) : null;
+ if (humor) howLines.push(`Humor: ${humor}.`);
+
+ // ---- WHAT I KNOW ----
+ const whatLines = [];
+ const techDepth = bulletsToPhrase(extractSection(technical, 'Depth & Orientation'));
+ const techPhilosophy = useLength === 'knowledge' ? bulletsToPhrase(extractSection(technical, 'Building Philosophy')) : null;
+ if (techDepth) whatLines.push(`Technical: ${techDepth}.`);
+ if (techPhilosophy) whatLines.push(`Building philosophy: ${techPhilosophy}.`);
+ const creativeDna = bulletsToPhrase(extractSection(creative, 'Creative DNA'));
+ if (creativeDna) whatLines.push(`Creative: ${creativeDna}.`);
+ const reasoning = bulletsToPhrase(extractSection(cognitive, 'Reasoning Defaults'));
+ if (reasoning) whatLines.push(`Reasoning: ${reasoning}.`);
+ const epistemic = useLength === 'knowledge' ? bulletsToPhrase(extractSection(cognitive, 'Epistemic Style')) : null;
+ if (epistemic) whatLines.push(`Epistemics: ${epistemic}.`);
+
+ const sections = {
+ whoIAm: whoLines.length ? whoLines.join('\n\n') : '_No identity data yet — add documents in the Enrich tab._',
+ howISpeak: howLines.length ? howLines.join('\n\n') : '_No communication data yet — run the Voice or Personality tab._',
+ whatIKnow: whatLines.length ? whatLines.join('\n\n') : '_No knowledge data yet — add Technical/Creative/Cognitive documents._',
+ };
+
+ const combined = [
+ `# Live Avatar Bio — ${name}`,
+ '',
+ '## Who I Am',
+ sections.whoIAm,
+ '',
+ '## How I Speak',
+ sections.howISpeak,
+ '',
+ '## What I Know',
+ sections.whatIKnow,
+ ].join('\n');
+
+ return {
+ length: useLength,
+ name,
+ sections,
+ combined,
+ hasVoiceTraits,
+ tokenEstimate: estimateTokens(combined),
+ };
+}
+
+const LENGTH_GUIDANCE = {
+ blurb: 'Keep it very tight — one short paragraph per section, suitable for a small persona field.',
+ persona: 'Balanced length — 2–4 sentences per section, avatar-persona ready.',
+ knowledge: 'Fuller detail per section — this feeds an avatar knowledge base, so more depth is welcome.',
+};
+
+/**
+ * Refine the deterministic draft into first-person, avatar-ready prose via an
+ * AI provider. Explicit user action only. Returns { content, tokenEstimate } or
+ * { error, rawResponse } so the caller can surface an unparseable/failed run.
+ */
+export async function polishAvatarBio({ providerId, model, length = DEFAULT_AVATAR_BIO_LENGTH }) {
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ return { error: 'Provider not found or disabled' };
+ }
+
+ const draft = await buildAvatarBio({ length });
+
+ const prompt = [
+ 'You are helping a person create the persona description for a live conversational AI avatar of themselves.',
+ 'Rewrite the structured draft below into natural, first-person prose ("I am…", "I speak…", "I know…").',
+ 'Keep three clearly labeled sections: "Who I Am", "How I Speak", and "What I Know".',
+ 'Preserve every concrete fact from the draft. Do NOT invent biography, credentials, or details not present.',
+ LENGTH_GUIDANCE[draft.length] || LENGTH_GUIDANCE.persona,
+ 'Output clean Markdown with a `## ` heading per section and no preamble.',
+ '',
+ '--- DRAFT ---',
+ draft.combined,
+ '--- END DRAFT ---',
+ ].join('\n');
+
+ const { text, error } = await callProviderAI(provider, model, prompt);
+ if (error) return { error };
+
+ const content = (text || '').trim();
+ if (!content || !/who i am/i.test(content)) {
+ return { error: 'The model response could not be parsed as an avatar bio', rawResponse: text || '' };
+ }
+
+ return {
+ length: draft.length,
+ name: draft.name,
+ hasVoiceTraits: draft.hasVoiceTraits,
+ content,
+ tokenEstimate: estimateTokens(content),
+ };
+}
diff --git a/server/services/digital-twin-avatar-bio.test.js b/server/services/digital-twin-avatar-bio.test.js
new file mode 100644
index 0000000000..d59342d50e
--- /dev/null
+++ b/server/services/digital-twin-avatar-bio.test.js
@@ -0,0 +1,218 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ---- Mocks (declared before importing the module under test) ----
+// Fixtures are deliberately synthetic — no live-instance identity data (per the
+// repo's Sensitive Data policy, tests are treated as public artifacts).
+
+const DOCS = {
+ 'SOUL.md': [
+ '# Soul Document — Ada Lumen',
+ '## Identity',
+ '- **Name:** Ada Lumen',
+ '- **Aliases:** lum | lumenaut',
+ '- **Orientation:** Rationalist, tinkerer',
+ '- **Primary Mode:** Builder, planner, tinkerer',
+ '## Core Purpose',
+ 'Life is organized around building useful tools and durable artifacts.',
+ '## Communication Preferences',
+ '- No filler',
+ '- Clarity over comfort',
+ 'Tone target:',
+ '> Peer collaborator with sharp edges',
+ '## Humor',
+ '- dry',
+ '- absurd',
+ '## References',
+ '- Example',
+ ].join('\n'),
+ 'COMMUNICATION.md': [
+ '# Communication Style',
+ '### How do you prefer to receive critical feedback?',
+ 'direct',
+ ].join('\n'),
+ 'PERSONALITY.md': [
+ '# Personality Assessments',
+ '### What is your Myers-Briggs type?',
+ 'INTP/ENTP',
+ ].join('\n'),
+ 'COGNITIVE.md': [
+ '# Cognitive Architecture',
+ '## Reasoning Defaults',
+ '- Decompose then test',
+ '- Systems thinking',
+ '## Epistemic Style',
+ '- Demands mechanism',
+ ].join('\n'),
+ 'TECHNICAL.md': [
+ '# Technical Profile',
+ '## Depth & Orientation',
+ '- Senior engineer across web stacks',
+ '- Thinks in systems',
+ '## Building Philosophy',
+ '- Tool-builder by default',
+ ].join('\n'),
+ 'CREATIVE.md': [
+ '# Creative Profile',
+ '## Creative DNA',
+ '- Genre gravity: sci-fi + puzzles',
+ '- Worlds over vignettes',
+ ].join('\n'),
+ 'VALUES.md': [
+ '# Values',
+ '### What are the top three values that guide your most important decisions?',
+ 'curiosity, craft, candor',
+ ].join('\n'),
+ 'NON_NEGOTIABLES.md': [
+ '# Non-Negotiables',
+ '### What topic should your digital twin absolutely refuse to engage with?',
+ 'medical diagnosis',
+ ].join('\n'),
+};
+
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ const name = String(path).split('/').pop();
+ if (DOCS[name] != null) return DOCS[name];
+ throw new Error('ENOENT');
+ }),
+}));
+
+vi.mock('fs', () => ({ existsSync: vi.fn(() => true) }));
+
+vi.mock('./digital-twin-helpers.js', () => ({
+ DIGITAL_TWIN_DIR: '/twin',
+ callProviderAI: vi.fn(),
+}));
+
+vi.mock('./digital-twin-meta.js', () => ({ loadMeta: vi.fn() }));
+vi.mock('./digital-twin-analysis.js', () => ({ getTraits: vi.fn() }));
+vi.mock('./identity.js', () => ({ getGoals: vi.fn() }));
+vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));
+
+import { buildAvatarBio, polishAvatarBio } from './digital-twin-avatar-bio.js';
+import { loadMeta } from './digital-twin-meta.js';
+import { getTraits } from './digital-twin-analysis.js';
+import { getGoals } from './identity.js';
+import { getProviderById } from './providers.js';
+import { callProviderAI } from './digital-twin-helpers.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ loadMeta.mockResolvedValue({ documents: [] }); // nothing explicitly disabled
+ getTraits.mockResolvedValue(null);
+ getGoals.mockResolvedValue({
+ goals: [
+ { title: 'Build a Useful Tool', status: 'active', priority: 'high' },
+ { title: 'Learn the Cello', status: 'active', priority: 'low' },
+ { title: 'Old Finished Thing', status: 'completed', priority: 'low' },
+ ],
+ });
+});
+
+describe('buildAvatarBio', () => {
+ it('assembles three grounded sections from twin documents', async () => {
+ const bio = await buildAvatarBio();
+
+ expect(bio.name).toBe('Ada Lumen');
+ expect(bio.length).toBe('persona');
+ expect(bio.combined).toContain('## Who I Am');
+ expect(bio.combined).toContain('## How I Speak');
+ expect(bio.combined).toContain('## What I Know');
+
+ // WHO — identity + values + goals (completed goal excluded)
+ expect(bio.sections.whoIAm).toContain('Ada Lumen');
+ expect(bio.sections.whoIAm).toContain('curiosity, craft, candor');
+ expect(bio.sections.whoIAm).toContain('Build a Useful Tool');
+ expect(bio.sections.whoIAm).not.toContain('Old Finished Thing');
+
+ // HOW — tone target + MBTI + feedback pref
+ expect(bio.sections.howISpeak).toContain('Peer collaborator with sharp edges');
+ expect(bio.sections.howISpeak).toContain('INTP/ENTP');
+ expect(bio.sections.howISpeak.toLowerCase()).toContain('direct');
+
+ // WHAT — technical + creative + reasoning
+ expect(bio.sections.whatIKnow).toContain('Senior engineer');
+ expect(bio.sections.whatIKnow.toLowerCase()).toContain('sci-fi');
+
+ expect(bio.tokenEstimate).toBeGreaterThan(0);
+ });
+
+ it('flags hasVoiceTraits false when no communication profile is stored', async () => {
+ const bio = await buildAvatarBio();
+ expect(bio.hasVoiceTraits).toBe(false);
+ expect(bio.sections.howISpeak).not.toContain('Cadence:');
+ });
+
+ it('includes numeric cadence + markers when traits are present', async () => {
+ getTraits.mockResolvedValue({
+ communicationProfile: {
+ formality: 4, verbosity: 7, avgSentenceLength: 18,
+ distinctiveMarkers: ['em-dashes', 'first-principles framing'],
+ },
+ });
+ const bio = await buildAvatarBio();
+ expect(bio.hasVoiceTraits).toBe(true);
+ expect(bio.sections.howISpeak).toContain('Cadence:');
+ expect(bio.sections.howISpeak).toContain('4/10');
+ expect(bio.sections.howISpeak).toContain('em-dashes');
+ });
+
+ it('blurb length omits refuse-topic and humor detail', async () => {
+ const bio = await buildAvatarBio({ length: 'blurb' });
+ expect(bio.length).toBe('blurb');
+ expect(bio.sections.whoIAm).not.toContain('Will not engage with');
+ expect(bio.sections.howISpeak).not.toContain('Humor:');
+ });
+
+ it('excludes documents the user has disabled in meta', async () => {
+ // SOUL.md disabled → identity/tone/values-from-soul must not surface, and the
+ // name falls back rather than leaking the disabled doc's content.
+ loadMeta.mockResolvedValue({
+ documents: [{ filename: 'SOUL.md', enabled: false }],
+ });
+ const bio = await buildAvatarBio();
+ expect(bio.name).toBe('the user');
+ expect(bio.sections.whoIAm).not.toContain('Ada Lumen');
+ expect(bio.sections.howISpeak).not.toContain('Peer collaborator with sharp edges');
+ // A still-enabled doc (COMMUNICATION.md) is unaffected.
+ expect(bio.sections.howISpeak.toLowerCase()).toContain('direct');
+ });
+
+ it('falls back gracefully when documents are missing', async () => {
+ const fsp = await import('fs/promises');
+ fsp.readFile.mockRejectedValue(new Error('ENOENT'));
+ getGoals.mockResolvedValue({ goals: [] });
+ const bio = await buildAvatarBio();
+ expect(bio.name).toBe('the user');
+ expect(bio.sections.whoIAm).toContain('No identity data yet');
+ expect(bio.sections.howISpeak).toContain('No communication data yet');
+ });
+});
+
+describe('polishAvatarBio', () => {
+ it('rejects when the provider is missing or disabled', async () => {
+ getProviderById.mockResolvedValue(null);
+ const res = await polishAvatarBio({ providerId: 'x', model: 'm' });
+ expect(res.error).toMatch(/provider not found/i);
+ expect(callProviderAI).not.toHaveBeenCalled();
+ });
+
+ it('returns refined content on a well-formed provider response', async () => {
+ getProviderById.mockResolvedValue({ id: 'x', enabled: true });
+ callProviderAI.mockResolvedValue({
+ text: '## Who I Am\nI am Ada.\n## How I Speak\nDirectly.\n## What I Know\nSystems.',
+ });
+ const res = await polishAvatarBio({ providerId: 'x', model: 'm' });
+ expect(res.error).toBeUndefined();
+ expect(res.content).toContain('Who I Am');
+ expect(res.tokenEstimate).toBeGreaterThan(0);
+ });
+
+ it('surfaces an unparseable response instead of passing it off as a bio', async () => {
+ getProviderById.mockResolvedValue({ id: 'x', enabled: true });
+ callProviderAI.mockResolvedValue({ text: 'Sorry, I cannot help with that.' });
+ const res = await polishAvatarBio({ providerId: 'x', model: 'm' });
+ expect(res.error).toMatch(/could not be parsed/i);
+ expect(res.rawResponse).toBeTruthy();
+ });
+});
diff --git a/server/services/digital-twin.js b/server/services/digital-twin.js
index 37ebd09570..db0fab4db6 100644
--- a/server/services/digital-twin.js
+++ b/server/services/digital-twin.js
@@ -87,6 +87,13 @@ export {
exportSoul
} from './digital-twin-export.js';
+export {
+ buildAvatarBio,
+ polishAvatarBio,
+ AVATAR_BIO_LENGTHS,
+ DEFAULT_AVATAR_BIO_LENGTH
+} from './digital-twin-avatar-bio.js';
+
export {
getDigitalTwinForPrompt,
getSoulForPrompt