Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(digital-twin): add aesthetic taste questionnaire with conversational Q&A flow

Adam Eivy2916cc4a9084
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.md
index fa1496abec..8e1c051449 100644
--- a/.changelog/v0.12.x.md
+++ b/.changelog/v0.12.x.md
@@ -583,6 +583,27 @@ This release adds branch management and automated release workflow capabilities
## Fixes
+### Digital Twin — Aesthetic Taste Questionnaire
+- **New "Taste" tab**: Dedicated tab on the Digital Twin page for building an aesthetic taste profile through a conversational Q&A flow
+- **5 taste domains**: Movies & Film, Music & Sound, Visual Art & Design, Architecture & Spaces, Food & Culinary — each with 3 core questions and conditional follow-up questions
+- **Branching follow-ups**: When answers mention specific topics (e.g., "cinematography", "minimalist", "spice"), targeted follow-up questions automatically trigger to dig deeper into those preferences
+- **Per-section progress tracking**: Each section tracks core/follow-up question counts, completion status, and progress percentage
+- **Response review**: View all answers for any section, with follow-up questions labeled distinctly
+- **AI-powered summaries**: Generate per-section summaries or a unified taste profile using any configured AI provider — extracts core preferences, anti-preferences, key patterns, and representative quotes
+- **Profile persistence**: Responses stored in `data/digital-twin/taste-profile.json`, also appended to `AESTHETICS.md` for digital twin context injection
+- **Section reset**: Clear and re-answer any section without affecting others
+
+**Server changes**:
+- `server/services/taste-questionnaire.js` — New service with question definitions (5 sections × 3 core + follow-ups), branching logic, answer persistence, and AI summary generation
+- `server/routes/digital-twin.js` — 7 new endpoints under `/api/digital-twin/taste/*` (profile, sections, next question, answer, responses, summary, reset)
+- `server/lib/digitalTwinValidation.js` — Added `tasteSectionEnum`, `tasteAnswerInputSchema`, `tasteSummaryInputSchema`
+
+**Client changes**:
+- `client/src/components/digital-twin/tabs/TasteTab.jsx` — Full conversational Q&A UI with section grid, question flow, review mode, summary generation, and provider selection
+- `client/src/components/digital-twin/constants.js` — Added Taste tab with Palette icon
+- `client/src/pages/DigitalTwin.jsx` — Imported and rendered TasteTab
+- `client/src/services/api.js` — Added 7 taste questionnaire API functions
+
### Digital Twin — CLI Provider Support for All AI Functions
- **Unified provider dispatch**: Refactored 8 functions in `digital-twin.js` that had direct `fetch()` calls to `provider.endpoint` (API-only) to use the existing `callProviderAI()` helper which supports both API and CLI providers
- **Affected functions**: `runSingleTest`, `scoreTestResponse`, `generateEnrichmentQuestion`, `analyzeEnrichmentList`, `detectContradictions`, `generateDynamicTests`, `analyzeWritingSamples`, `extractTraits`, `calculateConfidence`, `analyzeWithPrompt`
diff --git a/PLAN.md b/PLAN.md
index 617760fc27..9d2f4f432c 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -73,6 +73,353 @@ pm2 logs
- [ ] **M7**: App Templates - Template management and app scaffolding from templates
- [ ] **M34 P3,P5-P7**: Digital Twin - Behavioral feedback loop, multi-modal capture, advanced testing, personas
- [ ] **M40**: Agent Skill System - Task-type-specific prompt templates with routing logic, negative examples, and embedded workflows for improved agent accuracy and reliability
+- [ ] **M42**: Unified Digital Twin Identity System - Connect Genome, Chronotype, Aesthetic Taste, and Mortality-Aware Goals into a single coherent Identity architecture
+
+---
+
+## M42: Unified Digital Twin Identity System
+
+### Motivation
+
+Four separate workstreams converge on the same vision: a personal digital twin that knows *who you are* biologically, temporally, aesthetically, and existentially. Today these live as disconnected features:
+
+| Subsystem | Current State | Location |
+|-----------|--------------|----------|
+| **Genome** | Fully implemented: 23andMe upload, 37+ curated SNP markers across 13 categories, ClinVar integration | `server/services/genome.js`, `GenomeTab.jsx`, `data/digital-twin/genome.json` |
+| **Chronotype** | Partially exists: 2 sleep markers (CLOCK rs1801260, DEC2 rs57875989) in genome + `daily_routines` enrichment category | `curatedGenomeMarkers.js` sleep category, `ENRICHMENT_CATEGORIES.daily_routines` |
+| **Aesthetic Taste** | Partially exists: `aesthetics` enrichment category + book/movie/music list-based enrichments | `ENRICHMENT_CATEGORIES.aesthetics`, `BOOKS.md`, `MOVIES.md`, `AUDIO.md` |
+| **Goal Tracking** | Partially exists: `COS-GOALS.md` for CoS missions, `TASKS.md` for user tasks, `EXISTENTIAL.md` soul doc | `data/COS-GOALS.md`, `data/TASKS.md`, `data/digital-twin/EXISTENTIAL.md` |
+
+These should be unified under a single **Identity** architecture so the twin can reason across all dimensions (e.g., "your CLOCK gene says evening chronotype — schedule deep work after 8pm" or "given your longevity markers and age, here's how to prioritize your 10-year goals").
+
+### Data Model
+
+#### Entity: `identity.json` (new, top-level twin orchestration)
+
+```json
+{
+ "version": "1.0.0",
+ "createdAt": "2026-02-12T00:00:00.000Z",
+ "updatedAt": "2026-02-12T00:00:00.000Z",
+ "sections": {
+ "genome": { "status": "active", "dataFile": "genome.json", "markerCount": 37, "lastScanAt": "..." },
+ "chronotype": { "status": "active", "dataFile": "chronotype.json", "derivedFrom": ["genome:sleep", "enrichment:daily_routines"] },
+ "aesthetics": { "status": "active", "dataFile": "aesthetics.json", "derivedFrom": ["enrichment:aesthetics", "enrichment:favorite_books", "enrichment:favorite_movies", "enrichment:music_taste"] },
+ "goals": { "status": "active", "dataFile": "goals.json" }
+ },
+ "crossLinks": []
+}
+```
+
+#### Entity: Chronotype Profile (`chronotype.json`)
+
+Derived from genome sleep markers + daily_routines enrichment answers + user overrides.
+
+```json
+{
+ "chronotype": "evening",
+ "confidence": 0.75,
+ "sources": {
+ "genetic": {
+ "clockGene": { "rsid": "rs1801260", "genotype": "T/C", "signal": "mild_evening" },
+ "dec2": { "rsid": "rs57875989", "genotype": "G/G", "signal": "standard_sleep_need" }
+ },
+ "behavioral": {
+ "preferredWakeTime": "08:30",
+ "preferredSleepTime": "00:30",
+ "peakFocusWindow": "20:00-02:00",
+ "energyDipWindow": "14:00-16:00"
+ }
+ },
+ "recommendations": {
+ "deepWork": "20:00-02:00",
+ "lightTasks": "09:00-12:00",
+ "exercise": "17:00-19:00",
+ "caffeineCutoff": "14:00"
+ },
+ "updatedAt": "2026-02-12T00:00:00.000Z"
+}
+```
+
+**Derivation logic**: Genome sleep markers provide the genetic baseline. The `daily_routines` enrichment answers provide behavioral confirmation. When genetic and behavioral signals agree, confidence is high. When they disagree, surface the conflict for user review. Caffeine cutoff cross-references caffeine metabolism markers (CYP1A2 rs762551, ADA rs73598374).
+
+#### Entity: Aesthetic Taste Profile (`aesthetics.json`)
+
+Consolidates scattered aesthetic data into a structured profile.
+
+```json
+{
+ "profile": {
+ "visualStyle": [],
+ "narrativePreferences": [],
+ "musicProfile": [],
+ "designPrinciples": [],
+ "antiPatterns": []
+ },
+ "sources": {
+ "enrichmentAnswers": { "aesthetics": "...", "questionsAnswered": 0 },
+ "bookAnalysis": { "themes": [], "sourceDoc": "BOOKS.md" },
+ "movieAnalysis": { "themes": [], "sourceDoc": "MOVIES.md" },
+ "musicAnalysis": { "themes": [], "sourceDoc": "AUDIO.md" }
+ },
+ "questionnaire": {
+ "completed": false,
+ "sections": [
+ "visual_design",
+ "color_and_mood",
+ "architecture_and_space",
+ "fashion_and_texture",
+ "sound_and_music",
+ "narrative_and_story",
+ "anti_preferences"
+ ]
+ },
+ "updatedAt": null
+}
+```
+
+**Derivation logic**: Taste is partially observable from existing enrichment data (book/movie/music lists). The aesthetic questionnaire fills in the rest via prompted sections — each section shows image/description pairs and asks for preference rankings. LLM analysis of existing media lists extracts themes (e.g., "brutalist minimalism", "high-contrast neon", "atmospheric dread") to seed the profile.
+
+#### Entity: Mortality-Aware Goals (`goals.json`)
+
+```json
+{
+ "birthDate": "1980-01-15",
+ "lifeExpectancyEstimate": {
+ "baseline": 78.5,
+ "adjusted": null,
+ "adjustmentFactors": {
+ "geneticLongevity": null,
+ "cardiovascularRisk": null,
+ "lifestyle": null
+ },
+ "source": "SSA actuarial table + genome markers"
+ },
+ "timeHorizons": {
+ "yearsRemaining": null,
+ "healthyYearsRemaining": null,
+ "percentLifeComplete": null
+ },
+ "goals": [
+ {
+ "id": "uuid",
+ "title": "...",
+ "description": "...",
+ "horizon": "5-year",
+ "category": "creative|family|health|financial|legacy|mastery",
+ "urgency": null,
+ "status": "active|completed|abandoned",
+ "milestones": [],
+ "createdAt": "...",
+ "updatedAt": "..."
+ }
+ ],
+ "updatedAt": null
+}
+```
+
+**Derivation logic**: Birth date + actuarial baseline + genome longevity/cardiovascular markers produce an adjusted life expectancy. This creates urgency scoring: a "legacy" goal with a 20-year timeline hits differently at 30% life-complete vs 70%. Goals are categorized and scored by time-decay urgency. The system can suggest reprioritization when markers indicate risk factors (e.g., high cardiovascular genetic risk → prioritize health goals).
+
+### Entity Relationships
+
+```
+ ┌──────────────────┐
+ │ identity.json │
+ │ (orchestrator) │
+ └──┬───┬───┬───┬──┘
+ │ │ │ │
+ ┌──────────┘ │ │ └──────────┐
+ ▼ ▼ ▼ ▼
+ ┌─────────┐ ┌──────────┐ ┌──────────┐ ┌─────────┐
+ │ Genome │ │Chronotype│ │Aesthetics│ │ Goals │
+ │genome.json│ │chrono.json│ │aesth.json│ │goals.json│
+ └────┬────┘ └────┬─────┘ └────┬─────┘ └────┬────┘
+ │ │ │ │
+ │ ┌─────────┘ │ │
+ │ │ derives from │ │
+ ├────┤ sleep markers │ │
+ │ │ │ │
+ │ │ caffeine cutoff ◄─────┤ │
+ │ │ from caffeine markers │ │
+ │ │ │ │
+ │ └───────────────────────┤ │
+ │ │ │
+ │ longevity/cardio ────────────────────► │
+ │ markers inform │ urgency │
+ │ life expectancy │ scoring │
+ │ │ │
+ │ ┌─────────────┘ │
+ │ │ derives from │
+ │ │ enrichment: aesthetics, │
+ │ │ books, movies, music │
+ │ │ │
+ └──────────────┴────────────────────────────┘
+ All reference meta.json
+ (documents, enrichment, traits)
+```
+
+**Cross-cutting links** (stored in `identity.json.crossLinks`):
+- `genome:sleep` → `chronotype:genetic` (CLOCK/DEC2 markers feed chronotype)
+- `genome:caffeine` → `chronotype:recommendations.caffeineCutoff` (CYP1A2/ADA markers set cutoff)
+- `genome:longevity` + `genome:cardiovascular` → `goals:lifeExpectancyEstimate` (risk-adjusted lifespan)
+- `enrichment:daily_routines` → `chronotype:behavioral` (self-reported schedule)
+- `enrichment:aesthetics` + `enrichment:favorite_*` + `enrichment:music_taste` → `aesthetics:profile` (taste extraction)
+- `traits:valuesHierarchy` → `goals:category` priority weighting (autonomy-valuing person weights mastery goals higher)
+
+### Identity Page Structure
+
+The existing Digital Twin page at `/digital-twin/:tab` gets a new **Identity** tab that serves as the unified view. Individual subsystem tabs (Genome, Enrich) remain for deep dives.
+
+#### Route: `/digital-twin/identity`
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ Digital Twin │
+│ Overview | Documents | ... | Identity | Genome | ... │
+├─────────────────────────────────────────────────────────────┤
+│ │
+│ ┌─ Identity Dashboard ──────────────────────────────────┐ │
+│ │ Completeness: ████████░░ 72% │ │
+│ │ 4 sections: Genome ✓ Chronotype ◐ Taste ○ Goals ○│ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │
+│ ┌─ Genome Summary Card ─────────────────────────────────┐ │
+│ │ 37 markers scanned across 13 categories │ │
+│ │ Key findings: 3 beneficial, 2 concern, 1 major │ │
+│ │ [View Full Genome →] │ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │
+│ ┌─ Chronotype Card ─────────────────────────────────────┐ │
+│ │ Type: Evening Owl (75% confidence) │ │
+│ │ Genetic: CLOCK T/C (mild evening) + DEC2 G/G │ │
+│ │ Peak focus: 8pm-2am | Caffeine cutoff: 2pm │ │
+│ │ [Configure Schedule →] │ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │
+│ ┌─ Aesthetic Taste Card ────────────────────────────────┐ │
+│ │ Status: Needs questionnaire (0/7 sections) │ │
+│ │ Detected themes from media: brutalist, atmospheric │ │
+│ │ [Start Taste Questionnaire →] │ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │
+│ ┌─ Life Goals Card ─────────────────────────────────────┐ │
+│ │ Status: Not configured │ │
+│ │ Set birth date and goals to enable mortality-aware │ │
+│ │ priority scoring │ │
+│ │ [Set Up Goals →] │ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │
+│ ┌─ Cross-Insights ──────────────────────────────────────┐ │
+│ │ "Your CLOCK gene evening tendency + caffeine │ │
+│ │ sensitivity suggest cutting coffee by 2pm" │ │
+│ │ "Longevity marker FOXO3A T/T (concern) + IL-6 C/C │ │
+│ │ (inflammation concern) — prioritize health goals" │ │
+│ └───────────────────────────────────────────────────────┘ │
+│ │
+└─────────────────────────────────────────────────────────────┘
+```
+
+#### Sub-routes for deep dives:
+- `/digital-twin/identity` — Dashboard overview (above)
+- `/digital-twin/identity/chronotype` — Full chronotype editor with schedule builder
+- `/digital-twin/identity/taste` — Aesthetic questionnaire flow (section-by-section)
+- `/digital-twin/identity/goals` — Goal CRUD with urgency visualization
+- `/digital-twin/genome` — Existing genome tab (unchanged)
+
+### Implementation Phases
+
+#### P1: Identity Orchestrator & Chronotype (data layer)
+- Create `data/digital-twin/identity.json` with section status tracking
+- Create `server/services/identity.js` — orchestrator that reads from genome, enrichment, and new data files
+- Create `data/digital-twin/chronotype.json` — derive from genome sleep markers + daily_routines enrichment
+- Add `GET /api/digital-twin/identity` route returning unified section status
+- Add `GET/PUT /api/digital-twin/identity/chronotype` routes
+- Derivation function: `deriveChronotypeFromGenome(genomeSummary)` extracts CLOCK + DEC2 status → chronotype signal
+
+#### P2: Aesthetic Taste Questionnaire ✅
+- Created `data/digital-twin/taste-profile.json` for structured taste preference storage
+- Created `server/services/taste-questionnaire.js` with 5 taste sections (movies, music, visual_art, architecture, food), each with core questions and branching follow-ups triggered by keyword detection
+- Added 7 API routes under `/api/digital-twin/taste/*` (profile, sections, next question, answer, responses, summary, reset)
+- Built `TasteTab.jsx` conversational Q&A UI with section grid, question flow, review mode, and AI-powered summary generation
+- Responses persisted to taste-profile.json and appended to AESTHETICS.md for digital twin context
+- Added Taste tab to Digital Twin page navigation
+
+#### P3: Mortality-Aware Goal Tracking
+- Create `data/digital-twin/goals.json`
+- Add `GET/POST/PUT/DELETE /api/digital-twin/identity/goals` routes
+- Birth date input + SSA actuarial table lookup
+- Genome-adjusted life expectancy: weight longevity markers (FOXO3A, IGF1R, CETP) and cardiovascular risk markers (Factor V, 9p21, Lp(a)) into adjustment factor
+- Time-horizon calculation: years remaining, healthy years, percent complete
+- Urgency scoring: `urgency = (goalHorizonYears - yearsRemaining) / goalHorizonYears` normalized
+- Goal CRUD with category tagging and milestone tracking
+
+#### P4: Identity Tab UI
+- Add `identity` tab to `TABS` constant in `constants.js`
+- Create `IdentityTab.jsx` with dashboard layout (4 summary cards + cross-insights)
+- Create `ChronotypeEditor.jsx` — schedule visualization and override controls
+- Create `TasteQuestionnaire.jsx` — section-by-section prompted flow
+- Create `GoalTracker.jsx` — goal list with urgency heatmap and timeline view
+- Wire sub-routes for deep dives
+
+#### P5: Cross-Insights Engine
+- Add `generateCrossInsights(identity)` in identity service
+- Cross-reference genome markers with chronotype, goals, and enrichment data
+- Generate natural-language insight strings (e.g., caffeine + chronotype, longevity + goal urgency)
+- Display on Identity dashboard and inject into CoS context when relevant
+- Consider autonomous job: periodic identity insight refresh
+
+### Data Flow
+
+```
+User uploads 23andMe → genome.json (existing)
+ ↓
+Identity service reads genome sleep markers + caffeine markers
+ ↓
+Derives chronotype.json (with behavioral input from enrichment)
+ ↓
+User sets birth date → goals.json (life expectancy from actuarial + genome)
+ ↓
+User completes taste questionnaire → aesthetics.json
+ ↓
+LLM analyzes books/movies/music → seeds aesthetic profile themes
+ ↓
+Cross-insights engine reads all 4 sections → generates natural-language insights
+ ↓
+Identity tab renders unified dashboard
+ ↓
+CoS injects identity context into agent briefings when relevant
+```
+
+### Files to Create/Modify
+
+**New files:**
+- `data/digital-twin/identity.json` — orchestrator metadata
+- `data/digital-twin/chronotype.json` — derived chronotype profile
+- `data/digital-twin/aesthetics.json` — taste profile
+- `data/digital-twin/goals.json` — mortality-aware goals
+- `server/services/identity.js` — identity orchestration service
+- `server/routes/identity.js` — API routes
+- `server/lib/identityValidation.js` — Zod schemas
+- `client/src/components/digital-twin/tabs/IdentityTab.jsx` — dashboard
+- `client/src/components/digital-twin/identity/ChronotypeEditor.jsx`
+- `client/src/components/digital-twin/identity/TasteQuestionnaire.jsx`
+- `client/src/components/digital-twin/identity/GoalTracker.jsx`
+- `client/src/components/digital-twin/identity/CrossInsights.jsx`
+
+**Modified files:**
+- `client/src/components/digital-twin/constants.js` — add Identity tab
+- `client/src/pages/DigitalTwin.jsx` — add Identity tab rendering
+- `client/src/services/api.js` — add identity API methods
+- `server/index.js` — mount identity routes
+
+### Design Decisions
+
+1. **Separate data files per section** (not one giant file) — each section has independent update cadence and the genome file is already large
+2. **Derivation over duplication** — chronotype reads from genome.json at query time rather than copying marker data. Identity service is the join layer
+3. **Progressive disclosure** — Identity tab shows summary cards; deep dives are sub-routes, not modals (per CLAUDE.md: all views must be deep-linkable)
+4. **LLM-assisted but user-confirmed** — aesthetic themes extracted by LLM from media lists are suggestions, not gospel. User confirms/edits
+5. **No new dependencies** — uses existing Zod, Express, React, Lucide stack
+6. **Genome data stays read-only** — identity service reads genome markers but never writes to genome.json
---
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.js
index a3401897c6..12be456a83 100644
--- a/client/src/components/digital-twin/constants.js
+++ b/client/src/components/digital-twin/constants.js
@@ -33,6 +33,7 @@ export const TABS = [
{ id: 'documents', label: 'Documents', icon: FileText },
{ id: 'test', label: 'Test', icon: CheckCircle },
{ id: 'enrich', label: 'Enrich', icon: Sparkles },
+ { id: 'taste', label: 'Taste', icon: Palette },
{ id: 'accounts', label: 'Accounts', icon: Globe },
{ id: 'genome', label: 'Genome', icon: Dna },
{ id: 'interview', label: 'Interview', icon: MessageSquare },
diff --git a/client/src/components/digital-twin/tabs/TasteTab.jsx b/client/src/components/digital-twin/tabs/TasteTab.jsx
new file mode 100644
index 0000000000..bf055ef28e
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/TasteTab.jsx
@@ -0,0 +1,625 @@
+import { useState, useEffect, useCallback } from 'react';
+import {
+ Palette,
+ Film,
+ Music,
+ Building,
+ UtensilsCrossed,
+ ChevronRight,
+ ArrowLeft,
+ Send,
+ SkipForward,
+ RefreshCw,
+ Check,
+ Sparkles,
+ RotateCcw,
+ Eye,
+ ChevronDown,
+ ChevronUp
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from 'react-hot-toast';
+
+const SECTION_ICONS = {
+ movies: Film,
+ music: Music,
+ visual_art: Palette,
+ architecture: Building,
+ food: UtensilsCrossed
+};
+
+const SECTION_COLORS = {
+ movies: 'red',
+ music: 'green',
+ visual_art: 'violet',
+ architecture: 'amber',
+ food: 'orange'
+};
+
+export default function TasteTab({ onRefresh }) {
+ const [profile, setProfile] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ // Active session state
+ const [activeSection, setActiveSection] = useState(null);
+ const [currentQuestion, setCurrentQuestion] = useState(null);
+ const [answer, setAnswer] = useState('');
+ const [submitting, setSubmitting] = useState(false);
+ const [loadingQuestion, setLoadingQuestion] = useState(false);
+
+ // Summary generation
+ const [generatingSummary, setGeneratingSummary] = useState(false);
+ const [providers, setProviders] = useState([]);
+ const [selectedProvider, setSelectedProvider] = useState(null);
+
+ // Review mode
+ const [reviewSection, setReviewSection] = useState(null);
+ const [reviewResponses, setReviewResponses] = useState([]);
+ const [loadingReview, setLoadingReview] = useState(false);
+
+ // Expanded summaries
+ const [expandedSummary, setExpandedSummary] = useState(null);
+
+ const loadProfile = useCallback(async () => {
+ const data = await api.getTasteProfile().catch(() => null);
+ if (data) setProfile(data);
+ setLoading(false);
+ }, []);
+
+ const loadProviders = useCallback(async () => {
+ const data = await api.getProviders().catch(() => ({ providers: [] }));
+ const enabled = (data.providers || []).filter(p => p.enabled);
+ setProviders(enabled);
+ if (enabled.length > 0) {
+ setSelectedProvider({ providerId: enabled[0].id, model: enabled[0].defaultModel });
+ }
+ }, []);
+
+ useEffect(() => {
+ loadProfile();
+ loadProviders();
+ }, [loadProfile, loadProviders]);
+
+ const startSection = async (sectionId) => {
+ setActiveSection(sectionId);
+ setLoadingQuestion(true);
+ const question = await api.getTasteNextQuestion(sectionId).catch(() => null);
+ setCurrentQuestion(question);
+ setAnswer('');
+ setLoadingQuestion(false);
+ };
+
+ const submitAnswer = async () => {
+ if (!answer.trim() || !currentQuestion) return;
+
+ setSubmitting(true);
+ const result = await api.submitTasteAnswer(
+ activeSection,
+ currentQuestion.questionId,
+ answer.trim()
+ ).catch(() => null);
+
+ if (!result) {
+ toast.error('Failed to save response');
+ setSubmitting(false);
+ return;
+ }
+
+ toast.success('Response saved');
+ setAnswer('');
+
+ // Use the next question returned inline from the submit response
+ if (result.nextQuestion) {
+ setCurrentQuestion(result.nextQuestion);
+ } else {
+ setCurrentQuestion(null);
+ }
+
+ await loadProfile();
+ setSubmitting(false);
+ onRefresh?.();
+ };
+
+ const exitSection = () => {
+ setActiveSection(null);
+ setCurrentQuestion(null);
+ setAnswer('');
+ setReviewSection(null);
+ setReviewResponses([]);
+ };
+
+ const handleReviewSection = async (sectionId) => {
+ setReviewSection(sectionId);
+ setLoadingReview(true);
+ const responses = await api.getTasteSectionResponses(sectionId).catch(() => []);
+ setReviewResponses(responses);
+ setLoadingReview(false);
+ };
+
+ const handleResetSection = async (sectionId) => {
+ await api.resetTasteSection(sectionId).catch(() => null);
+ toast.success('Section reset');
+ await loadProfile();
+ setReviewSection(null);
+ setReviewResponses([]);
+ onRefresh?.();
+ };
+
+ const handleGenerateSummary = async (sectionId) => {
+ if (!selectedProvider) {
+ toast.error('Select a provider first');
+ return;
+ }
+ setGeneratingSummary(true);
+ const result = await api.generateTasteSummary(
+ selectedProvider.providerId,
+ selectedProvider.model,
+ sectionId
+ ).catch(e => ({ error: e.message }));
+
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ toast.success('Summary generated');
+ await loadProfile();
+ }
+ setGeneratingSummary(false);
+ };
+
+ const handleGenerateOverallSummary = async () => {
+ if (!selectedProvider) {
+ toast.error('Select a provider first');
+ return;
+ }
+ setGeneratingSummary(true);
+ const result = await api.generateTasteSummary(
+ selectedProvider.providerId,
+ selectedProvider.model
+ ).catch(e => ({ error: e.message }));
+
+ if (result.error) {
+ toast.error(result.error);
+ } else {
+ toast.success('Taste profile generated');
+ await loadProfile();
+ }
+ setGeneratingSummary(false);
+ onRefresh?.();
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <RefreshCw className="w-8 h-8 text-port-accent animate-spin" />
+ </div>
+ );
+ }
+
+ // Review mode — show previous responses
+ if (reviewSection) {
+ const section = profile?.sections?.find(s => s.id === reviewSection);
+ const Icon = SECTION_ICONS[reviewSection] || Palette;
+ const color = SECTION_COLORS[reviewSection] || 'blue';
+
+ return (
+ <div className="max-w-2xl mx-auto px-1">
+ <div className="mb-6">
+ <button
+ onClick={() => { setReviewSection(null); setReviewResponses([]); }}
+ className="flex items-center gap-2 text-gray-400 hover:text-white mb-4 py-2 min-h-[44px]"
+ >
+ <ArrowLeft size={18} />
+ Back to sections
+ </button>
+ <div className="flex items-center gap-3">
+ <div className={`p-2.5 rounded-lg bg-${color}-500/20`}>
+ <Icon className={`w-5 h-5 text-${color}-400`} />
+ </div>
+ <div>
+ <h2 className="text-xl font-semibold text-white">{section?.label} — Responses</h2>
+ <p className="text-sm text-gray-400">{reviewResponses.length} responses recorded</p>
+ </div>
+ </div>
+ </div>
+
+ {loadingReview ? (
+ <div className="flex items-center justify-center h-48">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ ) : (
+ <div className="space-y-4">
+ {reviewResponses.map((r, i) => (
+ <div key={i} className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex items-start gap-2 mb-2">
+ {r.isFollowUp && (
+ <span className="text-xs px-2 py-0.5 bg-port-accent/20 text-port-accent rounded">follow-up</span>
+ )}
+ <p className="text-sm text-gray-400">{r.questionText}</p>
+ </div>
+ <p className="text-white whitespace-pre-wrap">{r.answer}</p>
+ </div>
+ ))}
+
+ {section?.summary && (
+ <div className="bg-port-card rounded-lg border border-violet-500/30 p-4">
+ <h3 className="text-sm font-medium text-violet-400 mb-2 flex items-center gap-2">
+ <Sparkles size={14} />
+ AI Summary
+ </h3>
+ <div className="text-gray-300 text-sm whitespace-pre-wrap">{section.summary}</div>
+ </div>
+ )}
+
+ <div className="flex flex-col sm:flex-row gap-3 pt-2">
+ <button
+ onClick={() => handleGenerateSummary(reviewSection)}
+ disabled={generatingSummary || reviewResponses.length === 0}
+ className="flex items-center justify-center gap-2 px-4 py-3 min-h-[44px] bg-violet-600 text-white rounded-lg text-sm hover:bg-violet-500 disabled:opacity-50"
+ >
+ {generatingSummary ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Sparkles size={16} />}
+ {section?.summary ? 'Regenerate Summary' : 'Generate Summary'}
+ </button>
+ <button
+ onClick={() => handleResetSection(reviewSection)}
+ className="flex items-center justify-center gap-2 px-4 py-3 min-h-[44px] text-red-400 border border-red-500/30 rounded-lg text-sm hover:bg-red-500/10"
+ >
+ <RotateCcw size={16} />
+ Reset Section
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ // Active Q&A session
+ if (activeSection) {
+ const section = profile?.sections?.find(s => s.id === activeSection);
+ const Icon = SECTION_ICONS[activeSection] || Palette;
+ const color = SECTION_COLORS[activeSection] || 'blue';
+
+ // Section complete
+ if (!currentQuestion && !loadingQuestion) {
+ return (
+ <div className="max-w-2xl mx-auto px-1">
+ <div className="mb-6">
+ <button
+ onClick={exitSection}
+ className="flex items-center gap-2 text-gray-400 hover:text-white mb-4 py-2 min-h-[44px]"
+ >
+ <ArrowLeft size={18} />
+ Back to sections
+ </button>
+ <div className="flex items-center gap-3">
+ <div className={`p-2.5 rounded-lg bg-${color}-500/20`}>
+ <Icon className={`w-5 h-5 text-${color}-400`} />
+ </div>
+ <h2 className="text-xl font-semibold text-white">{section?.label}</h2>
+ </div>
+ </div>
+ <div className="p-4 bg-green-500/10 border border-green-500/30 rounded-lg mb-4">
+ <div className="flex items-center gap-3">
+ <Check className="w-5 h-5 text-green-400" />
+ <span className="text-green-400">All questions for this section are complete.</span>
+ </div>
+ </div>
+ <div className="flex flex-col sm:flex-row gap-3">
+ <button
+ onClick={() => handleReviewSection(activeSection)}
+ className="flex items-center justify-center gap-2 px-4 py-3 min-h-[44px] bg-port-card border border-port-border text-white rounded-lg text-sm hover:border-port-accent"
+ >
+ <Eye size={16} />
+ Review Responses
+ </button>
+ <button
+ onClick={() => handleGenerateSummary(activeSection)}
+ disabled={generatingSummary}
+ className="flex items-center justify-center gap-2 px-4 py-3 min-h-[44px] bg-violet-600 text-white rounded-lg text-sm hover:bg-violet-500 disabled:opacity-50"
+ >
+ {generatingSummary ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Sparkles size={16} />}
+ Generate Summary
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ // Active question
+ return (
+ <div className="max-w-2xl mx-auto px-1">
+ <div className="mb-6 sm:mb-8">
+ <button
+ onClick={exitSection}
+ className="flex items-center gap-2 text-gray-400 hover:text-white mb-4 py-2 min-h-[44px]"
+ >
+ <ArrowLeft size={18} />
+ Back to sections
+ </button>
+
+ <div className="flex items-center gap-3 sm:gap-4">
+ <div className={`p-2.5 sm:p-3 rounded-lg bg-${color}-500/20 flex-shrink-0`}>
+ <Icon className={`w-5 h-5 sm:w-6 sm:h-6 text-${color}-400`} />
+ </div>
+ <div className="min-w-0">
+ <h2 className="text-lg sm:text-xl font-bold text-white">{section?.label}</h2>
+ <p className="text-sm sm:text-base text-gray-400 truncate">{section?.description}</p>
+ </div>
+ </div>
+
+ {/* Progress bar */}
+ <div className="mt-4">
+ <div className="flex items-center justify-between text-sm mb-1">
+ <span className="text-gray-400">
+ {currentQuestion?.isFollowUp ? 'Follow-up question' : `Question ${currentQuestion?.progress?.current || 1} of ${currentQuestion?.progress?.coreTotal || '?'}`}
+ </span>
+ <span className="text-gray-400">{section?.progress?.percentage || 0}% core complete</span>
+ </div>
+ <div className="h-2 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-port-accent transition-all"
+ style={{ width: `${section?.progress?.percentage || 0}%` }}
+ />
+ </div>
+ </div>
+ </div>
+
+ {loadingQuestion ? (
+ <div className="flex items-center justify-center h-48">
+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />
+ </div>
+ ) : (
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <div className="mb-6">
+ <span className="text-xs text-gray-500 uppercase tracking-wider">
+ {currentQuestion?.isFollowUp ? 'Follow-up — based on your previous answer' : 'Core Question'}
+ </span>
+ <h3 className="text-xl text-white mt-2">{currentQuestion?.text}</h3>
+ </div>
+
+ <div className="mb-6">
+ <textarea
+ value={answer}
+ onChange={(e) => setAnswer(e.target.value)}
+ placeholder="Share your thoughts... be as specific as possible."
+ rows={6}
+ className="w-full px-4 py-3 bg-port-bg border border-port-border rounded-lg text-white resize-none focus:outline-none focus:border-port-accent"
+ autoFocus
+ />
+ <div className="text-xs text-gray-500 mt-2">
+ The more specific you are, the better your taste profile will be. Reference specific examples, feelings, and reasons.
+ </div>
+ </div>
+
+ <div className="flex flex-col-reverse sm:flex-row items-stretch sm:items-center justify-between gap-3">
+ <button
+ onClick={() => {
+ // Skip current question by submitting empty — move to next
+ setAnswer('');
+ setLoadingQuestion(true);
+ api.getTasteNextQuestion(activeSection).then(q => {
+ // If same question returned (can't skip core), just clear loading
+ if (q?.questionId === currentQuestion?.questionId) {
+ toast('Core questions cannot be skipped', { icon: '⚠️' });
+ } else {
+ setCurrentQuestion(q);
+ }
+ setLoadingQuestion(false);
+ }).catch(() => setLoadingQuestion(false));
+ }}
+ disabled={!currentQuestion?.isFollowUp}
+ className="flex items-center justify-center gap-2 px-4 py-3 min-h-[44px] text-gray-400 hover:text-white transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
+ >
+ <SkipForward size={18} />
+ Skip
+ </button>
+
+ <button
+ onClick={submitAnswer}
+ disabled={submitting || !answer.trim()}
+ className="flex items-center justify-center gap-2 px-6 py-3 min-h-[48px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {submitting ? (
+ <>
+ <RefreshCw className="w-5 h-5 animate-spin" />
+ Saving...
+ </>
+ ) : (
+ <>
+ <Send size={18} />
+ Submit
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ // Section selection view
+ return (
+ <div className="space-y-6">
+ {/* Overall Progress */}
+ <div className="bg-port-card rounded-lg border border-port-border p-6">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-3">
+ <Palette className="w-6 h-6 text-violet-400" />
+ <h2 className="text-lg font-semibold text-white">Aesthetic Taste Profile</h2>
+ </div>
+ <span className="text-gray-400">
+ {profile?.completedCount || 0}/{profile?.totalSections || 5} sections complete
+ </span>
+ </div>
+
+ <div className="h-3 bg-port-border rounded-full overflow-hidden">
+ <div
+ className="h-full bg-gradient-to-r from-violet-500 to-pink-500 transition-all"
+ style={{ width: `${profile?.overallPercentage || 0}%` }}
+ />
+ </div>
+
+ {profile?.lastSessionAt && (
+ <p className="text-sm text-gray-500 mt-3">
+ Last session: {new Date(profile.lastSessionAt).toLocaleDateString()}
+ </p>
+ )}
+ </div>
+
+ {/* Section Grid */}
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
+ {(profile?.sections || []).map((section) => {
+ const Icon = SECTION_ICONS[section.id] || Palette;
+ const color = SECTION_COLORS[section.id] || 'blue';
+ const isComplete = section.status === 'completed';
+ const isStarted = section.status === 'in_progress';
+
+ return (
+ <div
+ key={section.id}
+ className={`bg-port-card rounded-lg border transition-all ${
+ isComplete ? 'border-green-500/30' : isStarted ? 'border-port-accent/30' : 'border-port-border'
+ }`}
+ >
+ <button
+ onClick={() => startSection(section.id)}
+ className="w-full p-4 min-h-[120px] text-left hover:bg-port-border/20 rounded-t-lg transition-colors"
+ >
+ <div className="flex items-start justify-between mb-3">
+ <div className={`p-2 rounded-lg bg-${color}-500/20`}>
+ <Icon className={`w-5 h-5 text-${color}-400`} />
+ </div>
+ {isComplete ? (
+ <Check className="w-5 h-5 text-green-400" />
+ ) : (
+ <ChevronRight className="w-5 h-5 text-gray-500" />
+ )}
+ </div>
+
+ <h3 className="font-semibold text-white mb-1">{section.label}</h3>
+ <p className="text-sm text-gray-400 mb-3 line-clamp-2">{section.description}</p>
+
+ <div className="flex items-center justify-between text-xs">
+ <span className="text-gray-500">
+ {section.progress?.coreAnswered || 0}/{section.progress?.coreTotal || 0} core
+ {section.progress?.followUpsAnswered > 0 && ` + ${section.progress.followUpsAnswered} follow-ups`}
+ </span>
+ <span className={isComplete ? 'text-green-400' : 'text-gray-500'}>
+ {section.progress?.percentage || 0}%
+ </span>
+ </div>
+
+ {/* Mini progress bar */}
+ <div className="h-1 bg-port-border rounded-full mt-2 overflow-hidden">
+ <div
+ className={`h-full transition-all ${isComplete ? 'bg-green-500' : 'bg-port-accent'}`}
+ style={{ width: `${section.progress?.percentage || 0}%` }}
+ />
+ </div>
+ </button>
+
+ {/* Review button for sections with responses */}
+ {(section.progress?.coreAnswered > 0 || section.progress?.followUpsAnswered > 0) && (
+ <div className="px-4 pb-3 flex gap-2">
+ <button
+ onClick={() => handleReviewSection(section.id)}
+ className="text-xs text-gray-400 hover:text-white flex items-center gap-1 py-1"
+ >
+ <Eye size={12} />
+ Review
+ </button>
+ </div>
+ )}
+
+ {/* Expandable summary */}
+ {section.summary && (
+ <div className="px-4 pb-3">
+ <button
+ onClick={() => setExpandedSummary(expandedSummary === section.id ? null : section.id)}
+ className="text-xs text-violet-400 hover:text-violet-300 flex items-center gap-1 py-1"
+ >
+ <Sparkles size={12} />
+ Summary
+ {expandedSummary === section.id ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
+ </button>
+ {expandedSummary === section.id && (
+ <div className="mt-2 p-3 bg-port-bg rounded-lg text-xs text-gray-300 whitespace-pre-wrap max-h-48 overflow-auto">
+ {section.summary}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {/* Overall Summary */}
+ {profile?.profileSummary && (
+ <div className="bg-port-card rounded-lg border border-violet-500/30 p-6">
+ <h3 className="text-lg font-semibold text-white mb-3 flex items-center gap-2">
+ <Sparkles className="w-5 h-5 text-violet-400" />
+ Unified Taste Profile
+ </h3>
+ <div className="text-gray-300 text-sm whitespace-pre-wrap">{profile.profileSummary}</div>
+ </div>
+ )}
+
+ {/* Generate Summary / Provider Selection */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex flex-col sm:flex-row items-start sm:items-center gap-4">
+ <div className="flex-1">
+ <h3 className="font-medium text-white mb-1">Generate Taste Profile</h3>
+ <p className="text-sm text-gray-400">
+ Use AI to analyze your responses and build a unified aesthetic taste profile.
+ </p>
+ </div>
+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 w-full sm:w-auto">
+ <select
+ value={selectedProvider ? `${selectedProvider.providerId}:${selectedProvider.model}` : ''}
+ onChange={(e) => {
+ const [providerId, model] = e.target.value.split(':');
+ setSelectedProvider({ providerId, model });
+ }}
+ className="px-3 py-3 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-white text-sm"
+ >
+ {providers.map(p => (
+ (p.models || [p.defaultModel]).filter(Boolean).map(model => (
+ <option key={`${p.id}:${model}`} value={`${p.id}:${model}`}>
+ {p.name} - {model}
+ </option>
+ ))
+ ))}
+ </select>
+ <button
+ onClick={handleGenerateOverallSummary}
+ disabled={generatingSummary || (profile?.completedCount || 0) === 0}
+ className="flex items-center justify-center gap-2 px-4 py-3 min-h-[44px] bg-violet-600 text-white rounded-lg text-sm hover:bg-violet-500 disabled:opacity-50 whitespace-nowrap"
+ >
+ {generatingSummary ? <RefreshCw className="w-4 h-4 animate-spin" /> : <Sparkles size={16} />}
+ {profile?.profileSummary ? 'Regenerate' : 'Generate Profile'}
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {/* Info */}
+ <div className="bg-port-card rounded-lg border border-port-border p-4">
+ <div className="flex items-start gap-4">
+ <Palette className="w-6 h-6 text-violet-400 flex-shrink-0" />
+ <div>
+ <h3 className="font-medium text-white mb-1">How the Taste Questionnaire Works</h3>
+ <p className="text-sm text-gray-400">
+ Each section explores a different domain of aesthetic taste through a conversational Q&A flow.
+ Core questions establish your baseline preferences. Based on your answers, follow-up questions
+ dig deeper into specific areas — if you mention visual elements in your movie preferences,
+ you'll get questions about cinematography style. After completing sections, generate an
+ AI-powered taste profile that captures your aesthetic identity across all domains.
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index e19d5351ef..a120dfae51 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -9,6 +9,7 @@ import OverviewTab from '../components/digital-twin/tabs/OverviewTab';
import DocumentsTab from '../components/digital-twin/tabs/DocumentsTab';
import TestTab from '../components/digital-twin/tabs/TestTab';
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 GenomeTab from '../components/digital-twin/tabs/GenomeTab';
@@ -54,6 +55,8 @@ export default function DigitalTwin() {
return <TestTab onRefresh={fetchData} />;
case 'enrich':
return <EnrichTab onRefresh={fetchData} />;
+ case 'taste':
+ return <TasteTab onRefresh={fetchData} />;
case 'accounts':
return <AccountsTab />;
case 'genome':
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 0a0c6069d2..0b572d4f04 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -950,6 +950,23 @@ export const saveDigitalTwinImport = (source, suggestedDoc) => request('/digital
body: JSON.stringify({ source, suggestedDoc })
});
+// Digital Twin - Taste Questionnaire
+export const getTasteProfile = () => request('/digital-twin/taste');
+export const getTasteSections = () => request('/digital-twin/taste/sections');
+export const getTasteNextQuestion = (section) => request(`/digital-twin/taste/${section}/next`);
+export const submitTasteAnswer = (section, questionId, answer) => request('/digital-twin/taste/answer', {
+ method: 'POST',
+ body: JSON.stringify({ section, questionId, answer })
+});
+export const getTasteSectionResponses = (section) => request(`/digital-twin/taste/${section}/responses`);
+export const generateTasteSummary = (providerId, model, section) => request('/digital-twin/taste/summary', {
+ method: 'POST',
+ body: JSON.stringify({ providerId, model, ...(section ? { section } : {}) })
+});
+export const resetTasteSection = (section) => request(`/digital-twin/taste/${section}`, {
+ method: 'DELETE'
+});
+
// Digital Twin - Assessment Analyzer
export const analyzeAssessment = (content, providerId, model) =>
request('/digital-twin/interview/analyze', {
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index f883de5897..187dead62d 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -399,3 +399,21 @@ export const importAnalysisResultSchema = z.object({
})).optional(),
rawSummary: z.string().optional()
});
+
+// --- Taste Questionnaire Schemas ---
+
+export const tasteSectionEnum = z.enum([
+ 'movies', 'music', 'visual_art', 'architecture', 'food'
+]);
+
+export const tasteAnswerInputSchema = z.object({
+ section: tasteSectionEnum,
+ questionId: z.string().min(1),
+ answer: z.string().min(1).max(10000)
+});
+
+export const tasteSummaryInputSchema = z.object({
+ section: tasteSectionEnum.optional(),
+ providerId: z.string().min(1),
+ model: z.string().min(1)
+});
diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.js
index 69b485a02f..851dd84336 100644
--- a/server/routes/digital-twin.js
+++ b/server/routes/digital-twin.js
@@ -11,6 +11,7 @@
import { Router } from 'express';
import * as digitalTwinService from '../services/digital-twin.js';
+import * as tasteService from '../services/taste-questionnaire.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validate } from '../lib/validation.js';
import {
@@ -33,7 +34,10 @@ import {
updateTraitsInputSchema,
calculateConfidenceInputSchema,
importDataInputSchema,
- analyzeAssessmentInputSchema
+ analyzeAssessmentInputSchema,
+ tasteAnswerInputSchema,
+ tasteSummaryInputSchema,
+ tasteSectionEnum
} from '../lib/digitalTwinValidation.js';
const router = Router();
@@ -639,4 +643,121 @@ router.post('/import/save', asyncHandler(async (req, res) => {
res.json({ document, message: 'Document saved successfully' });
}));
+// =============================================================================
+// TASTE QUESTIONNAIRE
+// =============================================================================
+
+/**
+ * GET /api/digital-twin/taste
+ * Get taste profile status and progress
+ */
+router.get('/taste', asyncHandler(async (req, res) => {
+ const profile = await tasteService.getTasteProfile();
+ res.json(profile);
+}));
+
+/**
+ * GET /api/digital-twin/taste/sections
+ * Get available taste sections with question definitions
+ */
+router.get('/taste/sections', asyncHandler(async (req, res) => {
+ const sections = Object.entries(tasteService.TASTE_SECTIONS).map(([id, config]) => ({
+ id,
+ label: config.label,
+ description: config.description,
+ icon: config.icon,
+ color: config.color,
+ questionCount: config.questions.length
+ }));
+ res.json(sections);
+}));
+
+/**
+ * GET /api/digital-twin/taste/:section/next
+ * Get the next question for a taste section
+ */
+router.get('/taste/:section/next', asyncHandler(async (req, res) => {
+ const parsed = tasteSectionEnum.safeParse(req.params.section);
+ if (!parsed.success) {
+ throw new ServerError(`Invalid taste section: ${req.params.section}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR'
+ });
+ }
+ const question = await tasteService.getNextQuestion(parsed.data);
+ res.json(question);
+}));
+
+/**
+ * POST /api/digital-twin/taste/answer
+ * Submit an answer for a taste question
+ */
+router.post('/taste/answer', asyncHandler(async (req, res) => {
+ const validation = validate(tasteAnswerInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const { section, questionId, answer } = validation.data;
+ const result = await tasteService.submitAnswer(section, questionId, answer);
+ res.json(result);
+}));
+
+/**
+ * GET /api/digital-twin/taste/:section/responses
+ * Get all responses for a taste section
+ */
+router.get('/taste/:section/responses', asyncHandler(async (req, res) => {
+ const parsed = tasteSectionEnum.safeParse(req.params.section);
+ if (!parsed.success) {
+ throw new ServerError(`Invalid taste section: ${req.params.section}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR'
+ });
+ }
+ const responses = await tasteService.getSectionResponses(parsed.data);
+ res.json(responses);
+}));
+
+/**
+ * POST /api/digital-twin/taste/summary
+ * Generate a taste profile summary (section or overall)
+ */
+router.post('/taste/summary', asyncHandler(async (req, res) => {
+ const validation = validate(tasteSummaryInputSchema, req.body);
+ if (!validation.success) {
+ throw new ServerError('Validation failed', {
+ status: 400,
+ code: 'VALIDATION_ERROR',
+ context: { details: validation.errors }
+ });
+ }
+ const { section, providerId, model } = validation.data;
+
+ const result = section
+ ? await tasteService.generateSectionSummary(section, providerId, model)
+ : await tasteService.generateOverallSummary(providerId, model);
+
+ res.json(result);
+}));
+
+/**
+ * DELETE /api/digital-twin/taste/:section
+ * Reset a taste section
+ */
+router.delete('/taste/:section', asyncHandler(async (req, res) => {
+ const parsed = tasteSectionEnum.safeParse(req.params.section);
+ if (!parsed.success) {
+ throw new ServerError(`Invalid taste section: ${req.params.section}`, {
+ status: 400,
+ code: 'VALIDATION_ERROR'
+ });
+ }
+ const result = await tasteService.resetSection(parsed.data);
+ res.json(result);
+}));
+
export default router;
diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.js
new file mode 100644
index 0000000000..16758a0f45
--- /dev/null
+++ b/server/services/taste-questionnaire.js
@@ -0,0 +1,782 @@
+/**
+ * Taste Questionnaire Service
+ *
+ * Manages a conversational questionnaire for building an aesthetic taste profile.
+ * Covers movies, music, visual art, architecture, and food preferences
+ * with branching follow-up questions based on responses.
+ */
+
+import { readFile, writeFile, mkdir } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { v4 as uuidv4 } from 'uuid';
+import { getActiveProvider, getProviderById } from './providers.js';
+import { buildPrompt } from './promptService.js';
+import { digitalTwinEvents } from './digital-twin.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = dirname(__filename);
+const DIGITAL_TWIN_DIR = join(__dirname, '../../data/digital-twin');
+const TASTE_PROFILE_FILE = join(DIGITAL_TWIN_DIR, 'taste-profile.json');
+
+function now() {
+ return new Date().toISOString();
+}
+
+// =============================================================================
+// QUESTION DEFINITIONS
+// =============================================================================
+
+// Each section has core questions and conditional follow-ups.
+// Follow-ups trigger when a core answer matches certain keywords/conditions.
+export const TASTE_SECTIONS = {
+ movies: {
+ label: 'Movies & Film',
+ description: 'Your relationship with cinema — what resonates visually, emotionally, narratively',
+ icon: 'Film',
+ color: 'red',
+ questions: [
+ {
+ id: 'movies-core-1',
+ text: 'Name 3-5 films you consider near-perfect. What specifically makes each one resonate with you?',
+ type: 'text',
+ followUps: [
+ {
+ id: 'movies-fu-visual',
+ trigger: 'visual|cinematography|shot|color|frame|aesthetic|look',
+ text: 'You mentioned visual elements. Do you gravitate more toward naturalistic cinematography (handheld, available light) or highly stylized/composed frames? Any specific directors of photography whose work you love?'
+ },
+ {
+ id: 'movies-fu-narrative',
+ trigger: 'story|narrative|character|plot|writing|dialogue',
+ text: 'You value narrative craft. Do you prefer tight, economical storytelling or sprawling, layered narratives? Are you drawn to ambiguity or resolution?'
+ },
+ {
+ id: 'movies-fu-mood',
+ trigger: 'mood|atmosphere|feeling|tone|vibe|haunting|intense',
+ text: 'Atmosphere matters to you. Describe the ideal emotional texture of a film that really grabs you — dark and brooding? Electric and frenetic? Meditative and slow?'
+ }
+ ]
+ },
+ {
+ id: 'movies-core-2',
+ text: 'What genres or styles do you actively avoid in film, and why?',
+ type: 'text',
+ followUps: [
+ {
+ id: 'movies-fu-exception',
+ trigger: 'except|but|unless|sometimes|one|though',
+ text: 'It sounds like there are exceptions to your avoidance. What is it about those exceptions that overcomes your usual resistance?'
+ }
+ ]
+ },
+ {
+ id: 'movies-core-3',
+ text: 'Think about the last film that genuinely surprised you or changed how you see something. What was it and what shifted?',
+ type: 'text',
+ followUps: []
+ }
+ ]
+ },
+ music: {
+ label: 'Music & Sound',
+ description: 'How you use music — background, active listening, emotional regulation, cognitive tool',
+ icon: 'Music',
+ color: 'green',
+ questions: [
+ {
+ id: 'music-core-1',
+ text: 'Describe your music taste in terms of what it does for you functionally. What do you listen to when you need to focus? To energize? To decompress?',
+ type: 'text',
+ followUps: [
+ {
+ id: 'music-fu-focus',
+ trigger: 'focus|concentrate|work|deep|flow|code|write',
+ text: 'For focus music — do you need something without lyrics, or can you tune out vocals? Do you prefer repetitive/minimal textures or complex evolving soundscapes?'
+ },
+ {
+ id: 'music-fu-energy',
+ trigger: 'energy|pump|gym|run|workout|drive|hype',
+ text: 'For energy music — is it the tempo that matters most, or the emotional intensity? Name a track that always delivers.'
+ }
+ ]
+ },
+ {
+ id: 'music-core-2',
+ text: 'What artists or albums have had a lasting impact on your musical identity? The ones you return to across years.',
+ type: 'text',
+ followUps: [
+ {
+ id: 'music-fu-era',
+ trigger: 'teen|young|college|childhood|growing up|first|early',
+ text: 'Formative music is powerful. Has your taste evolved significantly since then, or do those early influences still define your core preference?'
+ }
+ ]
+ },
+ {
+ id: 'music-core-3',
+ text: 'What sounds, instruments, or production styles do you find actively unpleasant or grating?',
+ type: 'text',
+ followUps: []
+ }
+ ]
+ },
+ visual_art: {
+ label: 'Visual Art & Design',
+ description: 'What you find beautiful, compelling, or worth staring at — from fine art to UI design',
+ icon: 'Palette',
+ color: 'violet',
+ questions: [
+ {
+ id: 'visual-core-1',
+ text: 'Minimalist or maximalist? Where do you fall on this spectrum and why? Think about the spaces, screens, and objects you surround yourself with.',
+ type: 'text',
+ followUps: [
+ {
+ id: 'visual-fu-minimal',
+ trigger: 'minimal|clean|simple|less|sparse|white space|negative space',
+ text: 'Within minimalism, there are flavors — Japanese wabi-sabi (imperfect, organic), Scandinavian (warm functional), or Swiss/Bauhaus (geometric precision). Which resonates most?'
+ },
+ {
+ id: 'visual-fu-maximal',
+ trigger: 'maximal|bold|busy|layer|complex|rich|ornate|detail',
+ text: 'Within maximalism — are you drawn to controlled density (like intricate patterns or data-dense dashboards) or exuberant chaos (like street art or collage)?'
+ }
+ ]
+ },
+ {
+ id: 'visual-core-2',
+ text: 'What color palettes or color combinations make you feel something? Both ones you love and ones you find repulsive.',
+ type: 'text',
+ followUps: [
+ {
+ id: 'visual-fu-dark',
+ trigger: 'dark|black|moody|shadow|contrast|neon',
+ text: 'You lean toward darker palettes. Is this about drama/contrast, or about comfort/coziness? Do you prefer pure black backgrounds or very dark grays/blues?'
+ },
+ {
+ id: 'visual-fu-warm',
+ trigger: 'warm|earth|natural|wood|brown|amber|terracotta|sunset',
+ text: 'You gravitate toward warm tones. Is there a natural material or environment that captures your ideal color world? Desert, forest, coastline?'
+ }
+ ]
+ },
+ {
+ id: 'visual-core-3',
+ text: 'Name a design movement, artist, or visual style that you feel genuinely represents your aesthetic sensibility.',
+ type: 'text',
+ followUps: []
+ }
+ ]
+ },
+ architecture: {
+ label: 'Architecture & Spaces',
+ description: 'The built environments that make you feel at home, inspired, or in awe',
+ icon: 'Building',
+ color: 'amber',
+ questions: [
+ {
+ id: 'arch-core-1',
+ text: 'Describe your ideal living space. Not what you can afford — what you would build if constraints didn\'t exist. Materials, light, layout, relationship to outdoors.',
+ type: 'text',
+ followUps: [
+ {
+ id: 'arch-fu-light',
+ trigger: 'light|window|glass|sun|bright|open|natural light',
+ text: 'Natural light is important to you. Do you prefer dramatic directional light (like a cathedral) or diffuse even illumination? Floor-to-ceiling glass or carefully placed apertures?'
+ },
+ {
+ id: 'arch-fu-material',
+ trigger: 'concrete|wood|steel|stone|brick|glass|material',
+ text: 'You mentioned specific materials. Do you prefer raw/exposed materials (concrete, steel) or finished/refined surfaces? Is tactile quality important?'
+ }
+ ]
+ },
+ {
+ id: 'arch-core-2',
+ text: 'What architectural styles or environments make you uncomfortable or feel wrong? Think about spaces where you feel anxious, uninspired, or trapped.',
+ type: 'text',
+ followUps: []
+ },
+ {
+ id: 'arch-core-3',
+ text: 'Think about a building or space you visited that left a lasting impression. What was it and why did it affect you?',
+ type: 'text',
+ followUps: [
+ {
+ id: 'arch-fu-sacred',
+ trigger: 'church|temple|museum|library|sacred|spiritual|awe',
+ text: 'Sounds like you respond to spaces with a sense of reverence or gravity. Is this about scale, silence, age, or something else? Do secular spaces ever achieve this for you?'
+ }
+ ]
+ }
+ ]
+ },
+ food: {
+ label: 'Food & Culinary',
+ description: 'Your relationship with food — flavor profiles, cuisines, dining experiences, cooking philosophy',
+ icon: 'UtensilsCrossed',
+ color: 'orange',
+ questions: [
+ {
+ id: 'food-core-1',
+ text: 'What cuisines or flavor profiles do you find yourself craving most often? Be specific — not just "Italian" but what about it.',
+ type: 'text',
+ followUps: [
+ {
+ id: 'food-fu-spice',
+ trigger: 'spic|heat|chili|pepper|hot|szechuan|thai|indian|capsaicin',
+ text: 'You gravitate toward heat/spice. Is it about the endorphin rush, the complexity it adds, or the cultural context? Do you have a preferred type of heat (bright chili vs deep smoky)?'
+ },
+ {
+ id: 'food-fu-umami',
+ trigger: 'umami|savory|depth|ferment|miso|soy|mushroom|rich|broth',
+ text: 'You appreciate deep savory flavors. Do you actively seek out fermented foods? How do you feel about acquired-taste ingredients like fish sauce, natto, or blue cheese?'
+ }
+ ]
+ },
+ {
+ id: 'food-core-2',
+ text: 'Do you cook? If so, describe your cooking style — improvisational or recipe-following, simple or ambitious, comfort food or experimental?',
+ type: 'text',
+ followUps: [
+ {
+ id: 'food-fu-improv',
+ trigger: 'improv|experiment|invent|no recipe|freestyle|whatever|fridge',
+ text: 'You cook intuitively. What are your go-to base ingredients or flavor building blocks that you always have on hand?'
+ }
+ ]
+ },
+ {
+ id: 'food-core-3',
+ text: 'Describe the ideal dining experience. Is it about the food quality, the setting, the company, the ritual? What matters most?',
+ type: 'text',
+ followUps: []
+ }
+ ]
+ }
+};
+
+// =============================================================================
+// DATA ACCESS
+// =============================================================================
+
+let profileCache = null;
+
+async function loadTasteProfile() {
+ if (profileCache) return profileCache;
+
+ if (!existsSync(TASTE_PROFILE_FILE)) {
+ const defaultProfile = {
+ version: '1.0.0',
+ createdAt: null,
+ updatedAt: null,
+ sections: {},
+ profileSummary: null,
+ lastSessionAt: null
+ };
+ for (const sectionId of Object.keys(TASTE_SECTIONS)) {
+ defaultProfile.sections[sectionId] = { status: 'pending', responses: [], summary: null };
+ }
+ await saveTasteProfile(defaultProfile);
+ return defaultProfile;
+ }
+
+ const raw = await readFile(TASTE_PROFILE_FILE, 'utf-8');
+ profileCache = JSON.parse(raw);
+ return profileCache;
+}
+
+async function saveTasteProfile(profile) {
+ if (!existsSync(DIGITAL_TWIN_DIR)) {
+ await mkdir(DIGITAL_TWIN_DIR, { recursive: true });
+ }
+ profile.updatedAt = now();
+ await writeFile(TASTE_PROFILE_FILE, JSON.stringify(profile, null, 2));
+ profileCache = profile;
+}
+
+// =============================================================================
+// PUBLIC API
+// =============================================================================
+
+/**
+ * Get the full taste profile status — sections, progress, summary
+ */
+export async function getTasteProfile() {
+ const profile = await loadTasteProfile();
+ const sections = Object.entries(TASTE_SECTIONS).map(([id, config]) => {
+ const sectionData = profile.sections[id] || { status: 'pending', responses: [], summary: null };
+ const totalCoreQuestions = config.questions.length;
+ const answeredCore = sectionData.responses.filter(r => r.questionId.includes('-core-')).length;
+ const answeredFollowUps = sectionData.responses.filter(r => r.questionId.includes('-fu-')).length;
+
+ return {
+ id,
+ label: config.label,
+ description: config.description,
+ icon: config.icon,
+ color: config.color,
+ status: sectionData.status,
+ progress: {
+ coreAnswered: answeredCore,
+ coreTotal: totalCoreQuestions,
+ followUpsAnswered: answeredFollowUps,
+ percentage: totalCoreQuestions > 0 ? Math.round((answeredCore / totalCoreQuestions) * 100) : 0
+ },
+ summary: sectionData.summary
+ };
+ });
+
+ const completedCount = sections.filter(s => s.status === 'completed').length;
+
+ return {
+ sections,
+ completedCount,
+ totalSections: sections.length,
+ overallPercentage: Math.round((completedCount / sections.length) * 100),
+ profileSummary: profile.profileSummary,
+ lastSessionAt: profile.lastSessionAt
+ };
+}
+
+/**
+ * Get the next question for a section.
+ * Returns core questions first, then triggered follow-ups based on previous answers.
+ */
+export async function getNextQuestion(sectionId) {
+ const config = TASTE_SECTIONS[sectionId];
+ if (!config) return null;
+
+ const profile = await loadTasteProfile();
+ const sectionData = profile.sections[sectionId] || { status: 'pending', responses: [], summary: null };
+ const answeredIds = new Set(sectionData.responses.map(r => r.questionId));
+
+ // First: serve unanswered core questions in order
+ for (const q of config.questions) {
+ if (!answeredIds.has(q.id)) {
+ return {
+ questionId: q.id,
+ section: sectionId,
+ sectionLabel: config.label,
+ text: q.text,
+ type: q.type,
+ isFollowUp: false,
+ progress: {
+ current: sectionData.responses.length + 1,
+ coreTotal: config.questions.length,
+ totalAnswered: sectionData.responses.length
+ }
+ };
+ }
+
+ // Check for triggered follow-ups for this core question
+ const coreResponse = sectionData.responses.find(r => r.questionId === q.id);
+ if (!coreResponse) continue;
+
+ for (const fu of q.followUps) {
+ if (answeredIds.has(fu.id)) continue;
+ const pattern = new RegExp(fu.trigger, 'i');
+ if (pattern.test(coreResponse.answer)) {
+ return {
+ questionId: fu.id,
+ section: sectionId,
+ sectionLabel: config.label,
+ text: fu.text,
+ type: 'text',
+ isFollowUp: true,
+ triggeredBy: q.id,
+ progress: {
+ current: sectionData.responses.length + 1,
+ coreTotal: config.questions.length,
+ totalAnswered: sectionData.responses.length
+ }
+ };
+ }
+ }
+ }
+
+ // All questions answered for this section
+ return null;
+}
+
+/**
+ * Submit an answer for a taste question.
+ */
+export async function submitAnswer(sectionId, questionId, answer) {
+ const config = TASTE_SECTIONS[sectionId];
+ if (!config) throw new Error(`Unknown taste section: ${sectionId}`);
+
+ const profile = await loadTasteProfile();
+ if (!profile.sections[sectionId]) {
+ profile.sections[sectionId] = { status: 'pending', responses: [], summary: null };
+ }
+
+ // Prevent duplicate answers
+ const existing = profile.sections[sectionId].responses.find(r => r.questionId === questionId);
+ if (existing) {
+ existing.answer = answer;
+ existing.updatedAt = now();
+ } else {
+ profile.sections[sectionId].responses.push({
+ questionId,
+ answer,
+ answeredAt: now()
+ });
+ }
+
+ if (!profile.createdAt) profile.createdAt = now();
+ profile.lastSessionAt = now();
+
+ // Update section status
+ const answeredCoreIds = new Set(
+ profile.sections[sectionId].responses
+ .filter(r => r.questionId.includes('-core-'))
+ .map(r => r.questionId)
+ );
+ const allCoreAnswered = config.questions.every(q => answeredCoreIds.has(q.id));
+
+ if (allCoreAnswered) {
+ // Check if all triggered follow-ups are also answered
+ const next = await getNextQuestionInternal(sectionId, profile);
+ profile.sections[sectionId].status = next ? 'in_progress' : 'completed';
+ } else {
+ profile.sections[sectionId].status = 'in_progress';
+ }
+
+ await saveTasteProfile(profile);
+
+ // Also update the AESTHETICS.md document with the response
+ await appendToAestheticsDoc(sectionId, config, questionId, answer);
+
+ console.log(`🎨 Taste answer submitted: ${sectionId}/${questionId} (${profile.sections[sectionId].responses.length} responses)`);
+
+ // Get the next question to return inline
+ const nextQuestion = await getNextQuestion(sectionId);
+
+ return {
+ section: sectionId,
+ questionId,
+ sectionStatus: profile.sections[sectionId].status,
+ totalResponses: profile.sections[sectionId].responses.length,
+ nextQuestion
+ };
+}
+
+/**
+ * Internal version that operates on an already-loaded profile object
+ */
+function getNextQuestionInternal(sectionId, profile) {
+ const config = TASTE_SECTIONS[sectionId];
+ if (!config) return null;
+
+ const sectionData = profile.sections[sectionId] || { status: 'pending', responses: [] };
+ const answeredIds = new Set(sectionData.responses.map(r => r.questionId));
+
+ for (const q of config.questions) {
+ if (!answeredIds.has(q.id)) return q;
+
+ const coreResponse = sectionData.responses.find(r => r.questionId === q.id);
+ if (!coreResponse) continue;
+
+ for (const fu of q.followUps) {
+ if (answeredIds.has(fu.id)) continue;
+ const pattern = new RegExp(fu.trigger, 'i');
+ if (pattern.test(coreResponse.answer)) return fu;
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Generate a taste profile summary for a section using AI.
+ */
+export async function generateSectionSummary(sectionId, providerId, model) {
+ const config = TASTE_SECTIONS[sectionId];
+ if (!config) throw new Error(`Unknown taste section: ${sectionId}`);
+
+ const profile = await loadTasteProfile();
+ const sectionData = profile.sections[sectionId];
+ if (!sectionData?.responses?.length) {
+ throw new Error(`No responses to summarize for section: ${sectionId}`);
+ }
+
+ const provider = providerId
+ ? await getProviderById(providerId)
+ : await getActiveProvider();
+
+ if (!provider) throw new Error('No AI provider available');
+
+ const modelId = model || provider.defaultModel;
+
+ // Build Q&A transcript for analysis
+ const transcript = sectionData.responses.map(r => {
+ const qDef = findQuestionDef(sectionId, r.questionId);
+ return `Q: ${qDef?.text || r.questionId}\nA: ${r.answer}`;
+ }).join('\n\n');
+
+ const prompt = `Analyze the following taste/preference interview responses about ${config.label} and produce a structured profile summary. Extract concrete preferences, patterns, anti-preferences, and aesthetic principles. Be specific — cite actual examples they mentioned.
+
+## Interview Transcript
+
+${transcript}
+
+## Output Format
+
+Respond with a concise profile in this exact structure:
+
+### ${config.label} Profile
+
+**Core Preferences:**
+- [Specific preference 1]
+- [Specific preference 2]
+- ...
+
+**Anti-Preferences (Actively Dislikes):**
+- [What they avoid and why]
+
+**Key Patterns:**
+- [Recurring theme or principle]
+
+**In Their Words:**
+- [1-2 direct quotes that capture their taste]`;
+
+ const result = await callProviderAISimple(provider, modelId, prompt, { temperature: 0.3, max_tokens: 1000 });
+
+ if (result.error) throw new Error(`AI analysis failed: ${result.error}`);
+
+ const summary = result.text?.trim();
+ if (!summary) throw new Error('AI returned empty summary');
+
+ // Store the summary
+ profile.sections[sectionId].summary = summary;
+ await saveTasteProfile(profile);
+
+ console.log(`🎨 Taste summary generated for ${sectionId}`);
+
+ return { section: sectionId, summary };
+}
+
+/**
+ * Generate an overall taste profile summary across all completed sections.
+ */
+export async function generateOverallSummary(providerId, model) {
+ const profile = await loadTasteProfile();
+
+ const completedSections = Object.entries(profile.sections)
+ .filter(([, data]) => data.responses?.length > 0);
+
+ if (completedSections.length === 0) {
+ throw new Error('No taste responses to summarize. Complete at least one section first.');
+ }
+
+ const provider = providerId
+ ? await getProviderById(providerId)
+ : await getActiveProvider();
+
+ if (!provider) throw new Error('No AI provider available');
+
+ const modelId = model || provider.defaultModel;
+
+ // Build combined transcript
+ const allTranscripts = completedSections.map(([sectionId, data]) => {
+ const config = TASTE_SECTIONS[sectionId];
+ const transcript = data.responses.map(r => {
+ const qDef = findQuestionDef(sectionId, r.questionId);
+ return `Q: ${qDef?.text || r.questionId}\nA: ${r.answer}`;
+ }).join('\n\n');
+ return `## ${config.label}\n\n${transcript}`;
+ }).join('\n\n---\n\n');
+
+ const prompt = `Analyze the following taste/preference interview responses across multiple aesthetic domains and produce a unified taste profile. Identify cross-cutting themes, contradictions, and the person's core aesthetic identity.
+
+${allTranscripts}
+
+## Output Format
+
+### Unified Taste Profile
+
+**Aesthetic Identity (2-3 sentences):**
+[A concise description of this person's overall aesthetic sensibility]
+
+**Cross-Cutting Themes:**
+- [Theme that appears across multiple domains]
+
+**Core Aesthetic Principles:**
+- [Fundamental principle 1]
+- [Fundamental principle 2]
+
+**Contradictions & Tensions:**
+- [Any interesting tensions in their preferences]
+
+**Summary Tags:**
+[5-8 descriptive tags like: "brutalist minimalist", "atmospheric storyteller", "texture-obsessed", etc.]`;
+
+ const result = await callProviderAISimple(provider, modelId, prompt, { temperature: 0.3, max_tokens: 1500 });
+
+ if (result.error) throw new Error(`AI analysis failed: ${result.error}`);
+
+ const summary = result.text?.trim();
+ if (!summary) throw new Error('AI returned empty summary');
+
+ profile.profileSummary = summary;
+ await saveTasteProfile(profile);
+
+ // Also write to AESTHETICS.md as the definitive profile
+ await writeAestheticsDocument(summary, completedSections);
+
+ digitalTwinEvents.emit('taste:profile-updated', { summary });
+ console.log(`🎨 Overall taste profile generated`);
+
+ return { summary };
+}
+
+/**
+ * Get all responses for a section (for review/editing)
+ */
+export async function getSectionResponses(sectionId) {
+ const config = TASTE_SECTIONS[sectionId];
+ if (!config) throw new Error(`Unknown taste section: ${sectionId}`);
+
+ const profile = await loadTasteProfile();
+ const sectionData = profile.sections[sectionId] || { responses: [] };
+
+ return sectionData.responses.map(r => {
+ const qDef = findQuestionDef(sectionId, r.questionId);
+ return {
+ questionId: r.questionId,
+ questionText: qDef?.text || r.questionId,
+ answer: r.answer,
+ isFollowUp: r.questionId.includes('-fu-'),
+ answeredAt: r.answeredAt
+ };
+ });
+}
+
+/**
+ * Reset a section (clear all responses)
+ */
+export async function resetSection(sectionId) {
+ const profile = await loadTasteProfile();
+ if (profile.sections[sectionId]) {
+ profile.sections[sectionId] = { status: 'pending', responses: [], summary: null };
+ await saveTasteProfile(profile);
+ console.log(`🎨 Taste section reset: ${sectionId}`);
+ }
+ return { section: sectionId, status: 'reset' };
+}
+
+// =============================================================================
+// HELPERS
+// =============================================================================
+
+function findQuestionDef(sectionId, questionId) {
+ const config = TASTE_SECTIONS[sectionId];
+ if (!config) return null;
+
+ for (const q of config.questions) {
+ if (q.id === questionId) return q;
+ for (const fu of q.followUps) {
+ if (fu.id === questionId) return fu;
+ }
+ }
+ return null;
+}
+
+async function callProviderAISimple(provider, model, prompt, { temperature = 0.3, max_tokens = 1000 } = {}) {
+ const timeout = provider.timeout || 300000;
+
+ if (provider.type === 'api') {
+ const headers = { 'Content-Type': 'application/json' };
+ if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeout);
+
+ const response = await fetch(`${provider.endpoint}/chat/completions`, {
+ method: 'POST',
+ headers,
+ signal: controller.signal,
+ body: JSON.stringify({
+ model,
+ messages: [{ role: 'user', content: prompt }],
+ temperature,
+ max_tokens
+ })
+ });
+
+ clearTimeout(timer);
+
+ if (!response.ok) {
+ const errorText = await response.text().catch(() => 'Unknown error');
+ return { error: `Provider returned ${response.status}: ${errorText}` };
+ }
+
+ const data = await response.json();
+ return { text: data.choices?.[0]?.message?.content || '' };
+ }
+
+ // CLI providers not supported for summary generation — require API
+ return { error: 'Taste profile summary requires an API-based provider' };
+}
+
+async function appendToAestheticsDoc(sectionId, config, questionId, answer) {
+ const targetPath = join(DIGITAL_TWIN_DIR, 'AESTHETICS.md');
+ let content = '';
+
+ if (existsSync(targetPath)) {
+ content = await readFile(targetPath, 'utf-8');
+ } else {
+ content = '# Aesthetic Preferences\n\n';
+ }
+
+ const qDef = findQuestionDef(sectionId, questionId);
+ const questionText = qDef?.text || questionId;
+ const sectionHeader = `## ${config.label}`;
+
+ // Add section header if not present
+ if (!content.includes(sectionHeader)) {
+ content += `\n${sectionHeader}\n\n`;
+ }
+
+ // Append the Q&A
+ const entry = `### ${questionText}\n\n${answer}\n\n`;
+
+ // Insert after the section header
+ const headerIdx = content.indexOf(sectionHeader);
+ const afterHeader = headerIdx + sectionHeader.length;
+ const nextSection = content.indexOf('\n## ', afterHeader + 1);
+
+ if (nextSection > -1) {
+ content = content.slice(0, nextSection) + entry + content.slice(nextSection);
+ } else {
+ content += entry;
+ }
+
+ await writeFile(targetPath, content);
+}
+
+async function writeAestheticsDocument(profileSummary, completedSections) {
+ const targetPath = join(DIGITAL_TWIN_DIR, 'AESTHETICS.md');
+
+ let content = '# Aesthetic Preferences\n\n';
+ content += '## Taste Profile Summary\n\n';
+ content += profileSummary + '\n\n';
+ content += '---\n\n';
+ content += '## Detailed Responses\n\n';
+
+ for (const [sectionId, data] of completedSections) {
+ const config = TASTE_SECTIONS[sectionId];
+ content += `### ${config.label}\n\n`;
+
+ for (const r of data.responses) {
+ const qDef = findQuestionDef(sectionId, r.questionId);
+ content += `**Q: ${qDef?.text || r.questionId}**\n\n`;
+ content += `${r.answer}\n\n`;
+ }
+ }
+
+ await writeFile(targetPath, content);
+}