Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add behavioral feedback loop with identity validation (M34 P3)
Adam Eivy7969d1d4c473
diff --git a/.changelog/v1.7.x.md b/.changelog/v1.7.x.mdindex c126891752..a475e95386 100644--- a/.changelog/v1.7.x.md+++ b/.changelog/v1.7.x.md@@ -4,7 +4,7 @@ Released: YYYY-MM-DD## Overview-Personalized taste prompting and expanded aesthetic domains for the Digital Twin.+Personalized taste prompting, behavioral feedback loop, and expanded aesthetic domains for the Digital Twin.## Features@@ -20,3 +20,10 @@ Personalized taste prompting and expanded aesthetic domains for the Digital Twin- **Fashion & Texture** (`fashion`): material/fabric preferences, color wardrobe, formality spectrum, style identity, anti-fashion positions — with follow-ups for texture sensitivity, natural materials, minimalist wardrobe, color expression, and vintage aesthetics- **Digital & Interface** (`digital`): dark/light mode preferences, information density, animation tolerance, tool aesthetics, notification/attention style — with follow-ups for dark mode specifics, minimal vs dense UI, software craftsmanship, and digital focus management- Total taste sections expanded from 5 to 7++### Behavioral Feedback Loop (M34 P3)+- "Sounds like me" / "Not quite" / "Not me" validation buttons on behavioral test responses and taste profile summaries+- Feedback stored with content type, snippet, provider/model attribution, and timestamp+- Feedback statistics dashboard in TestTab: total ratings, validation rate percentage, per-validation breakdown, and recent accuracy trend (improving/declining/stable)+- Document weight recalculation from feedback history — documents consistently associated with validated responses get boosted, contradicted ones get reduced+- New API endpoints: `POST /api/digital-twin/feedback`, `GET /api/digital-twin/feedback/stats`, `POST /api/digital-twin/feedback/recalculate`, `GET /api/digital-twin/feedback/recent`diff --git a/PLAN.md b/PLAN.mdindex 558bd25035..e2f1ddb737 100644--- a/PLAN.md+++ b/PLAN.md@@ -161,5 +161,5 @@ All 10 audit items (S1–S10) from the 2025-02-19 security audit have been resol1. ~~**M42 P1: Identity Orchestrator & Chronotype**~~ ✅ - Identity service, chronotype derivation from genome sleep/caffeine markers, 4 API endpoints, 36 tests2. ~~**M42 P2.5: Personalized Taste Prompting**~~ ✅ - LLM-personalized follow-ups using identity context, 2 new taste sections (Fashion & Digital), "Go Deeper" flow3. **M7: App Templates** - Implement template management UI and app scaffolding from templates-4. **M34 P3: Behavioral Feedback Loop** - Add "sounds like me" response validation and adaptive weighting+4. ~~**M34 P3: Behavioral Feedback Loop**~~ ✅ - "Sounds like me" validation on test responses and taste summaries, feedback stats dashboard, document weight recalculation5. **M42 P3: Mortality-Aware Goal Tracking** - Birth date + genome longevity markers for urgency-scored goalsdiff --git a/client/src/components/digital-twin/tabs/TasteTab.jsx b/client/src/components/digital-twin/tabs/TasteTab.jsxindex 3f4c7b7798..eb17e14ab9 100644--- a/client/src/components/digital-twin/tabs/TasteTab.jsx+++ b/client/src/components/digital-twin/tabs/TasteTab.jsx@@ -18,7 +18,10 @@ import {Eye,ChevronDown,ChevronUp,- Telescope+ Telescope,+ ThumbsUp,+ ThumbsDown,+ Minus} from 'lucide-react';import * as api from '../../../services/api';import toast from 'react-hot-toast';@@ -68,6 +71,9 @@ export default function TasteTab({ onRefresh }) {const [personalizedQuestion, setPersonalizedQuestion] = useState(null);const [loadingPersonalized, setLoadingPersonalized] = useState(false);+ // Behavioral feedback+ const [summaryFeedback, setSummaryFeedback] = useState({}); // key: sectionId → validation+// Expanded summariesconst [expandedSummary, setExpandedSummary] = useState(null);@@ -211,6 +217,21 @@ export default function TasteTab({ onRefresh }) {setGeneratingSummary(false);};+ const submitSummaryFeedback = async (sectionId, summary, validation) => {+ setSummaryFeedback(prev => ({ ...prev, [sectionId]: validation }));+ await api.submitBehavioralFeedback({+ contentType: 'taste_summary',+ validation,+ contentSnippet: summary,+ context: `Taste section: ${sectionId}`,+ providerId: selectedProvider?.providerId,+ model: selectedProvider?.model+ }).catch(() => {+ toast.error('Failed to save feedback');+ setSummaryFeedback(prev => { const next = { ...prev }; delete next[sectionId]; return next; });+ });+ };+const handleGenerateOverallSummary = async () => {if (!selectedProvider) {toast.error('Select a provider first');@@ -293,7 +314,33 @@ export default function TasteTab({ onRefresh }) {<Sparkles size={14} />AI Summary</h3>- <div className="text-gray-300 text-sm whitespace-pre-wrap">{section.summary}</div>+ <div className="text-gray-300 text-sm whitespace-pre-wrap mb-3">{section.summary}</div>++ {/* Behavioral Feedback */}+ <div className="pt-3 border-t border-port-border">+ <p className="text-xs text-gray-500 mb-2">Does this summary capture your taste accurately?</p>+ <div className="flex items-center gap-2">+ {[+ { key: 'sounds_like_me', label: 'Sounds like me', icon: ThumbsUp, color: 'green' },+ { key: 'not_quite', label: 'Not quite', icon: Minus, color: 'yellow' },+ { key: 'doesnt_sound_like_me', label: 'Not me', icon: ThumbsDown, color: 'red' }+ ].map(({ key, label, icon: FbIcon, color }) => (+ <button+ key={key}+ onClick={() => submitSummaryFeedback(reviewSection, section.summary, key)}+ disabled={!!summaryFeedback[reviewSection]}+ className={`flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] rounded-lg text-xs transition-colors ${+ summaryFeedback[reviewSection] === key+ ? `bg-${color}-500/20 text-${color}-400 border border-${color}-500/30`+ : `text-gray-400 border border-port-border hover:text-${color}-400 hover:border-${color}-500/30 disabled:opacity-30`+ }`}+ >+ <FbIcon size={14} />+ {label}+ </button>+ ))}+ </div>+ </div></div>)}diff --git a/client/src/components/digital-twin/tabs/TestTab.jsx b/client/src/components/digital-twin/tabs/TestTab.jsxindex 738d345057..ead9f68bd0 100644--- a/client/src/components/digital-twin/tabs/TestTab.jsx+++ b/client/src/components/digital-twin/tabs/TestTab.jsx@@ -10,7 +10,11 @@ import {RefreshCw,History,Wand2,- Plus+ Plus,+ ThumbsUp,+ ThumbsDown,+ Minus,+ TrendingUp} from 'lucide-react';import * as api from '../../../services/api';import toast from 'react-hot-toast';@@ -37,22 +41,28 @@ export default function TestTab({ onRefresh }) {const [generating, setGenerating] = useState(false);const [showGenerated, setShowGenerated] = useState(false);+ // Behavioral feedback+ const [feedbackGiven, setFeedbackGiven] = useState({}); // key: `${providerId}:${model}:${testId}` → validation+ const [feedbackStats, setFeedbackStats] = useState(null);+useEffect(() => {loadData();}, []);const loadData = async () => {setLoading(true);- const [testsData, providersData, historyData] = await Promise.all([+ const [testsData, providersData, historyData, fbStats] = await Promise.all([api.getSoulTests().catch(() => []),api.getProviders().catch(() => ({ providers: [] })),- api.getSoulTestHistory(5).catch(() => [])+ api.getSoulTestHistory(5).catch(() => []),+ api.getBehavioralFeedbackStats().catch(() => null)]);setTests(testsData);const providersList = providersData.providers || [];setProviders(providersList.filter(p => p.enabled));setHistory(historyData);+ if (fbStats) setFeedbackStats(fbStats);// Default: select all testssetSelectedTests(testsData.map(t => t.testId));@@ -60,6 +70,27 @@ export default function TestTab({ onRefresh }) {setLoading(false);};+ const submitFeedback = async (providerId, model, testId, testName, response, validation) => {+ const key = `${providerId}:${model}:${testId}`;+ setFeedbackGiven(prev => ({ ...prev, [key]: validation }));++ await api.submitBehavioralFeedback({+ contentType: 'test_response',+ validation,+ contentSnippet: response,+ context: `Test: ${testName} | Model: ${model}`,+ providerId,+ model+ }).catch(() => {+ toast.error('Failed to save feedback');+ setFeedbackGiven(prev => { const next = { ...prev }; delete next[key]; return next; });+ });++ // Refresh stats+ const fbStats = await api.getBehavioralFeedbackStats().catch(() => null);+ if (fbStats) setFeedbackStats(fbStats);+ };+const toggleProvider = (providerId, model) => {const key = `${providerId}:${model}`;setSelectedProviders(prev => {@@ -445,6 +476,9 @@ export default function TestTab({ onRefresh }) {const testResult = r.results?.find(tr => tr.testId === expandedTest);if (!testResult) return null;+ const fbKey = `${r.providerId}:${r.model}:${expandedTest}`;+ const currentFeedback = feedbackGiven[fbKey];+return (<div key={`${r.providerId}-${r.model}-response`}><h4 className="text-sm font-medium text-gray-400 mb-1">@@ -457,6 +491,49 @@ export default function TestTab({ onRefresh }) {Reasoning: {testResult.reasoning}</p>)}++ {/* Behavioral Feedback */}+ <div className="mt-3 pt-3 border-t border-port-border">+ <p className="text-xs text-gray-500 mb-2">Does this response sound like you?</p>+ <div className="flex items-center gap-2">+ <button+ onClick={() => submitFeedback(r.providerId, r.model, expandedTest, test.testName, testResult.response, 'sounds_like_me')}+ disabled={!!currentFeedback}+ className={`flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] rounded-lg text-xs transition-colors ${+ currentFeedback === 'sounds_like_me'+ ? 'bg-green-500/20 text-green-400 border border-green-500/30'+ : 'text-gray-400 border border-port-border hover:text-green-400 hover:border-green-500/30 disabled:opacity-30'+ }`}+ >+ <ThumbsUp size={14} />+ Sounds like me+ </button>+ <button+ onClick={() => submitFeedback(r.providerId, r.model, expandedTest, test.testName, testResult.response, 'not_quite')}+ disabled={!!currentFeedback}+ className={`flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] rounded-lg text-xs transition-colors ${+ currentFeedback === 'not_quite'+ ? 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30'+ : 'text-gray-400 border border-port-border hover:text-yellow-400 hover:border-yellow-500/30 disabled:opacity-30'+ }`}+ >+ <Minus size={14} />+ Not quite+ </button>+ <button+ onClick={() => submitFeedback(r.providerId, r.model, expandedTest, test.testName, testResult.response, 'doesnt_sound_like_me')}+ disabled={!!currentFeedback}+ className={`flex items-center gap-1.5 px-3 py-1.5 min-h-[36px] rounded-lg text-xs transition-colors ${+ currentFeedback === 'doesnt_sound_like_me'+ ? 'bg-red-500/20 text-red-400 border border-red-500/30'+ : 'text-gray-400 border border-port-border hover:text-red-400 hover:border-red-500/30 disabled:opacity-30'+ }`}+ >+ <ThumbsDown size={14} />+ Not me+ </button>+ </div>+ </div></div></div>);@@ -501,6 +578,58 @@ export default function TestTab({ onRefresh }) {</div></div>)}++ {/* Behavioral Feedback Stats */}+ {feedbackStats && feedbackStats.totalFeedback > 0 && (+ <div className="bg-port-card rounded-lg border border-port-border p-4">+ <h3 className="font-semibold text-white mb-4 flex items-center gap-2">+ <TrendingUp size={18} className="text-purple-400" />+ Identity Validation+ </h3>+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">+ <div className="p-3 bg-port-bg rounded-lg text-center">+ <div className="text-2xl font-bold text-white">{feedbackStats.totalFeedback}</div>+ <div className="text-xs text-gray-500">Total Ratings</div>+ </div>+ <div className="p-3 bg-port-bg rounded-lg text-center">+ <div className={`text-2xl font-bold ${+ feedbackStats.validationRate >= 0.7 ? 'text-green-400' :+ feedbackStats.validationRate >= 0.4 ? 'text-yellow-400' : 'text-red-400'+ }`}>+ {feedbackStats.validationRate != null ? `${Math.round(feedbackStats.validationRate * 100)}%` : '—'}+ </div>+ <div className="text-xs text-gray-500">Validation Rate</div>+ </div>+ <div className="p-3 bg-port-bg rounded-lg text-center">+ <div className="text-2xl font-bold text-green-400">+ {feedbackStats.byValidation?.sounds_like_me || 0}+ </div>+ <div className="text-xs text-gray-500">Sounds Like Me</div>+ </div>+ <div className="p-3 bg-port-bg rounded-lg text-center">+ <div className="text-2xl font-bold text-red-400">+ {feedbackStats.byValidation?.doesnt_sound_like_me || 0}+ </div>+ <div className="text-xs text-gray-500">Not Me</div>+ </div>+ </div>++ {feedbackStats.recentTrend && feedbackStats.recentTrend.direction !== 'insufficient_data' && (+ <div className={`p-3 rounded-lg text-sm ${+ feedbackStats.recentTrend.direction === 'improving' ? 'bg-green-500/10 text-green-400' :+ feedbackStats.recentTrend.direction === 'declining' ? 'bg-red-500/10 text-red-400' :+ 'bg-port-bg text-gray-400'+ }`}>+ {feedbackStats.recentTrend.direction === 'improving'+ ? `Twin accuracy is improving: ${feedbackStats.recentTrend.previousRate}% → ${feedbackStats.recentTrend.recentRate}% (+${feedbackStats.recentTrend.delta}%)`+ : feedbackStats.recentTrend.direction === 'declining'+ ? `Twin accuracy needs attention: ${feedbackStats.recentTrend.previousRate}% → ${feedbackStats.recentTrend.recentRate}% (${feedbackStats.recentTrend.delta}%)`+ : `Twin accuracy is stable at ${feedbackStats.recentTrend.recentRate}%`+ }+ </div>+ )}+ </div>+ )}</div>);}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 82c9035f1c..63ae36f95c 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1081,6 +1081,22 @@ export const saveDigitalTwinImport = (source, suggestedDoc) => request('/digitalbody: JSON.stringify({ source, suggestedDoc })});+// Digital Twin - Behavioral Feedback Loop+export const submitBehavioralFeedback = (data) => request('/digital-twin/feedback', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const getBehavioralFeedbackStats = () => request('/digital-twin/feedback/stats');+export const recalculateFeedbackWeights = () => request('/digital-twin/feedback/recalculate', {+ method: 'POST'+});+export const getRecentFeedback = (contentType, limit) => {+ const params = new URLSearchParams();+ if (contentType) params.set('contentType', contentType);+ if (limit) params.set('limit', limit);+ return request(`/digital-twin/feedback/recent?${params}`);+};+// Digital Twin - Taste Questionnaireexport const getTasteProfile = () => request('/digital-twin/taste');export const getTasteSections = () => request('/digital-twin/taste/sections');diff --git a/package-lock.json b/package-lock.jsonindex 51d837baf1..09230fe75a 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "portos",- "version": "1.7.1",+ "version": "1.7.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "portos",- "version": "1.7.1",+ "version": "1.7.2","license": "MIT","dependencies": {"express": "^4.21.2",diff --git a/package.json b/package.jsonindex 3962b43f7c..8a82f1b156 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "portos",- "version": "1.7.1",+ "version": "1.7.2","private": true,"description": "Local dev machine App OS portal","author": "Adam Eivy (@antic|@atomantic)",diff --git a/server/lib/digitalTwinValidation.js b/server/lib/digitalTwinValidation.jsindex 7db795566b..4699f56970 100644--- a/server/lib/digitalTwinValidation.js+++ b/server/lib/digitalTwinValidation.js@@ -425,3 +425,23 @@ export const tasteSummaryInputSchema = z.object({providerId: z.string().min(1),model: z.string().min(1)});++// --- Behavioral Feedback Loop Schemas (M34 P3) ---++export const feedbackContentTypeEnum = z.enum([+ 'test_response', 'taste_summary', 'enrichment', 'export'+]);++export const feedbackValidationEnum = z.enum([+ 'sounds_like_me', 'not_quite', 'doesnt_sound_like_me'+]);++export const feedbackInputSchema = z.object({+ contentType: feedbackContentTypeEnum,+ validation: feedbackValidationEnum,+ contentSnippet: z.string().min(1).max(2000),+ context: z.string().max(500).optional(),+ providerId: z.string().min(1).optional(),+ model: z.string().min(1).optional(),+ documentsUsed: z.array(z.string()).optional()+});diff --git a/server/routes/digital-twin.js b/server/routes/digital-twin.jsindex c029ee73f0..87208b3b42 100644--- a/server/routes/digital-twin.js+++ b/server/routes/digital-twin.js@@ -12,6 +12,7 @@import { Router } from 'express';import * as digitalTwinService from '../services/digital-twin.js';import * as tasteService from '../services/taste-questionnaire.js';+import * as feedbackService from '../services/feedbackLoop.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import {@@ -38,7 +39,8 @@ import {tasteAnswerInputSchema,tasteSummaryInputSchema,tasteSectionEnum,- tastePersonalizedQuestionInputSchema+ tastePersonalizedQuestionInputSchema,+ feedbackInputSchema} from '../lib/digitalTwinValidation.js';const router = Router();@@ -471,6 +473,49 @@ router.post('/import/save', asyncHandler(async (req, res) => {res.json({ document, message: 'Document saved successfully' });}));+// =============================================================================+// BEHAVIORAL FEEDBACK LOOP (M34 P3)+// =============================================================================++/**+ * POST /api/digital-twin/feedback+ * Submit a "sounds like me" / "doesn't sound like me" validation+ */+router.post('/feedback', asyncHandler(async (req, res) => {+ const data = validateRequest(feedbackInputSchema, req.body);+ const entry = await feedbackService.submitFeedback(data);+ res.json(entry);+}));++/**+ * GET /api/digital-twin/feedback/stats+ * Get feedback statistics and analysis+ */+router.get('/feedback/stats', asyncHandler(async (req, res) => {+ const stats = await feedbackService.getFeedbackStats();+ res.json(stats);+}));++/**+ * POST /api/digital-twin/feedback/recalculate+ * Recalculate document weight adjustments from feedback history+ */+router.post('/feedback/recalculate', asyncHandler(async (req, res) => {+ const result = await feedbackService.recalculateWeights();+ res.json(result);+}));++/**+ * GET /api/digital-twin/feedback/recent+ * Get recent feedback entries (optionally filtered by content type)+ */+router.get('/feedback/recent', asyncHandler(async (req, res) => {+ const contentType = req.query.contentType || null;+ const limit = Math.min(parseInt(req.query.limit) || 20, 50);+ const entries = await feedbackService.getRecentFeedback(contentType, limit);+ res.json(entries);+}));+// =============================================================================// TASTE QUESTIONNAIRE// =============================================================================diff --git a/server/services/feedbackLoop.js b/server/services/feedbackLoop.jsnew file mode 100644index 0000000000..b4dd173adf--- /dev/null+++ b/server/services/feedbackLoop.js@@ -0,0 +1,271 @@+/**+ * Behavioral Feedback Loop Service (M34 P3)+ *+ * Captures "sounds like me" / "doesn't sound like me" validations on+ * AI-generated content (test responses, taste summaries, enrichment output).+ * Tracks feedback patterns and adjusts document weights for confidence scoring.+ */++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 { safeJSONParse } from '../lib/fileUtils.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 FEEDBACK_FILE = join(DIGITAL_TWIN_DIR, 'feedback.json');++function now() {+ return new Date().toISOString();+}++// =============================================================================+// DATA ACCESS+// =============================================================================++let feedbackCache = null;++async function loadFeedback() {+ if (feedbackCache) return feedbackCache;++ const defaultData = {+ version: '1.0.0',+ entries: [],+ stats: { totalFeedback: 0, soundsLikeMe: 0, doesntSoundLikeMe: 0 },+ documentWeightAdjustments: {},+ lastCalculatedAt: null+ };++ if (!existsSync(FEEDBACK_FILE)) {+ await saveFeedback(defaultData);+ return defaultData;+ }++ const raw = await readFile(FEEDBACK_FILE, 'utf-8');+ feedbackCache = safeJSONParse(raw, defaultData);+ return feedbackCache;+}++async function saveFeedback(data) {+ if (!existsSync(DIGITAL_TWIN_DIR)) {+ await mkdir(DIGITAL_TWIN_DIR, { recursive: true });+ }+ data.updatedAt = now();+ await writeFile(FEEDBACK_FILE, JSON.stringify(data, null, 2));+ feedbackCache = data;+}++// =============================================================================+// PUBLIC API+// =============================================================================++/**+ * Submit a "sounds like me" or "doesn't sound like me" feedback entry.+ *+ * @param {Object} params+ * @param {string} params.contentType - 'test_response' | 'taste_summary' | 'enrichment' | 'export'+ * @param {string} params.validation - 'sounds_like_me' | 'not_quite' | 'doesnt_sound_like_me'+ * @param {string} params.contentSnippet - The AI-generated text being validated (first 500 chars)+ * @param {string} [params.context] - Additional context (test name, section id, etc.)+ * @param {string} [params.providerId] - Which provider generated the content+ * @param {string} [params.model] - Which model generated the content+ * @param {string[]} [params.documentsUsed] - Which twin documents influenced the response+ */+export async function submitFeedback({ contentType, validation, contentSnippet, context, providerId, model, documentsUsed }) {+ const data = await loadFeedback();++ const entry = {+ id: uuidv4(),+ contentType,+ validation,+ contentSnippet: (contentSnippet || '').slice(0, 500),+ context: context || null,+ providerId: providerId || null,+ model: model || null,+ documentsUsed: documentsUsed || [],+ createdAt: now()+ };++ data.entries.push(entry);++ // Update running stats+ data.stats.totalFeedback++;+ if (validation === 'sounds_like_me') data.stats.soundsLikeMe++;+ else if (validation === 'doesnt_sound_like_me') data.stats.doesntSoundLikeMe++;++ // Keep last 500 entries to prevent unbounded growth+ if (data.entries.length > 500) {+ data.entries = data.entries.slice(-500);+ }++ await saveFeedback(data);++ digitalTwinEvents.emit('feedback:submitted', entry);+ console.log(`🔄 Feedback submitted: ${validation} on ${contentType} (${data.stats.totalFeedback} total)`);++ return entry;+}++/**+ * Get feedback statistics and analysis.+ */+export async function getFeedbackStats() {+ const data = await loadFeedback();+ const entries = data.entries;++ if (entries.length === 0) {+ return {+ totalFeedback: 0,+ validationRate: null,+ byContentType: {},+ byValidation: {},+ recentTrend: null,+ documentWeightAdjustments: {},+ lastCalculatedAt: data.lastCalculatedAt+ };+ }++ // Aggregate by content type+ const byContentType = {};+ for (const e of entries) {+ if (!byContentType[e.contentType]) {+ byContentType[e.contentType] = { total: 0, sounds_like_me: 0, not_quite: 0, doesnt_sound_like_me: 0 };+ }+ byContentType[e.contentType].total++;+ byContentType[e.contentType][e.validation]++;+ }++ // Aggregate by validation type+ const byValidation = { sounds_like_me: 0, not_quite: 0, doesnt_sound_like_me: 0 };+ for (const e of entries) {+ byValidation[e.validation]++;+ }++ // Validation rate = sounds_like_me / total+ const validationRate = entries.length > 0+ ? Math.round((byValidation.sounds_like_me / entries.length) * 100) / 100+ : null;++ // Recent trend: compare last 20 vs previous 20+ let recentTrend = null;+ if (entries.length >= 20) {+ const recent20 = entries.slice(-20);+ const previous20 = entries.slice(-40, -20);++ const recentRate = recent20.filter(e => e.validation === 'sounds_like_me').length / 20;++ if (previous20.length >= 10) {+ const prevRate = previous20.filter(e => e.validation === 'sounds_like_me').length / previous20.length;+ const delta = Math.round((recentRate - prevRate) * 100);+ recentTrend = {+ direction: delta > 2 ? 'improving' : delta < -2 ? 'declining' : 'stable',+ recentRate: Math.round(recentRate * 100),+ previousRate: Math.round(prevRate * 100),+ delta+ };+ } else {+ recentTrend = {+ direction: 'insufficient_data',+ recentRate: Math.round(recentRate * 100)+ };+ }+ }++ // Per-provider breakdown+ const byProvider = {};+ for (const e of entries) {+ const key = e.model || e.providerId || 'unknown';+ if (!byProvider[key]) {+ byProvider[key] = { total: 0, sounds_like_me: 0, not_quite: 0, doesnt_sound_like_me: 0 };+ }+ byProvider[key].total++;+ byProvider[key][e.validation]++;+ }++ return {+ totalFeedback: entries.length,+ validationRate,+ byContentType,+ byValidation,+ byProvider,+ recentTrend,+ documentWeightAdjustments: data.documentWeightAdjustments,+ lastCalculatedAt: data.lastCalculatedAt+ };+}++/**+ * Recalculate document weight adjustments based on feedback history.+ *+ * Documents that consistently appear in "sounds like me" responses get boosted.+ * Documents that appear in "doesn't sound like me" responses get reduced.+ * Returns the new weight adjustments (deltas from base weight).+ */+export async function recalculateWeights() {+ const data = await loadFeedback();+ const entries = data.entries.filter(e => e.documentsUsed?.length > 0);++ if (entries.length < 5) {+ return { adjustments: {}, message: 'Need at least 5 feedback entries with document attribution to calculate weights' };+ }++ // Track per-document validation counts+ const docScores = {};+ for (const e of entries) {+ for (const doc of e.documentsUsed) {+ if (!docScores[doc]) docScores[doc] = { positive: 0, neutral: 0, negative: 0, total: 0 };+ docScores[doc].total++;+ if (e.validation === 'sounds_like_me') docScores[doc].positive++;+ else if (e.validation === 'not_quite') docScores[doc].neutral++;+ else docScores[doc].negative++;+ }+ }++ // Calculate weight adjustments+ const adjustments = {};+ for (const [doc, scores] of Object.entries(docScores)) {+ if (scores.total < 3) continue; // Need minimum data points++ const ratio = (scores.positive - scores.negative) / scores.total;++ // Adjustment: +1 for strongly positive docs, -1 for strongly negative+ // Scale: ratio ranges from -1 to +1, map to weight delta of -2 to +2+ const delta = Math.round(ratio * 2 * 10) / 10;+ if (Math.abs(delta) >= 0.5) {+ adjustments[doc] = {+ delta,+ confidence: Math.min(1, scores.total / 10), // How confident we are in this adjustment+ positive: scores.positive,+ negative: scores.negative,+ total: scores.total+ };+ }+ }++ data.documentWeightAdjustments = adjustments;+ data.lastCalculatedAt = now();+ await saveFeedback(data);++ digitalTwinEvents.emit('feedback:weights-recalculated', adjustments);+ console.log(`🔄 Feedback weights recalculated: ${Object.keys(adjustments).length} documents adjusted`);++ return { adjustments };+}++/**+ * Get feedback entries for a specific content type (for UI display).+ */+export async function getRecentFeedback(contentType, limit = 20) {+ const data = await loadFeedback();+ let entries = data.entries;++ if (contentType) {+ entries = entries.filter(e => e.contentType === contentType);+ }++ return entries.slice(-limit).reverse();+}