Skip to content

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

feat([issue-708]): add Digital Twin image identity source (Appearance tab)

[._.]/ Adam Eivy7b8b4e0f4eb5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 27e553b256..12177fcd53 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,7 @@
- **[issue-708] Digital Twin "Voice" tab — spoken vs. written style** — Paste a transcript of yourself speaking and the Digital Twin compares it against how you write (a pasted sample, or your existing twin documents), surfacing where your spoken voice differs from your writing — formality, verbosity, sentence length, directness, filler words — and suggesting a communication profile for voice contexts that you can apply in one click.
- **[issue-711] "While You Were Away" dashboard card** — A new dashboard widget recaps what your agents did since your last visit: a count of completed runs, success/failure tally, total time worked, and the most recent wins plus anything that failed and needs a look. Each item opens the agents view, and a "Mark as seen" button resets the window to now. It appears on the Everything and Agent Watch layouts and can be added to any layout via Arrange.
+- **[issue-708] Digital Twin "Appearance" tab — image identity source** — Upload a photo of yourself and a vision-capable provider extracts your visible appearance and self-presentation (apparent age range, build, hair, style, grooming, vibe, setting, expression). Review and edit the generated write-up, then save it as your "Appearance & Presentation" core identity document so the twin has a grounded sense of how you look. Use a local vision model (LM Studio / Ollama) to keep the photo on-device; the image itself is never persisted, only the derived text.
## Changed
diff --git a/client/src/components/digital-twin/constants.js b/client/src/components/digital-twin/constants.js
index c8b3912c71..e6647f6a53 100644
--- a/client/src/components/digital-twin/constants.js
+++ b/client/src/components/digital-twin/constants.js
@@ -27,7 +27,8 @@ import {
Target,
Archive,
Drama,
- Mic
+ Mic,
+ Camera
} from 'lucide-react';
// Main navigation tabs
@@ -43,6 +44,7 @@ export const TABS = [
{ id: 'goals', label: 'Goals', icon: Target },
{ id: 'interview', label: 'Interview', icon: MessageSquare },
{ id: 'voice', label: 'Voice', icon: Mic },
+ { id: 'appearance', label: 'Appearance', icon: Camera },
{ 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/AppearanceTab.jsx b/client/src/components/digital-twin/tabs/AppearanceTab.jsx
new file mode 100644
index 0000000000..41ac8cb3a2
--- /dev/null
+++ b/client/src/components/digital-twin/tabs/AppearanceTab.jsx
@@ -0,0 +1,286 @@
+import { useState, useRef } from 'react';
+import {
+ Camera,
+ RefreshCw,
+ ScanFace,
+ Check,
+ Upload,
+ X,
+ AlertCircle
+} from 'lucide-react';
+import * as api from '../../../services/api';
+import toast from '../../ui/Toast';
+import useProviderModels from '../../../hooks/useProviderModels';
+import ProviderModelSelector from '../../ProviderModelSelector';
+
+// Cap the uploaded image so the base64 data URL stays well under the server's
+// JSON body limit and vision providers don't choke on huge payloads.
+const MAX_IMAGE_BYTES = 10 * 1024 * 1024; // 10MB
+
+const DETAIL_FIELDS = [
+ { key: 'appearance', label: 'Appearance' },
+ { key: 'presentation', label: 'Presentation' },
+ { key: 'expression', label: 'Expression & demeanor' },
+ { key: 'setting', label: 'Setting' }
+];
+
+export default function AppearanceTab({ onRefresh }) {
+ const {
+ providers, selectedProviderId, selectedModel, availableModels,
+ setSelectedProviderId, setSelectedModel, loading: providersLoading
+ } = useProviderModels();
+
+ const fileInputRef = useRef(null);
+ const [imageDataUrl, setImageDataUrl] = useState('');
+ const [analyzing, setAnalyzing] = useState(false);
+ const [result, setResult] = useState(null);
+ const [docDraft, setDocDraft] = useState('');
+ const [saving, setSaving] = useState(false);
+ const [saved, setSaved] = useState(false);
+
+ const handleFile = (file) => {
+ if (!file) return;
+ if (!file.type.startsWith('image/')) {
+ toast.error('Please choose an image file');
+ return;
+ }
+ if (file.size > MAX_IMAGE_BYTES) {
+ toast.error('Image is too large (max 10MB)');
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = (e) => {
+ setImageDataUrl(e.target.result);
+ setResult(null);
+ setDocDraft('');
+ setSaved(false);
+ };
+ reader.onerror = () => toast.error('Could not read that image');
+ reader.readAsDataURL(file);
+ };
+
+ const clearImage = () => {
+ setImageDataUrl('');
+ setResult(null);
+ setDocDraft('');
+ setSaved(false);
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ };
+
+ const handleAnalyze = async () => {
+ if (!imageDataUrl) {
+ toast.error('Choose a photo first');
+ return;
+ }
+ if (!selectedProviderId || !selectedModel) {
+ toast.error('Select a provider and model');
+ return;
+ }
+
+ setAnalyzing(true);
+ setResult(null);
+ setDocDraft('');
+ setSaved(false);
+
+ const res = await api.analyzeIdentityImage(
+ { imageDataUrl, providerId: selectedProviderId, model: selectedModel },
+ { silent: true }
+ ).catch((err) => ({ error: err.message }));
+
+ if (res.error && res.rawResponse) {
+ // The model replied but its output couldn't be parsed — surface it inline.
+ setResult(res);
+ } else if (res.error) {
+ toast.error(res.error);
+ } else {
+ setResult(res);
+ setDocDraft(res.suggestedDocument?.content || '');
+ toast.success('Image analyzed');
+ }
+ setAnalyzing(false);
+ };
+
+ const handleSave = async () => {
+ const content = docDraft.trim();
+ if (!content) return;
+
+ setSaving(true);
+ const res = await api.saveIdentityImageDocument(
+ { content, title: result?.suggestedDocument?.title },
+ { silent: true }
+ ).catch((err) => ({ error: err.message }));
+
+ if (res?.error) {
+ toast.error(res.error);
+ } else {
+ setSaved(true);
+ toast.success('Saved to Appearance & Presentation document');
+ onRefresh?.();
+ }
+ setSaving(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">
+ <Camera className="w-6 h-6 text-port-accent" />
+ <div>
+ <h2 className="text-lg font-semibold text-white">Appearance from a Photo</h2>
+ <p className="text-sm text-gray-400">
+ Upload a photo of yourself and a vision model extracts your visible appearance and
+ self-presentation, which you can save as a Digital Twin identity document. Use a
+ local vision provider (LM Studio / Ollama) to keep the photo on-device.
+ </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={analyzing}
+ />
+ )}
+
+ <div>
+ <label htmlFor="appearance-image" className="block text-sm font-medium text-gray-300 mb-1">
+ Photo
+ </label>
+ <input
+ id="appearance-image"
+ ref={fileInputRef}
+ type="file"
+ accept="image/*"
+ onChange={(e) => handleFile(e.target.files?.[0])}
+ disabled={analyzing}
+ className="hidden"
+ />
+ {!imageDataUrl ? (
+ <button
+ type="button"
+ onClick={() => fileInputRef.current?.click()}
+ disabled={analyzing}
+ className="flex items-center gap-2 px-4 py-3 min-h-[48px] w-full justify-center border border-dashed border-port-border rounded-lg text-gray-400 hover:border-port-accent hover:text-white transition-colors disabled:opacity-50"
+ >
+ <Upload size={18} /> Choose a photo (max 10MB)
+ </button>
+ ) : (
+ <div className="relative inline-block">
+ <img
+ src={imageDataUrl}
+ alt="Selected"
+ className="max-h-64 rounded-lg border border-port-border"
+ />
+ <button
+ type="button"
+ onClick={clearImage}
+ disabled={analyzing}
+ aria-label="Remove photo"
+ className="absolute top-2 right-2 p-1.5 bg-port-bg/90 border border-port-border rounded-full text-gray-300 hover:text-white disabled:opacity-50"
+ >
+ <X size={16} />
+ </button>
+ </div>
+ )}
+ </div>
+
+ <div className="flex justify-end">
+ <button
+ onClick={handleAnalyze}
+ disabled={analyzing || !imageDataUrl || !selectedProviderId || !selectedModel}
+ className="flex items-center gap-2 px-6 py-3 min-h-[48px] bg-port-accent text-white rounded-lg font-medium hover:bg-port-accent/80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {analyzing ? (
+ <><RefreshCw size={18} className="animate-spin" /> Analyzing...</>
+ ) : (
+ <><ScanFace size={18} /> Analyze</>
+ )}
+ </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">
+ <ScanFace className="w-6 h-6 text-green-400" />
+ <h2 className="text-lg font-semibold text-white">Appearance analysis</h2>
+ </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">
+ {DETAIL_FIELDS.map(({ key, label }) => (
+ result[key] && (
+ <div key={key} className="bg-port-bg rounded-lg border border-port-border p-4">
+ <h4 className="text-sm font-semibold text-port-accent mb-2">{label}</h4>
+ <p className="text-sm text-gray-300">{result[key]}</p>
+ </div>
+ )
+ ))}
+ </div>
+
+ {Array.isArray(result.descriptors) && result.descriptors.length > 0 && (
+ <div className="flex flex-wrap gap-1.5">
+ {result.descriptors.map((d, i) => (
+ <span key={i} className="text-xs px-2 py-0.5 rounded-full bg-port-border/60 text-gray-300">
+ {d}
+ </span>
+ ))}
+ </div>
+ )}
+
+ {result.suggestedDocument && (
+ <div className="bg-port-bg rounded-lg border border-port-accent/30 p-4 space-y-3">
+ <div>
+ <label htmlFor="appearance-doc" className="block text-sm font-semibold text-white mb-1">
+ Identity document
+ </label>
+ <p className="text-xs text-gray-500 mb-2">
+ Edit if needed, then save. This updates your <span className="text-gray-300">Appearance &amp; Presentation</span> core document.
+ </p>
+ <textarea
+ id="appearance-doc"
+ value={docDraft}
+ onChange={(e) => { setDocDraft(e.target.value); setSaved(false); }}
+ rows={10}
+ className="w-full px-4 py-3 bg-port-card border border-port-border rounded-lg text-white text-sm font-mono resize-y focus:outline-hidden focus:border-port-accent"
+ />
+ </div>
+ <button
+ onClick={handleSave}
+ disabled={saving || saved || !docDraft.trim()}
+ 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"
+ >
+ {saved ? (
+ <><Check size={16} /> Saved</>
+ ) : saving ? (
+ <><RefreshCw size={16} className="animate-spin" /> Saving...</>
+ ) : (
+ 'Save as identity document'
+ )}
+ </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.jsx
index ba4d47043a..9f8bc00edd 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -17,6 +17,7 @@ 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 AppearanceTab from '../components/digital-twin/tabs/AppearanceTab';
import IdentityTab from '../components/digital-twin/tabs/IdentityTab';
import PersonasTab from '../components/digital-twin/tabs/PersonasTab';
import GoalsTab from '../components/digital-twin/tabs/GoalsTab';
@@ -75,6 +76,8 @@ export default function DigitalTwin() {
return <InterviewTab onRefresh={refetch} />;
case 'voice':
return <VoiceStyleTab onRefresh={refetch} />;
+ case 'appearance':
+ return <AppearanceTab onRefresh={refetch} />;
case 'autobiography':
return <AutobiographyTab onRefresh={refetch} />;
case 'import':
diff --git a/client/src/services/apiDigitalTwin.js b/client/src/services/apiDigitalTwin.js
index c0db814800..a01fc7cb5b 100644
--- a/client/src/services/apiDigitalTwin.js
+++ b/client/src/services/apiDigitalTwin.js
@@ -120,6 +120,19 @@ export const compareSpokenWrittenStyle = (payload, options = {}) => request('/di
...options
});
+// Image identity source (M34 P5). Analyze a photo with a vision model to extract
+// visible appearance / presentation, then optionally save it as an identity doc.
+export const analyzeIdentityImage = (payload, options = {}) => request('/digital-twin/identity/image', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ ...options
+});
+export const saveIdentityImageDocument = (payload, options = {}) => request('/digital-twin/identity/image/save', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ ...options
+});
+
// Digital Twin - List-based Enrichment
export const analyzeEnrichmentList = (category, items, providerId, model) => request('/digital-twin/enrich/analyze-list', {
method: 'POST',
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index f3bba3350a..aabf0a9a7d 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -228,6 +228,13 @@
"returnsJson": true,
"variables": []
},
+ "twin-image-identity-analyze": {
+ "name": "Twin Image Identity Analyzer",
+ "description": "Analyze a photo of a person and extract visible appearance and self-presentation descriptors for their digital twin",
+ "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-image-identity-analyze.md b/data.reference/prompts/stages/twin-image-identity-analyze.md
new file mode 100644
index 0000000000..618724cf7c
--- /dev/null
+++ b/data.reference/prompts/stages/twin-image-identity-analyze.md
@@ -0,0 +1,21 @@
+You are analyzing a photograph of a person to build an "identity source" for their digital twin. Look only at what is actually visible in the image and describe it factually. Do NOT attempt to identify who the person is, guess their name, infer protected attributes (race, religion, health conditions, sexual orientation), or speculate beyond what the picture supports. If a dimension can't be judged from the image, say so briefly rather than inventing detail.
+
+Describe the person's visible appearance and self-presentation so their digital twin has a grounded sense of how they look and present themselves (useful for avatar generation, self-description, and presentation-aware contexts).
+
+Cover:
+- appearance: apparent age range, build, hair, and any clearly visible physical features — visible facts only
+- presentation: clothing, style, grooming, accessories, and the overall aesthetic/vibe they project
+- setting: the environment or background and what, if anything, it suggests about context (professional, casual, outdoors, studio, candid…)
+- expression: facial expression, demeanor, and apparent energy
+- descriptors: a handful of short tag-like words that capture the overall look and presentation
+
+Reply with JSON only, no prose outside the JSON:
+{
+ "appearance": "<2-4 sentences, visible physical description only>",
+ "presentation": "<2-4 sentences on style, clothing, grooming, accessories, overall vibe>",
+ "setting": "<1-2 sentences on environment/background and any context it suggests>",
+ "expression": "<1-2 sentences on facial expression, demeanor, energy>",
+ "descriptors": ["short", "tag-like", "descriptors", "up to 8"],
+ "summary": "<2-3 sentence overall appearance-and-presentation summary>",
+ "documentMarkdown": "<a clean, self-contained markdown block (use ## headings) suitable to save directly as a Digital Twin identity document, weaving the above together>"
+}
diff --git a/scripts/migrations/070-twin-image-identity-prompt.js b/scripts/migrations/070-twin-image-identity-prompt.js
new file mode 100644
index 0000000000..1dafb309f9
--- /dev/null
+++ b/scripts/migrations/070-twin-image-identity-prompt.js
@@ -0,0 +1,84 @@
+/**
+ * Seed the Digital Twin image-identity analysis prompt stage into existing
+ * installs (issue #708, M34 P5 — multi-modal personality capture).
+ *
+ * Single-stage sibling of the spoken-vs-written prompt seed (migration 069):
+ * copies the `twin-image-identity-analyze.md` template from
+ * `data.reference/prompts/stages/` and merges its stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running the full setup) would otherwise leave the new stage unseeded and the
+ * first POST .../identity/image call would throw "Stage not found".
+ *
+ * FIRST-SHIPMENT SEED ONLY — no MD5 hashing: it copies the template only when
+ * missing and never overwrites an install's existing prompt. A FUTURE migration
+ * that AMENDS this prompt must follow migration 003's hash-driven pattern
+ * (normalize line endings, ship OLD + NEW shipped hashes) instead.
+ */
+
+import { access, copyFile, mkdir, readFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+import { atomicWrite } from '../../server/lib/fileUtils.js';
+
+// The prompt file's basename doubles as its stage-config key (sans `.md`).
+const STAGE = 'twin-image-identity-analyze';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ // 1. Copy the prompt template if it's missing.
+ const filename = `${STAGE}.md`;
+ const dataPath = join(stagesDir, filename);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 twin-image-identity prompt: ${filename} already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ twin-image-identity: sample missing for ${filename} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${filename}`);
+ } catch (err) {
+ console.warn(`⚠️ twin-image-identity: copy failed for ${filename}: ${err.message}`);
+ }
+ }
+ }
+
+ // 2. Merge the stage-config entry if it's missing.
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ twin-image-identity: data.reference stage-config.json missing — skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE]) {
+ console.log(`📝 twin-image-identity stage-config: ${STAGE} already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE]) {
+ console.warn(`⚠️ twin-image-identity: sample stage-config missing ${STAGE} — skipping`);
+ return;
+ }
+ installed.stages[STAGE] = sample.stages[STAGE];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await atomicWrite(installedConfigPath, `${JSON.stringify(installed, null, 2)}\n`);
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 twin-image-identity stage-config (${action}): ${STAGE} added`);
+ } catch (err) {
+ console.warn(`⚠️ twin-image-identity: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/scripts/migrations/070-twin-image-identity-prompt.test.js b/scripts/migrations/070-twin-image-identity-prompt.test.js
new file mode 100644
index 0000000000..aaf63e0fc9
--- /dev/null
+++ b/scripts/migrations/070-twin-image-identity-prompt.test.js
@@ -0,0 +1,58 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './070-twin-image-identity-prompt.js';
+
+const STAGE = 'twin-image-identity-analyze';
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 070 — seed twin image-identity analysis prompt', () => {
+ let rootDir;
+ let installedStagesDir;
+ let installedConfigPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-070-'));
+ const refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');
+ mkdirSync(refStagesDir, { recursive: true });
+ writeFileSync(join(refStagesDir, `${STAGE}.md`), `# ${STAGE}\n\nbody\n`);
+ const refConfig = { stages: { [STAGE]: { name: STAGE, model: 'default', returnsJson: true, variables: [] } } };
+ writeFileSync(join(rootDir, 'data.reference', 'prompts', 'stage-config.json'), JSON.stringify(refConfig, null, 2) + '\n');
+
+ installedStagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('seeds the prompt file + stage-config entry on a fresh install', async () => {
+ await migration.up({ rootDir });
+ expect(existsSync(join(installedStagesDir, `${STAGE}.md`))).toBe(true);
+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();
+ });
+
+ it('merges into an existing stage-config without clobbering other stages', async () => {
+ mkdirSync(installedStagesDir, { recursive: true });
+ writeFileSync(installedConfigPath, JSON.stringify({ stages: { 'pipeline-prose': { name: 'Prose' } } }, null, 2) + '\n');
+ await migration.up({ rootDir });
+ const config = readJson(installedConfigPath);
+ expect(config.stages['pipeline-prose']).toBeTruthy();
+ expect(config.stages[STAGE]).toBeTruthy();
+ });
+
+ it('is idempotent and preserves a user-customized installed prompt', async () => {
+ mkdirSync(installedStagesDir, { recursive: true });
+ const customPath = join(installedStagesDir, `${STAGE}.md`);
+ writeFileSync(customPath, '# CUSTOM image identity prompt\n');
+ await migration.up({ rootDir });
+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');
+ // Second run is a clean no-op.
+ await migration.up({ rootDir });
+ expect(readFileSync(customPath, 'utf-8')).toContain('CUSTOM');
+ expect(readJson(installedConfigPath).stages[STAGE]).toBeTruthy();
+ });
+});
diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.js
index cf955ce213..eff9aecab4 100644
--- a/server/lib/digitalTwinValidation.js
+++ b/server/lib/digitalTwinValidation.js
@@ -419,6 +419,24 @@ export const spokenWrittenStyleInputSchema = z.object({
model: z.string().min(1)
});
+// Image identity-source input (M34 P5 — multi-modal capture). A base64 image
+// data URL plus the vision-capable provider/model. The data URL is capped well
+// under the server's 55mb JSON body limit (~15M chars ≈ 11MB of image bytes).
+export const identityImageInputSchema = z.object({
+ imageDataUrl: z.string()
+ .max(15_000_000)
+ .regex(/^data:image\/(png|jpe?g|gif|webp);base64,/, 'Must be a base64 image data URL'),
+ providerId: z.string().min(1),
+ model: z.string().min(1)
+});
+
+// Save the appearance analysis as an identity document. Mirrors the import/save
+// upsert shape — content is required, title optional.
+export const identityImageSaveInputSchema = z.object({
+ content: z.string().min(1).max(100000),
+ title: z.string().min(1).max(200).optional()
+});
+
// List-based enrichment item
export const listItemSchema = z.object({
title: z.string().min(1).max(500),
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 7e078ad7c4..4c02462461 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -100,6 +100,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.twin.overview', path: '/digital-twin/overview', label: 'Overview', section: 'Digital Twin', aliases: ['digital-twin', 'twin'] },
{ id: 'nav.twin.accounts', path: '/digital-twin/accounts', label: 'Accounts', section: 'Digital Twin', aliases: ['twin-accounts'] },
+ { id: 'nav.twin.appearance', path: '/digital-twin/appearance', label: 'Appearance', section: 'Digital Twin', aliases: ['twin-appearance', 'appearance', 'photo'], keywords: ['image', 'photo', 'vision', 'face', 'identity', 'presentation', 'look', 'avatar'] },
{ id: 'nav.ask', path: '/ask', label: 'Ask Yourself', section: 'Digital Twin', aliases: ['ask', 'ask-yourself', 'twin-chat'], keywords: ['chat', 'twin', 'conversation', 'advise', 'draft'] },
{ id: 'nav.twin.autobiography', path: '/digital-twin/autobiography', label: 'Autobiography', section: 'Digital Twin', aliases: ['twin-autobiography', 'autobiography'] },
{ id: 'nav.character', path: '/character', label: 'Character', section: 'Digital Twin', aliases: ['character'] },
diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.js
index 3bcefcc837..9ad806ccb9 100644
--- a/server/routes/digital-twin.js
+++ b/server/routes/digital-twin.js
@@ -29,6 +29,8 @@ import {
generateTestsInputSchema,
writingAnalysisInputSchema,
spokenWrittenStyleInputSchema,
+ identityImageInputSchema,
+ identityImageSaveInputSchema,
analyzeListInputSchema,
saveListDocumentInputSchema,
getListItemsInputSchema,
@@ -555,6 +557,31 @@ router.post('/style/spoken-written', asyncHandler(async (req, res) => {
res.json(result);
}));
+/**
+ * POST /api/digital-twin/identity/image
+ * Analyze a photo of the user with a vision model and extract visible
+ * appearance / self-presentation descriptors (M34 P5 — multi-modal capture).
+ */
+router.post('/identity/image', asyncHandler(async (req, res) => {
+ const data = validateRequest(identityImageInputSchema, req.body);
+ const result = await digitalTwinService.analyzeIdentityImage(data);
+ res.json(result);
+}));
+
+/**
+ * POST /api/digital-twin/identity/image/save
+ * Persist the appearance analysis as a Digital Twin identity document
+ * (upserts APPEARANCE.md).
+ */
+router.post('/identity/image/save', asyncHandler(async (req, res) => {
+ const data = validateRequest(identityImageSaveInputSchema, req.body);
+ const result = await digitalTwinService.saveIdentityImageDocument(data);
+ if (result?.error) {
+ throw new ServerError(result.error, { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ res.json(result);
+}));
+
// =============================================================================
// TRAITS & CONFIDENCE (Phase 1 & 2)
// =============================================================================
diff --git a/server/services/digital-twin-image-identity.js b/server/services/digital-twin-image-identity.js
new file mode 100644
index 0000000000..fcc3a63e1b
--- /dev/null
+++ b/server/services/digital-twin-image-identity.js
@@ -0,0 +1,173 @@
+/**
+ * Digital Twin — Image Identity Source (M34 P5)
+ *
+ * A multi-modal capture slice: the user supplies a photo of themselves and a
+ * vision-capable provider extracts the *visible* appearance and self-presentation
+ * (apparent age range, build, hair, style, grooming, vibe, setting, expression).
+ * The result can be saved as a Digital Twin identity document so the twin has a
+ * grounded sense of how the user looks and presents themselves — useful for
+ * avatar generation, self-description, and presentation-aware contexts.
+ *
+ * Reuses the existing vision plumbing (`describeImageDataUrl`) and the prompt
+ * stage system; no new capture/transcription infra. The image arrives as a
+ * base64 data URL in the request body, is sent to the provider, and is NOT
+ * persisted — only the derived text descriptors are.
+ */
+
+import { buildPrompt } from './promptService.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { getProviderById } from './providers.js';
+import { describeImageDataUrl } from './visionTest.js';
+import { loadMeta } from './digital-twin-meta.js';
+import { createDocument, updateDocument } from './digital-twin-documents.js';
+
+// The identity document this slice creates/updates on save.
+const IDENTITY_DOC = {
+ filename: 'APPEARANCE.md',
+ title: 'Appearance & Presentation',
+ category: 'core'
+};
+
+/**
+ * Analyze a photo of the user and extract visible appearance / presentation
+ * descriptors.
+ *
+ * @param {object} input
+ * @param {string} input.imageDataUrl - base64 image data URL (data:image/...;base64,...)
+ * @param {string} input.providerId - a vision-capable API provider
+ * @param {string} input.model
+ */
+export async function analyzeIdentityImage({ imageDataUrl, providerId, model }) {
+ if (typeof imageDataUrl !== 'string' || !imageDataUrl.startsWith('data:image/')) {
+ return { error: 'A base64 image data URL is required' };
+ }
+
+ const provider = await getProviderById(providerId);
+ if (!provider || !provider.enabled) {
+ return { error: 'Provider not found or disabled' };
+ }
+ // Vision runs over the OpenAI-compatible /chat/completions path, which only
+ // the API provider type implements — surface a clear message rather than the
+ // raw transport error a CLI/TUI provider would throw.
+ if (provider.type !== 'api') {
+ return { error: 'Image analysis needs an API provider with a vision-capable model (e.g. a local LM Studio or Ollama vision model)' };
+ }
+
+ const prompt = await buildPrompt('twin-image-identity-analyze', {}).catch(() => null);
+ if (!prompt) {
+ return { error: 'Image identity prompt template not found' };
+ }
+
+ // describeImageDataUrl throws on provider/transport errors; translate to the
+ // { error } shape the rest of the digital-twin services use.
+ const text = await describeImageDataUrl({ dataUrl: imageDataUrl, prompt, providerId, model })
+ .catch((err) => ({ __error: err?.message || 'Vision request failed' }));
+
+ if (text && typeof text === 'object' && text.__error) {
+ return { error: text.__error };
+ }
+ if (!text) {
+ return { error: 'Vision model returned an empty response' };
+ }
+
+ return parseIdentityImage(text);
+}
+
+/**
+ * Persist (or update) the appearance analysis as a Digital Twin identity
+ * document. Upserts by filename — mirrors `saveImportAsDocument` so re-running
+ * the analysis refreshes the same document instead of erroring on a duplicate.
+ *
+ * @param {object} suggestedDoc - { content, title? }
+ */
+export async function saveIdentityImageDocument(suggestedDoc) {
+ const content = typeof suggestedDoc?.content === 'string' ? suggestedDoc.content.trim() : '';
+ if (!content) {
+ return { error: 'No document content to save' };
+ }
+ const title = (typeof suggestedDoc?.title === 'string' && suggestedDoc.title.trim())
+ ? suggestedDoc.title.trim()
+ : IDENTITY_DOC.title;
+
+ const meta = await loadMeta();
+ const existing = meta.documents.find(d => d.filename === IDENTITY_DOC.filename);
+ if (existing) {
+ return updateDocument(existing.id, { content, title });
+ }
+ return createDocument({
+ filename: IDENTITY_DOC.filename,
+ title,
+ category: IDENTITY_DOC.category,
+ content,
+ enabled: true,
+ priority: 5
+ });
+}
+
+/**
+ * Build a markdown identity document from the parsed appearance fields. Used as
+ * a fallback when the model omits `documentMarkdown`, so a save always has clean
+ * content to persist.
+ */
+function buildDocumentMarkdown({ summary, appearance, presentation, setting, expression, descriptors }) {
+ const lines = ['# Appearance & Presentation', ''];
+ if (summary) lines.push(summary, '');
+ if (appearance) lines.push('## Appearance', '', appearance, '');
+ if (presentation) lines.push('## Presentation', '', presentation, '');
+ if (expression) lines.push('## Expression & Demeanor', '', expression, '');
+ if (setting) lines.push('## Setting', '', setting, '');
+ if (Array.isArray(descriptors) && descriptors.length > 0) {
+ lines.push('## Descriptors', '', descriptors.map(d => `- ${d}`).join('\n'), '');
+ }
+ return lines.join('\n').trim();
+}
+
+/**
+ * Parse the vision response into a normalized shape. Tolerates a raw JSON
+ * object or a ```json fenced block (same convention as the other twin
+ * analyzers). Strings default to '' and arrays to [] so the client can
+ * distinguish absent from present-but-empty; a `suggestedDocument` is always
+ * synthesized so the save action has content even when the model omits
+ * `documentMarkdown`.
+ */
+export function parseIdentityImage(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 image analysis - no JSON found', rawResponse: response };
+ }
+
+ const parsed = safeJSONParse(jsonStr, null, {
+ allowArray: false,
+ logError: true,
+ context: 'image identity analysis'
+ });
+
+ if (!parsed) {
+ return { error: 'Failed to parse image analysis - invalid JSON', rawResponse: response };
+ }
+
+ const str = (v) => (typeof v === 'string' ? v.trim() : '');
+ const fields = {
+ appearance: str(parsed.appearance),
+ presentation: str(parsed.presentation),
+ setting: str(parsed.setting),
+ expression: str(parsed.expression),
+ descriptors: Array.isArray(parsed.descriptors)
+ ? parsed.descriptors.filter(d => typeof d === 'string' && d.trim()).map(d => d.trim()).slice(0, 8)
+ : [],
+ summary: str(parsed.summary)
+ };
+
+ const documentMarkdown = str(parsed.documentMarkdown) || buildDocumentMarkdown(fields);
+
+ return {
+ ...fields,
+ suggestedDocument: documentMarkdown
+ ? { filename: IDENTITY_DOC.filename, title: IDENTITY_DOC.title, category: IDENTITY_DOC.category, content: documentMarkdown }
+ : null
+ };
+}
diff --git a/server/services/digital-twin-image-identity.test.js b/server/services/digital-twin-image-identity.test.js
new file mode 100644
index 0000000000..3ef6d0cca1
--- /dev/null
+++ b/server/services/digital-twin-image-identity.test.js
@@ -0,0 +1,165 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mocks — declared before importing the module under test. We mock the
+// provider/vision/prompt/document deps; safeJSONParse (from fileUtils) runs for
+// real so parseIdentityImage is exercised end-to-end.
+vi.mock('./promptService.js', () => ({ buildPrompt: vi.fn() }));
+vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));
+vi.mock('./visionTest.js', () => ({ describeImageDataUrl: vi.fn() }));
+vi.mock('./digital-twin-meta.js', () => ({ loadMeta: vi.fn() }));
+vi.mock('./digital-twin-documents.js', () => ({ createDocument: vi.fn(), updateDocument: vi.fn() }));
+
+import {
+ analyzeIdentityImage,
+ saveIdentityImageDocument,
+ parseIdentityImage
+} from './digital-twin-image-identity.js';
+import { buildPrompt } from './promptService.js';
+import { getProviderById } from './providers.js';
+import { describeImageDataUrl } from './visionTest.js';
+import { loadMeta } from './digital-twin-meta.js';
+import { createDocument, updateDocument } from './digital-twin-documents.js';
+
+const DATA_URL = 'data:image/jpeg;base64,QUJD';
+
+const VALID_JSON = JSON.stringify({
+ appearance: 'Adult with short dark hair and a medium build.',
+ presentation: 'Casual button-down, relaxed style, minimal accessories.',
+ setting: 'Indoors against a plain wall — looks like a candid shot.',
+ expression: 'Relaxed, slight smile, calm energy.',
+ descriptors: ['casual', 'approachable', 'minimal', ' ', 42],
+ summary: 'Approachable, casual self-presentation in a candid indoor setting.',
+ documentMarkdown: '## Appearance\nShort dark hair, medium build.'
+});
+
+describe('parseIdentityImage', () => {
+ it('parses a raw JSON object and synthesizes a suggestedDocument', () => {
+ const r = parseIdentityImage(VALID_JSON);
+ expect(r.error).toBeUndefined();
+ expect(r.appearance).toContain('dark hair');
+ expect(r.summary).toContain('Approachable');
+ // Non-string / blank descriptors are filtered out.
+ expect(r.descriptors).toEqual(['casual', 'approachable', 'minimal']);
+ expect(r.suggestedDocument.filename).toBe('APPEARANCE.md');
+ expect(r.suggestedDocument.content).toContain('## Appearance');
+ });
+
+ it('parses a ```json fenced block', () => {
+ const r = parseIdentityImage('Sure:\n```json\n' + VALID_JSON + '\n```\nDone.');
+ expect(r.error).toBeUndefined();
+ expect(r.presentation).toContain('button-down');
+ });
+
+ it('builds document markdown from fields when documentMarkdown is absent', () => {
+ const r = parseIdentityImage(JSON.stringify({
+ appearance: 'Tall with curly hair.',
+ summary: 'A quick look.',
+ descriptors: ['tall', 'curly']
+ }));
+ expect(r.error).toBeUndefined();
+ expect(r.suggestedDocument.content).toContain('# Appearance & Presentation');
+ expect(r.suggestedDocument.content).toContain('Tall with curly hair.');
+ expect(r.suggestedDocument.content).toContain('- tall');
+ // Absent string fields default to '' rather than undefined.
+ expect(r.presentation).toBe('');
+ });
+
+ it('returns an error with rawResponse when no JSON is present', () => {
+ const r = parseIdentityImage('I cannot analyze that image.');
+ expect(r.error).toMatch(/no JSON found/);
+ expect(r.rawResponse).toBe('I cannot analyze that image.');
+ });
+
+ it('returns an error with rawResponse on invalid JSON', () => {
+ const r = parseIdentityImage('{ not valid json ');
+ expect(r.error).toMatch(/invalid JSON|no JSON found/);
+ });
+});
+
+describe('analyzeIdentityImage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getProviderById.mockResolvedValue({ id: 'p1', enabled: true, type: 'api' });
+ buildPrompt.mockResolvedValue('PROMPT');
+ describeImageDataUrl.mockResolvedValue(VALID_JSON);
+ });
+
+ it('rejects a non-data-URL before touching the provider', async () => {
+ const r = await analyzeIdentityImage({ imageDataUrl: 'http://example.com/x.png', providerId: 'p1', model: 'm' });
+ expect(r.error).toMatch(/data URL/);
+ expect(getProviderById).not.toHaveBeenCalled();
+ });
+
+ it('errors when the provider is missing or disabled', async () => {
+ getProviderById.mockResolvedValue(null);
+ const r = await analyzeIdentityImage({ imageDataUrl: DATA_URL, providerId: 'p1', model: 'm' });
+ expect(r.error).toMatch(/not found or disabled/);
+ expect(describeImageDataUrl).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-API provider (vision needs an API provider)', async () => {
+ getProviderById.mockResolvedValue({ id: 'p1', enabled: true, type: 'cli' });
+ const r = await analyzeIdentityImage({ imageDataUrl: DATA_URL, providerId: 'p1', model: 'm' });
+ expect(r.error).toMatch(/API provider/);
+ expect(describeImageDataUrl).not.toHaveBeenCalled();
+ });
+
+ it('errors when the prompt template is missing', async () => {
+ buildPrompt.mockRejectedValue(new Error('Stage not found'));
+ const r = await analyzeIdentityImage({ imageDataUrl: DATA_URL, providerId: 'p1', model: 'm' });
+ expect(r.error).toMatch(/prompt template not found/);
+ expect(describeImageDataUrl).not.toHaveBeenCalled();
+ });
+
+ it('translates a thrown vision error to the { error } shape', async () => {
+ describeImageDataUrl.mockRejectedValue(new Error('vision endpoint unreachable'));
+ const r = await analyzeIdentityImage({ imageDataUrl: DATA_URL, providerId: 'p1', model: 'm' });
+ expect(r.error).toBe('vision endpoint unreachable');
+ });
+
+ it('errors on an empty vision response', async () => {
+ describeImageDataUrl.mockResolvedValue('');
+ const r = await analyzeIdentityImage({ imageDataUrl: DATA_URL, providerId: 'p1', model: 'm' });
+ expect(r.error).toMatch(/empty response/);
+ });
+
+ it('returns parsed descriptors on success', async () => {
+ const r = await analyzeIdentityImage({ imageDataUrl: DATA_URL, providerId: 'p1', model: 'm' });
+ expect(r.error).toBeUndefined();
+ expect(r.suggestedDocument.filename).toBe('APPEARANCE.md');
+ expect(describeImageDataUrl).toHaveBeenCalledWith(
+ expect.objectContaining({ dataUrl: DATA_URL, prompt: 'PROMPT', providerId: 'p1', model: 'm' })
+ );
+ });
+});
+
+describe('saveIdentityImageDocument', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('errors when there is no content to save', async () => {
+ const r = await saveIdentityImageDocument({ content: ' ' });
+ expect(r.error).toMatch(/No document content/);
+ });
+
+ it('creates a new document when APPEARANCE.md does not exist', async () => {
+ loadMeta.mockResolvedValue({ documents: [] });
+ createDocument.mockResolvedValue({ id: 'new', filename: 'APPEARANCE.md' });
+ const r = await saveIdentityImageDocument({ content: '## Appearance\nstuff' });
+ expect(createDocument).toHaveBeenCalledWith(expect.objectContaining({
+ filename: 'APPEARANCE.md', category: 'core', enabled: true
+ }));
+ expect(r.filename).toBe('APPEARANCE.md');
+ });
+
+ it('updates the existing document when APPEARANCE.md is present', async () => {
+ loadMeta.mockResolvedValue({ documents: [{ id: 'existing', filename: 'APPEARANCE.md' }] });
+ updateDocument.mockResolvedValue({ id: 'existing', filename: 'APPEARANCE.md' });
+ await saveIdentityImageDocument({ content: '## Appearance\nupdated', title: 'My Look' });
+ expect(updateDocument).toHaveBeenCalledWith('existing', expect.objectContaining({
+ content: '## Appearance\nupdated', title: 'My Look'
+ }));
+ expect(createDocument).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/digital-twin.js b/server/services/digital-twin.js
index 84752bb2e1..37ebd09570 100644
--- a/server/services/digital-twin.js
+++ b/server/services/digital-twin.js
@@ -115,6 +115,12 @@ export {
parseStyleComparison
} from './digital-twin-style-comparison.js';
+export {
+ analyzeIdentityImage,
+ saveIdentityImageDocument,
+ parseIdentityImage
+} from './digital-twin-image-identity.js';
+
export {
analyzeImportedData,
saveImportAsDocument,