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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-708]): add spoken-vs-written style comparison to Digital Twin
[._.]/ Adam Eivy20f24cc4d456
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.jsindex 04ee420938..c8b3912c71 100644--- a/client/src/components/digital-twin/constants.js+++ b/client/src/components/digital-twin/constants.js@@ -26,7 +26,8 @@ import {PenLine,Target,Archive,- Drama+ Drama,+ Mic} from 'lucide-react';// Main navigation tabs@@ -41,6 +42,7 @@ export const TABS = [{ id: 'personas', label: 'Personas', icon: Drama },{ id: 'goals', label: 'Goals', icon: Target },{ id: 'interview', label: 'Interview', icon: MessageSquare },+ { id: 'voice', label: 'Voice', icon: Mic },{ 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/VoiceStyleTab.jsx b/client/src/components/digital-twin/tabs/VoiceStyleTab.jsxnew file mode 100644index 0000000000..6f5883852f--- /dev/null+++ b/client/src/components/digital-twin/tabs/VoiceStyleTab.jsx@@ -0,0 +1,295 @@+import { useState } from 'react';+import {+ Mic,+ RefreshCw,+ GitCompareArrows,+ Check,+ AlertCircle+} from 'lucide-react';+import * as api from '../../../services/api';+import toast from '../../ui/Toast';+import useProviderModels from '../../../hooks/useProviderModels';+import ProviderModelSelector from '../../ProviderModelSelector';++const MIN_TRANSCRIPT = 100;++// Scale fields rendered as numbers; everything else is shown as free text.+const SCALE_FIELDS = [+ { key: 'formality', label: 'Formality', suffix: '/10' },+ { key: 'verbosity', label: 'Verbosity', suffix: '/10' },+ { key: 'directness', label: 'Directness', suffix: '/10' },+ { key: 'avgSentenceLength', label: 'Avg sentence', suffix: ' words' }+];++function ProfileCard({ title, profile, accent }) {+ if (!profile) return null;+ return (+ <div className="bg-port-bg rounded-lg border border-port-border p-4">+ <h4 className={`text-sm font-semibold mb-3 ${accent}`}>{title}</h4>+ <div className="grid grid-cols-2 gap-2 mb-3">+ {SCALE_FIELDS.map(({ key, label, suffix }) => (+ profile[key] != null && (+ <div key={key} className="flex items-baseline justify-between gap-2">+ <span className="text-xs text-gray-500">{label}</span>+ <span className="text-sm text-white font-medium">+ {profile[key]}{suffix}+ </span>+ </div>+ )+ ))}+ </div>+ {profile.fillerWords && (+ <p className="text-xs text-gray-400 mb-2">+ <span className="text-gray-500">Filler: </span>{profile.fillerWords}+ </p>+ )}+ {Array.isArray(profile.distinctiveMarkers) && profile.distinctiveMarkers.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {profile.distinctiveMarkers.map((m, i) => (+ <span key={i} className="text-xs px-2 py-0.5 rounded-full bg-port-border/60 text-gray-300">+ {m}+ </span>+ ))}+ </div>+ )}+ </div>+ );+}++export default function VoiceStyleTab({ onRefresh }) {+ const {+ providers, selectedProviderId, selectedModel, availableModels,+ setSelectedProviderId, setSelectedModel, loading: providersLoading+ } = useProviderModels();++ const [transcript, setTranscript] = useState('');+ const [written, setWritten] = useState('');+ const [comparing, setComparing] = useState(false);+ const [result, setResult] = useState(null);+ const [applying, setApplying] = useState(false);+ const [applied, setApplied] = useState(false);++ const handleCompare = async () => {+ if (transcript.trim().length < MIN_TRANSCRIPT) {+ toast.error(`Spoken transcript must be at least ${MIN_TRANSCRIPT} characters`);+ return;+ }+ if (!selectedProviderId || !selectedModel) {+ toast.error('Select a provider and model');+ return;+ }++ setComparing(true);+ setResult(null);+ setApplied(false);++ const payload = {+ spokenTranscript: transcript.trim(),+ providerId: selectedProviderId,+ model: selectedModel+ };+ // Only send written samples when the user pasted some; otherwise the+ // server falls back to the twin's documents.+ if (written.trim().length >= 10) {+ payload.writtenSamples = [written.trim()];+ }++ const res = await api.compareSpokenWrittenStyle(payload, { silent: true })+ .catch((err) => ({ error: err.message }));++ if (res.error) {+ toast.error(res.error);+ } else {+ setResult(res);+ toast.success('Style comparison complete');+ }+ setComparing(false);+ };++ const handleApply = async () => {+ const suggested = result?.suggestedCommunicationProfile;+ if (!suggested) return;++ setApplying(true);+ // Forward only the fields the communicationProfile schema accepts.+ const communicationProfile = {};+ ['formality', 'verbosity', 'emojiUsage', 'preferredTone'].forEach((k) => {+ if (suggested[k] != null) communicationProfile[k] = suggested[k];+ });++ const res = await api.updateDigitalTwinTraits({ communicationProfile }, { silent: true })+ .catch((err) => ({ error: err.message }));++ if (res?.error) {+ toast.error(res.error);+ } else {+ setApplied(true);+ toast.success('Applied to communication profile');+ onRefresh?.();+ }+ setApplying(false);+ };++ return (+ <div className="space-y-6 max-w-4xl mx-auto">+ {/* Inputs */}+ <div className="bg-port-card rounded-lg border border-port-border p-6">+ <div className="flex items-center gap-3 mb-4">+ <Mic className="w-6 h-6 text-port-accent" />+ <div>+ <h2 className="text-lg font-semibold text-white">Spoken vs. Written Style</h2>+ <p className="text-sm text-gray-400">+ Paste a transcript of yourself speaking and compare it against how you write.+ Surfaces the gap and suggests a voice-context communication profile.+ </p>+ </div>+ </div>++ <div className="space-y-4">+ {!providersLoading && providers.length > 0 && (+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={setSelectedProviderId}+ onModelChange={setSelectedModel}+ disabled={comparing}+ />+ )}++ <div>+ <label htmlFor="voice-transcript" className="block text-sm font-medium text-gray-300 mb-1">+ Spoken transcript+ </label>+ <textarea+ id="voice-transcript"+ value={transcript}+ onChange={(e) => setTranscript(e.target.value)}+ placeholder="Paste a transcript of yourself speaking — a voice memo transcription, a meeting/podcast transcript, dictated notes..."+ rows={7}+ className="w-full px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white resize-y focus:outline-hidden focus:border-port-accent placeholder-gray-600"+ disabled={comparing}+ />+ <span className="text-xs text-gray-500">+ {transcript.length} characters {transcript.length > 0 && transcript.length < MIN_TRANSCRIPT && `(need ${MIN_TRANSCRIPT}+)`}+ </span>+ </div>++ <div>+ <label htmlFor="voice-written" className="block text-sm font-medium text-gray-300 mb-1">+ Written sample <span className="text-gray-500 font-normal">(optional)</span>+ </label>+ <textarea+ id="voice-written"+ value={written}+ onChange={(e) => setWritten(e.target.value)}+ placeholder="Optionally paste a sample of your writing. Leave blank to compare against your existing Digital Twin documents."+ rows={5}+ className="w-full px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white resize-y focus:outline-hidden focus:border-port-accent placeholder-gray-600"+ disabled={comparing}+ />+ </div>++ <div className="flex justify-end">+ <button+ onClick={handleCompare}+ disabled={comparing || transcript.trim().length < MIN_TRANSCRIPT || !selectedProviderId}+ 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"+ >+ {comparing ? (+ <><RefreshCw size={18} className="animate-spin" /> Comparing...</>+ ) : (+ <><GitCompareArrows size={18} /> Compare</>+ )}+ </button>+ </div>+ </div>+ </div>++ {/* Results */}+ {result && (+ <div className="bg-port-card rounded-lg border border-green-500/30 p-6 space-y-5">+ <div className="flex items-center gap-3">+ <GitCompareArrows className="w-6 h-6 text-green-400" />+ <h2 className="text-lg font-semibold text-white">Comparison</h2>+ {result.writtenSource === 'documents' && (+ <span className="text-xs text-gray-500">(written style from your documents)</span>+ )}+ </div>++ {result.summary && (+ <p className="text-sm text-gray-300">{result.summary}</p>+ )}++ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <ProfileCard title="Spoken" profile={result.spokenProfile} accent="text-port-accent" />+ <ProfileCard title="Written" profile={result.writtenProfile} accent="text-pink-400" />+ </div>++ {result.differences.length > 0 && (+ <div>+ <h4 className="text-sm font-semibold text-white mb-2">Key differences</h4>+ <div className="space-y-2">+ {result.differences.map((d, i) => (+ <div key={i} className="bg-port-bg rounded-lg border border-port-border p-3">+ <div className="flex items-center justify-between gap-2 mb-1">+ <span className="text-sm font-medium text-white capitalize">+ {String(d.dimension || '').replace(/_/g, ' ')}+ </span>+ </div>+ <div className="grid grid-cols-2 gap-2 text-xs mb-1">+ <span className="text-gray-400"><span className="text-port-accent">Spoken:</span> {d.spoken}</span>+ <span className="text-gray-400"><span className="text-pink-400">Written:</span> {d.written}</span>+ </div>+ {d.note && <p className="text-xs text-gray-500">{d.note}</p>}+ </div>+ ))}+ </div>+ </div>+ )}++ {result.suggestedCommunicationProfile && (+ <div className="bg-port-bg rounded-lg border border-port-accent/30 p-4">+ <h4 className="text-sm font-semibold text-white mb-2">Suggested voice profile</h4>+ <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-gray-300 mb-3">+ {result.suggestedCommunicationProfile.formality != null && (+ <span><span className="text-gray-500">Formality:</span> {result.suggestedCommunicationProfile.formality}/10</span>+ )}+ {result.suggestedCommunicationProfile.verbosity != null && (+ <span><span className="text-gray-500">Verbosity:</span> {result.suggestedCommunicationProfile.verbosity}/10</span>+ )}+ {result.suggestedCommunicationProfile.emojiUsage && (+ <span><span className="text-gray-500">Emoji:</span> {result.suggestedCommunicationProfile.emojiUsage}</span>+ )}+ {result.suggestedCommunicationProfile.preferredTone && (+ <span><span className="text-gray-500">Tone:</span> {result.suggestedCommunicationProfile.preferredTone}</span>+ )}+ </div>+ <button+ onClick={handleApply}+ disabled={applying || applied}+ className="flex items-center gap-2 px-4 py-2 min-h-[44px] bg-port-accent text-white rounded-lg text-sm font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {applied ? (+ <><Check size={16} /> Applied</>+ ) : applying ? (+ <><RefreshCw size={16} className="animate-spin" /> Applying...</>+ ) : (+ 'Apply to communication profile'+ )}+ </button>+ </div>+ )}++ {result.rawResponse && !result.summary && (+ <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 structured data.+ </div>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex c184980569..ba4d47043a 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -16,6 +16,7 @@ import EnrichTab from '../components/digital-twin/tabs/EnrichTab';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 VoiceStyleTab from '../components/digital-twin/tabs/VoiceStyleTab';import IdentityTab from '../components/digital-twin/tabs/IdentityTab';import PersonasTab from '../components/digital-twin/tabs/PersonasTab';import GoalsTab from '../components/digital-twin/tabs/GoalsTab';@@ -72,6 +73,8 @@ export default function DigitalTwin() {return <GoalsTab onRefresh={refetch} />;case 'interview':return <InterviewTab onRefresh={refetch} />;+ case 'voice':+ return <VoiceStyleTab onRefresh={refetch} />;case 'autobiography':return <AutobiographyTab onRefresh={refetch} />;case 'import':diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.jsindex 221d266458..c0db814800 100644--- a/client/src/services/apiDigitalTwin.js+++ b/client/src/services/apiDigitalTwin.js@@ -112,6 +112,13 @@ export const analyzeWritingSamples = (samples, providerId, model) => request('/dmethod: 'POST',body: JSON.stringify({ samples, providerId, model })});+// Spoken-vs-written style comparison (M34 P5). writtenSamples is optional —+// omit it to compare the transcript against the twin's existing documents.+export const compareSpokenWrittenStyle = (payload, options = {}) => request('/digital-twin/style/spoken-written', {+ method: 'POST',+ body: JSON.stringify(payload),+ ...options+});// Digital Twin - List-based Enrichmentexport const analyzeEnrichmentList = (category, items, providerId, model) => request('/digital-twin/enrich/analyze-list', {@@ -130,9 +137,10 @@ export const analyzeDigitalTwinTraits = (providerId, model, forceReanalyze = falmethod: 'POST',body: JSON.stringify({ providerId, model, forceReanalyze })});-export const updateDigitalTwinTraits = (updates) => request('/digital-twin/traits', {+export const updateDigitalTwinTraits = (updates, options = {}) => request('/digital-twin/traits', {method: 'PUT',- body: JSON.stringify(updates)+ body: JSON.stringify(updates),+ ...options});export const getDigitalTwinConfidence = () => request('/digital-twin/confidence');export const calculateDigitalTwinConfidence = (providerId, model) => request('/digital-twin/confidence/calculate', {diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex d0e6589e70..f3bba3350a 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -221,6 +221,13 @@"returnsJson": true,"variables": []},+ "twin-spoken-written-compare": {+ "name": "Twin Spoken-vs-Written Comparison",+ "description": "Compare a person's spoken transcript against their writing samples and surface communication-style differences",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"pipeline-idea-expansion": {"name": "Pipeline — Idea / Beat Sheet","description": "Turn a rough seed idea for one issue or episode into a tight beat sheet with logline, theme, beats, setting, and any new characters. Spine for prose, comic script, TV script, and storyboard stages.",diff --git a/data.reference/prompts/stages/twin-spoken-written-compare.md b/data.reference/prompts/stages/twin-spoken-written-compare.mdnew file mode 100644index 0000000000..f4f7c7ab43--- /dev/null+++ b/data.reference/prompts/stages/twin-spoken-written-compare.md@@ -0,0 +1,32 @@+You are analyzing how a single person's communication style differs between SPEAKING and WRITING. You are given a transcript of them speaking and one or more samples of their writing. Compare the two and report concrete, evidence-based differences. Do not invent traits the text does not support — if the samples are too thin to judge a dimension, say so in the note rather than guessing.++Written sample(s):+"""+{{writtenSamples}}+"""++Spoken transcript:+"""+{{spokenTranscript}}+"""++For BOTH the spoken and the written style, estimate:+- formality: integer 1 (very casual) to 10 (very formal)+- verbosity: integer 1 (terse) to 10 (elaborate)+- avgSentenceLength: approximate words per sentence+- directness: integer 1 (hedged / indirect) to 10 (blunt / direct)+- fillerWords: a short note on filler and discourse markers ("um", "like", "you know", "I mean") — usually higher in speech+- distinctiveMarkers: up to 5 short phrases, idioms, or habits that recur++Then list the most significant DIFFERENCES between how they speak vs. how they write. For each difference, give the dimension, the spoken value or description, the written value or description, and a one-line note citing the evidence.++Finally, suggest a `communicationProfile` the person could adopt for SPOKEN / voice contexts (for example when their digital twin talks aloud or answers in voice mode), using the same 1-10 formality and verbosity scales, an emojiUsage of one of "never" | "rare" | "occasional" | "frequent", and a short preferredTone phrase.++Reply with JSON only, no prose outside the JSON:+{+ "spokenProfile": {"formality": <1-10>, "verbosity": <1-10>, "avgSentenceLength": <number>, "directness": <1-10>, "fillerWords": "<note>", "distinctiveMarkers": ["..."]},+ "writtenProfile": {"formality": <1-10>, "verbosity": <1-10>, "avgSentenceLength": <number>, "directness": <1-10>, "fillerWords": "<note>", "distinctiveMarkers": ["..."]},+ "differences": [{"dimension": "<name>", "spoken": "<value or description>", "written": "<value or description>", "note": "<evidence>"}],+ "summary": "<2-3 sentences on the overall spoken-vs-written gap>",+ "suggestedCommunicationProfile": {"formality": <1-10>, "verbosity": <1-10>, "emojiUsage": "never" | "rare" | "occasional" | "frequent", "preferredTone": "<short phrase>"}+}diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex e57c3484ba..cf955ce213 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -409,6 +409,16 @@ export const writingAnalysisInputSchema = z.object({model: z.string().min(1)});+// Spoken-vs-written style comparison input (M34 P5 — multi-modal capture).+// writtenSamples is optional: when omitted the service falls back to the+// user's enabled twin documents.+export const spokenWrittenStyleInputSchema = z.object({+ spokenTranscript: z.string().min(100).max(50000),+ writtenSamples: z.array(z.string().min(10).max(20000)).max(10).optional(),+ providerId: z.string().min(1),+ model: z.string().min(1)+});+// List-based enrichment itemexport const listItemSchema = z.object({title: z.string().min(1).max(500),diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex c6eb3e13a6..7e078ad7c4 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -116,6 +116,7 @@ export const NAV_COMMANDS = [{ id: 'nav.twin.taste', path: '/digital-twin/taste', label: 'Taste', section: 'Digital Twin', aliases: ['twin-taste'] },{ id: 'nav.twin.test', path: '/digital-twin/test', label: 'Test', section: 'Digital Twin', aliases: ['twin-test'] },{ id: 'nav.twin.time-capsule', path: '/digital-twin/time-capsule', label: 'Time Capsule', section: 'Digital Twin', aliases: ['time-capsule', 'twin-time-capsule', 'capsule'], keywords: ['legacy', 'archive', 'snapshot'] },+ { id: 'nav.twin.voice', path: '/digital-twin/voice', label: 'Voice', section: 'Digital Twin', aliases: ['twin-voice', 'voice-style', 'spoken-written'], keywords: ['speech', 'spoken', 'written', 'transcript', 'style', 'comparison', 'communication'] },{ id: 'nav.meatspace.overview', path: '/meatspace/overview', label: 'Overview', section: 'MeatSpace', aliases: ['meatspace'] },{ id: 'nav.meatspace.health', path: '/meatspace/health', label: 'Body Health', section: 'MeatSpace', aliases: ['meatspace-health', 'body-health'], keywords: ['health', 'vitals', 'wellbeing', 'biometrics'] },diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.jsindex f3931ce0f7..3bcefcc837 100644--- a/server/routes/digital-twin.js+++ b/server/routes/digital-twin.js@@ -28,6 +28,7 @@ import {contradictionInputSchema,generateTestsInputSchema,writingAnalysisInputSchema,+ spokenWrittenStyleInputSchema,analyzeListInputSchema,saveListDocumentInputSchema,getListItemsInputSchema,@@ -543,6 +544,17 @@ router.post('/analyze-writing', asyncHandler(async (req, res) => {res.json(result);}));+/**+ * POST /api/digital-twin/style/spoken-written+ * Compare the user's spoken style (a transcript) against their written style+ * (pasted samples, or their twin documents) and surface the differences.+ */+router.post('/style/spoken-written', asyncHandler(async (req, res) => {+ const data = validateRequest(spokenWrittenStyleInputSchema, req.body);+ const result = await digitalTwinService.compareSpokenWrittenStyle(data);+ res.json(result);+}));+// =============================================================================// TRAITS & CONFIDENCE (Phase 1 & 2)// =============================================================================diff --git a/server/services/digital-twin-style-comparison.js b/server/services/digital-twin-style-comparison.jsnew file mode 100644index 0000000000..7721046edc--- /dev/null+++ b/server/services/digital-twin-style-comparison.js@@ -0,0 +1,119 @@+/**+ * Digital Twin — Spoken-vs-Written Style Comparison (M34 P5)+ *+ * The first slice of "multi-modal personality capture": compare how the user+ * *speaks* (a pasted/transcribed transcript) against how they *write* (their+ * twin documents, or pasted writing samples) and surface the concrete style+ * differences — formality, verbosity, sentence length, directness, filler+ * words. Returns a suggested `communicationProfile` the user can adopt for+ * voice/spoken contexts.+ *+ * No live capture infra: speech arrives as text (a transcript the user pastes+ * or imports), so this needs no microphone, transcription service, or new+ * persistence. Self-contained — reuses the shared helpers and the existing+ * twin-document content loader only.+ */++import { getProviderById } from './providers.js';+import { buildPrompt } from './promptService.js';+import { safeJSONParse } from '../lib/fileUtils.js';+import { callProviderAI } from './digital-twin-helpers.js';+import { getAllTwinContent } from './digital-twin-analysis.js';++const MIN_TRANSCRIPT_CHARS = 100;++/**+ * Compare a spoken transcript against written samples and surface style deltas.+ *+ * @param {object} input+ * @param {string} input.spokenTranscript - transcript of the user speaking+ * @param {string[]} [input.writtenSamples] - written samples; when omitted,+ * falls back to the user's enabled twin documents+ * @param {string} input.providerId+ * @param {string} input.model+ */+export async function compareSpokenWrittenStyle({ spokenTranscript, writtenSamples, providerId, model }) {+ if (!spokenTranscript || spokenTranscript.trim().length < MIN_TRANSCRIPT_CHARS) {+ return { error: `Spoken transcript must be at least ${MIN_TRANSCRIPT_CHARS} characters` };+ }++ // Use provided written samples, otherwise fall back to the twin's documents+ // so the comparison works even when the user only pastes a transcript.+ let written = Array.isArray(writtenSamples)+ ? writtenSamples.filter(s => typeof s === 'string' && s.trim().length > 0)+ : [];+ let writtenSource = 'provided';++ if (written.length === 0) {+ const twinContent = await getAllTwinContent();+ if (!twinContent || twinContent.trim().length < MIN_TRANSCRIPT_CHARS) {+ return {+ error: 'No written samples provided and not enough twin document content to compare against. Paste a writing sample or add documents first.'+ };+ }+ written = [twinContent];+ writtenSource = 'documents';+ }++ const combinedWritten = written+ .map((s, i) => `--- Written Sample ${i + 1} ---\n${s}`)+ .join('\n\n');++ const prompt = await buildPrompt('twin-spoken-written-compare', {+ spokenTranscript: spokenTranscript.trim(),+ writtenSamples: combinedWritten+ }).catch(() => null);++ if (!prompt) {+ return { error: 'Spoken-vs-written comparison prompt template not found' };+ }++ const provider = await getProviderById(providerId);+ if (!provider || !provider.enabled) {+ return { error: 'Provider not found or disabled' };+ }++ const result = await callProviderAI(provider, model, prompt);+ if (result.error || !result.text) {+ return { error: result.error || 'Failed to analyze spoken-vs-written style' };+ }++ return { ...parseStyleComparison(result.text), writtenSource };+}++/**+ * Parse the LLM comparison response into a normalized shape. Tolerates a raw+ * JSON object or a ```json fenced block (same convention as the other twin+ * analyzers). Arrays default to [] and objects to null so the client can+ * distinguish "absent" from "present-but-empty".+ */+export function parseStyleComparison(response) {+ const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);+ const jsonStr = jsonMatch+ ? jsonMatch[1]+ : (response.trim().startsWith('{') ? response.trim() : null);++ if (!jsonStr) {+ return { error: 'Failed to parse comparison response - no JSON found', rawResponse: response };+ }++ const parsed = safeJSONParse(jsonStr, null, {+ allowArray: false,+ logError: true,+ context: 'spoken-written comparison'+ });++ if (!parsed) {+ return { error: 'Failed to parse comparison response - invalid JSON', rawResponse: response };+ }++ return {+ spokenProfile: parsed.spokenProfile && typeof parsed.spokenProfile === 'object' ? parsed.spokenProfile : null,+ writtenProfile: parsed.writtenProfile && typeof parsed.writtenProfile === 'object' ? parsed.writtenProfile : null,+ differences: Array.isArray(parsed.differences) ? parsed.differences : [],+ summary: typeof parsed.summary === 'string' ? parsed.summary : '',+ suggestedCommunicationProfile: parsed.suggestedCommunicationProfile && typeof parsed.suggestedCommunicationProfile === 'object'+ ? parsed.suggestedCommunicationProfile+ : null+ };+}diff --git a/server/services/digital-twin-style-comparison.test.js b/server/services/digital-twin-style-comparison.test.jsnew file mode 100644index 0000000000..bccd4430b9--- /dev/null+++ b/server/services/digital-twin-style-comparison.test.js@@ -0,0 +1,137 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Mocks — declared before importing the module under test. We mock only the+// LLM/provider/document deps; safeJSONParse (from fileUtils) runs for real so+// parseStyleComparison is exercised end-to-end.+vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));+vi.mock('./promptService.js', () => ({ buildPrompt: vi.fn() }));+vi.mock('./digital-twin-helpers.js', () => ({ callProviderAI: vi.fn() }));+vi.mock('./digital-twin-analysis.js', () => ({ getAllTwinContent: vi.fn() }));++import { compareSpokenWrittenStyle, parseStyleComparison } from './digital-twin-style-comparison.js';+import { getProviderById } from './providers.js';+import { buildPrompt } from './promptService.js';+import { callProviderAI } from './digital-twin-helpers.js';+import { getAllTwinContent } from './digital-twin-analysis.js';++const LONG_TRANSCRIPT = 'So, um, I was thinking about this, you know, the whole thing kind of just, like, came together. '.repeat(3);++const VALID_JSON = JSON.stringify({+ spokenProfile: { formality: 3, verbosity: 7, avgSentenceLength: 12, directness: 6, fillerWords: 'frequent um/like', distinctiveMarkers: ['you know'] },+ writtenProfile: { formality: 7, verbosity: 5, avgSentenceLength: 18, directness: 8, fillerWords: 'rare', distinctiveMarkers: ['—'] },+ differences: [{ dimension: 'formality', spoken: '3', written: '7', note: 'speech is looser' }],+ summary: 'You speak more casually than you write.',+ suggestedCommunicationProfile: { formality: 4, verbosity: 6, emojiUsage: 'rare', preferredTone: 'warm and direct' }+});++describe('parseStyleComparison', () => {+ it('parses a raw JSON object', () => {+ const r = parseStyleComparison(VALID_JSON);+ expect(r.error).toBeUndefined();+ expect(r.spokenProfile.formality).toBe(3);+ expect(r.writtenProfile.formality).toBe(7);+ expect(r.differences).toHaveLength(1);+ expect(r.summary).toContain('casually');+ expect(r.suggestedCommunicationProfile.preferredTone).toBe('warm and direct');+ });++ it('parses a ```json fenced block', () => {+ const r = parseStyleComparison('Here you go:\n```json\n' + VALID_JSON + '\n```\nDone.');+ expect(r.error).toBeUndefined();+ expect(r.spokenProfile.verbosity).toBe(7);+ });++ it('defaults arrays/objects so absent is distinguishable from empty', () => {+ const r = parseStyleComparison('{"summary":"only a summary"}');+ expect(r.error).toBeUndefined();+ expect(r.differences).toEqual([]);+ expect(r.spokenProfile).toBeNull();+ expect(r.suggestedCommunicationProfile).toBeNull();+ expect(r.summary).toBe('only a summary');+ });++ it('returns an error with rawResponse when no JSON is present', () => {+ const r = parseStyleComparison('I could not analyze that.');+ expect(r.error).toMatch(/no JSON found/);+ expect(r.rawResponse).toBe('I could not analyze that.');+ });++ it('returns an error with rawResponse on invalid JSON', () => {+ const r = parseStyleComparison('{ not valid json ');+ expect(r.error).toMatch(/invalid JSON|no JSON found/);+ });+});++describe('compareSpokenWrittenStyle', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getProviderById.mockResolvedValue({ id: 'p1', enabled: true });+ buildPrompt.mockResolvedValue('PROMPT');+ callProviderAI.mockResolvedValue({ text: VALID_JSON });+ getAllTwinContent.mockResolvedValue('A long body of the user written documents. '.repeat(5));+ });++ it('rejects a too-short transcript before calling the model', async () => {+ const r = await compareSpokenWrittenStyle({ spokenTranscript: 'too short', providerId: 'p1', model: 'm' });+ expect(r.error).toMatch(/at least 100/);+ expect(callProviderAI).not.toHaveBeenCalled();+ });++ it('uses provided written samples and reports writtenSource=provided', async () => {+ const r = await compareSpokenWrittenStyle({+ spokenTranscript: LONG_TRANSCRIPT,+ writtenSamples: ['Here is a sufficiently long written sample for the comparison.'],+ providerId: 'p1',+ model: 'm'+ });+ expect(r.writtenSource).toBe('provided');+ expect(getAllTwinContent).not.toHaveBeenCalled();+ expect(r.summary).toContain('casually');+ });++ it('falls back to twin documents when no written samples are provided', async () => {+ const r = await compareSpokenWrittenStyle({ spokenTranscript: LONG_TRANSCRIPT, providerId: 'p1', model: 'm' });+ expect(getAllTwinContent).toHaveBeenCalled();+ expect(r.writtenSource).toBe('documents');+ });++ it('errors when no written samples and document content is too thin', async () => {+ getAllTwinContent.mockResolvedValue('tiny');+ const r = await compareSpokenWrittenStyle({ spokenTranscript: LONG_TRANSCRIPT, providerId: 'p1', model: 'm' });+ expect(r.error).toMatch(/not enough twin document content/);+ expect(callProviderAI).not.toHaveBeenCalled();+ });++ it('errors when the prompt template is missing', async () => {+ buildPrompt.mockRejectedValue(new Error('Stage not found'));+ const r = await compareSpokenWrittenStyle({+ spokenTranscript: LONG_TRANSCRIPT,+ writtenSamples: ['A sufficiently long written sample to compare.'],+ providerId: 'p1',+ model: 'm'+ });+ expect(r.error).toMatch(/prompt template not found/);+ });++ it('errors when the provider is missing or disabled', async () => {+ getProviderById.mockResolvedValue(null);+ const r = await compareSpokenWrittenStyle({+ spokenTranscript: LONG_TRANSCRIPT,+ writtenSamples: ['A sufficiently long written sample to compare.'],+ providerId: 'p1',+ model: 'm'+ });+ expect(r.error).toMatch(/Provider not found/);+ });++ it('surfaces the provider error when the model call fails', async () => {+ callProviderAI.mockResolvedValue({ error: 'rate limited' });+ const r = await compareSpokenWrittenStyle({+ spokenTranscript: LONG_TRANSCRIPT,+ writtenSamples: ['A sufficiently long written sample to compare.'],+ providerId: 'p1',+ model: 'm'+ });+ expect(r.error).toBe('rate limited');+ });+});diff --git a/server/services/digital-twin.js b/server/services/digital-twin.jsindex f7d96d42e5..84752bb2e1 100644--- a/server/services/digital-twin.js+++ b/server/services/digital-twin.js@@ -110,6 +110,11 @@ export {getGapRecommendations} from './digital-twin-analysis.js';+export {+ compareSpokenWrittenStyle,+ parseStyleComparison+} from './digital-twin-style-comparison.js';+export {analyzeImportedData,saveImportAsDocument,