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 POST (Power On Self Test) — cognitive self-test system
Adam Eivyfe6148d4dd6f
diff --git a/PLAN.md b/PLAN.mdindex ce5f97dc6c..4f2afe7d3e 100644--- a/PLAN.md+++ b/PLAN.md@@ -80,6 +80,7 @@ pm2 logs### In Progress- [ ] **M44 P6**: MeatSpace - Genome/Epigenetic Migration cleanup (genome routes moved, but route comments still reference `/api/digital-twin/genome/` and IdentityTab still renders a Genome card with broken link to `/digital-twin/genome`)+- [ ] **M53 P1**: POST (Power On Self Test) - Foundation + Mental Math (daily cognitive self-test with 5 drill types, scoring, history, config). Phase 1 complete: server service/routes/tests, client UI with drill runner, results, history charts, config editor### Planned@@ -119,6 +120,7 @@ Check via `existsSync()` against `app.repoPath + '/.planning/...'` (same pattern- [ ] **M48 P1-P4**: Google Calendar Integration - OAuth2, two-way event sync, chronotype-aware smart scheduling, CoS autonomous rescheduling, calendar UI with week/month views- [ ] **M49 P1-P4**: Life Goals & Todo Planning - Enhanced goal model with todos and milestones, calendar time-blocking, AI-powered periodic check-ins, mortality-aware progress dashboard- [ ] **M50 P1-P4**: Email Management - Gmail + Outlook integration, AI categorization and priority extraction, Digital Twin voice drafting, review-before-send outbox, Brain knowledge capture+- [ ] **M52**: Update Detection - Poll GitHub releases for new version tags, compare against local `package.json` version, surface update availability in dashboard and settings---@@ -302,6 +304,32 @@ M49 P1 (Enhanced Goals + Todos) — independent, no deps*Touches: new server/services/email.js, server/services/emailProvider.js, server/services/emailClassifier.js, server/services/emailDrafter.js, server/routes/email.js, client/src/pages/Email.jsx, client/src/components/email/tabs/, Layout.jsx, brain.js, autonomousJobs.js, portos-ai-toolkit (Digital Twin context for drafting)*+### M52: Update Detection++Check for new PortOS releases on GitHub and notify the user when an update is available.++**Version Check**+- Scheduled service polls `GET https://api.github.com/repos/atomantic/PortOS/releases/latest` (or tags endpoint) on a configurable interval (default: daily)+- Compare remote latest tag against local version from `package.json`+- Semver comparison — only flag when remote is newer (ignore pre-release tags unless opted in)+- Cache last-checked timestamp and latest remote version in `data/settings.json` or `data/update-check.json`++**UI Notifications**+- Dashboard widget: subtle banner when update available showing current vs. latest version+- Settings page: "Check for Updates" button with last-checked timestamp, auto-check toggle, and interval config+- Sidebar badge or indicator on Settings nav item when update is pending++**Update Action**+- Display release notes summary (fetched from GitHub release body)+- "View Release" link opens GitHub release page+- Optional: show one-liner shell command to pull the update (`git pull && npm run install:all && pm2 restart ecosystem.config.cjs`)++**Routes:** `GET /api/system/update-check` (returns current version, latest version, update available boolean, release notes), `POST /api/system/update-check` (trigger manual check)++**Nav:** No new nav item — surfaces in Dashboard widget and Settings page++*Touches: new server/services/updateCheck.js, server/routes/system.js, Dashboard.jsx (update banner widget), Settings page (update check section), data/update-check.json*+### Tier 1: Identity Integration (aligns with M42 direction)- **Chronotype-Aware Scheduling** — Chronotype derivation exists (M42 P1) but isn't applied to task scheduling yet. Use peak-focus windows from genome sleep markers to schedule deep-work tasks during peak hours, routine tasks during low-energy. Display energy curve on Schedule tab. *Touches: taskSchedule.js, genome.js, CoS Schedule tab*@@ -387,3 +415,4 @@ All 10 audit items (S1–S10) from the 2025-02-19 security audit have been resol6. **M48 P1**: Google Calendar — OAuth2 foundation + calendar read7. **M49 P1**: Life Goals — Enhanced goal model with todos and progress tracking8. **M48 P2**: Google Calendar — Event CRUD and two-way sync+9. **M52**: Update Detection — GitHub release polling and update notificationdiff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex ad311690f3..114bed1d45 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -55,7 +55,8 @@ import {Github,Link2,Database,- Shield+ Shield,+ Zap} from 'lucide-react';import packageJson from '../../package.json';import Logo from './Logo';@@ -163,7 +164,8 @@ const navItems = [{ to: '/meatspace/health', label: 'Health', icon: Heart },{ to: '/meatspace/import', label: 'Import', icon: Upload },{ to: '/meatspace/lifestyle', label: 'Lifestyle', icon: ClipboardList },- { to: '/meatspace/overview', label: 'Overview', icon: Activity }+ { to: '/meatspace/overview', label: 'Overview', icon: Activity },+ { to: '/meatspace/post', label: 'POST', icon: Zap }]},{ to: '/security', label: 'Security', icon: Camera, single: true },diff --git a/client/src/components/meatspace/constants.js b/client/src/components/meatspace/constants.jsindex 5ba1248cc5..b837c0a371 100644--- a/client/src/components/meatspace/constants.js+++ b/client/src/components/meatspace/constants.js@@ -9,7 +9,8 @@ import {Activity,Scale,Stethoscope,- Upload+ Upload,+ Zap} from 'lucide-react';export const TABS = [@@ -22,7 +23,8 @@ export const TABS = [{ id: 'genome', label: 'Genome', icon: Dna },{ id: 'health', label: 'Health', icon: Stethoscope },{ id: 'import', label: 'Import', icon: Upload },- { id: 'lifestyle', label: 'Lifestyle', icon: ClipboardList }+ { id: 'lifestyle', label: 'Lifestyle', icon: ClipboardList },+ { id: 'post', label: 'POST', icon: Zap }];// Lifestyle adjustment table for death clockdiff --git a/client/src/components/meatspace/post/PostDrillConfig.jsx b/client/src/components/meatspace/post/PostDrillConfig.jsxnew file mode 100644index 0000000000..74ef27b377--- /dev/null+++ b/client/src/components/meatspace/post/PostDrillConfig.jsx@@ -0,0 +1,151 @@+import { useState } from 'react';+import { ArrowLeft, Save } from 'lucide-react';+import { updatePostConfig } from '../../../services/api';+import toast from 'react-hot-toast';++const DRILL_META = {+ 'doubling-chain': {+ label: 'Doubling Chain',+ desc: 'Double a number repeatedly',+ fields: [+ { key: 'steps', label: 'Steps', type: 'number', min: 3, max: 20 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 }+ ]+ },+ 'serial-subtraction': {+ label: 'Serial Subtraction',+ desc: 'Subtract a number repeatedly',+ fields: [+ { key: 'steps', label: 'Steps', type: 'number', min: 3, max: 30 },+ { key: 'subtrahend', label: 'Subtract By', type: 'number', min: 1, max: 100 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 }+ ]+ },+ 'multiplication': {+ label: 'Multiplication',+ desc: 'Multiply random numbers',+ fields: [+ { key: 'count', label: 'Questions', type: 'number', min: 3, max: 30 },+ { key: 'maxDigits', label: 'Max Digits', type: 'number', min: 1, max: 4 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 600 }+ ]+ },+ 'powers': {+ label: 'Powers',+ desc: 'Calculate base^exponent',+ fields: [+ { key: 'count', label: 'Questions', type: 'number', min: 3, max: 20 },+ { key: 'maxExponent', label: 'Max Exponent', type: 'number', min: 2, max: 20 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 300 }+ ]+ },+ 'estimation': {+ label: 'Estimation',+ desc: 'Approximate arithmetic results',+ fields: [+ { key: 'count', label: 'Questions', type: 'number', min: 3, max: 20 },+ { key: 'tolerancePct', label: 'Tolerance %', type: 'number', min: 1, max: 50 },+ { key: 'timeLimitSec', label: 'Time Limit (sec)', type: 'number', min: 10, max: 600 }+ ]+ }+};++export default function PostDrillConfig({ config, onSaved, onBack }) {+ const [drillTypes, setDrillTypes] = useState(+ () => config?.mentalMath?.drillTypes || {}+ );+ const [saving, setSaving] = useState(false);++ function toggleDrill(type) {+ setDrillTypes(prev => ({+ ...prev,+ [type]: { ...prev[type], enabled: !prev[type]?.enabled }+ }));+ }++ function updateField(type, key, value) {+ setDrillTypes(prev => ({+ ...prev,+ [type]: { ...prev[type], [key]: Number(value) }+ }));+ }++ async function handleSave() {+ setSaving(true);+ const updated = await updatePostConfig({+ mentalMath: { drillTypes }+ });+ toast.success('POST config saved');+ setSaving(false);+ onSaved(updated);+ }++ return (+ <div className="space-y-6 max-w-2xl">+ {/* Header */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <ArrowLeft size={20} />+ </button>+ <h2 className="text-xl font-bold text-white">Drill Configuration</h2>+ </div>+ <button+ onClick={handleSave}+ disabled={saving}+ className="flex items-center gap-1.5 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"+ >+ <Save size={14} />+ {saving ? 'Saving...' : 'Save'}+ </button>+ </div>++ {/* Drill Cards */}+ {Object.entries(DRILL_META).map(([type, meta]) => {+ const drillConfig = drillTypes[type] || {};+ const enabled = drillConfig.enabled !== false;++ return (+ <div key={type} className={`bg-port-card border rounded-lg p-4 transition-colors ${+ enabled ? 'border-port-border' : 'border-port-border/50 opacity-60'+ }`}>+ <div className="flex items-center justify-between mb-3">+ <div>+ <h3 className="text-white font-medium">{meta.label}</h3>+ <p className="text-gray-500 text-xs">{meta.desc}</p>+ </div>+ <button+ onClick={() => toggleDrill(type)}+ className={`w-10 h-5 rounded-full transition-colors relative ${+ enabled ? 'bg-port-accent' : 'bg-port-border'+ }`}+ >+ <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${+ enabled ? 'translate-x-5' : 'translate-x-0.5'+ }`} />+ </button>+ </div>++ {enabled && (+ <div className="grid grid-cols-3 gap-3">+ {meta.fields.map(field => (+ <div key={field.key}>+ <label className="text-xs text-gray-500 mb-1 block">{field.label}</label>+ <input+ type="number"+ min={field.min}+ max={field.max}+ value={drillConfig[field.key] ?? ''}+ onChange={e => updateField(type, field.key, e.target.value)}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ ))}+ </div>+ )}+ </div>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/meatspace/post/PostDrillRunner.jsx b/client/src/components/meatspace/post/PostDrillRunner.jsxnew file mode 100644index 0000000000..9bbf785d1c--- /dev/null+++ b/client/src/components/meatspace/post/PostDrillRunner.jsx@@ -0,0 +1,156 @@+import { useState, useEffect, useRef, useCallback } from 'react';++const DRILL_LABELS = {+ 'doubling-chain': 'Doubling Chain',+ 'serial-subtraction': 'Serial Subtraction',+ 'multiplication': 'Multiplication',+ 'powers': 'Powers',+ 'estimation': 'Estimation'+};++export default function PostDrillRunner({ session }) {+ const {+ currentDrill,+ currentQuestionIndex,+ currentDrillIndex,+ drillCount,+ state,+ submitAnswer,+ skipQuestion,+ timeExpired+ } = session;++ const [inputValue, setInputValue] = useState('');+ const [timeLeft, setTimeLeft] = useState(0);+ const inputRef = useRef(null);+ const timerRef = useRef(null);++ const timeLimitMs = (currentDrill?.timeLimitSec || 120) * 1000;+ const totalQuestions = currentDrill?.questions?.length || 0;++ // Timer+ useEffect(() => {+ if (state !== 'drilling' || !currentDrill) return;++ const startTime = Date.now();+ setTimeLeft(timeLimitMs);++ timerRef.current = setInterval(() => {+ const elapsed = Date.now() - startTime;+ const remaining = Math.max(0, timeLimitMs - elapsed);+ setTimeLeft(remaining);+ if (remaining <= 0) {+ clearInterval(timerRef.current);+ timeExpired();+ }+ }, 100);++ return () => clearInterval(timerRef.current);+ }, [state, currentDrill, currentDrillIndex]);++ // Auto-focus input on question change+ useEffect(() => {+ setInputValue('');+ inputRef.current?.focus();+ }, [currentQuestionIndex, currentDrillIndex]);++ const handleSubmit = useCallback((e) => {+ e.preventDefault();+ if (inputValue.trim() === '') return;+ submitAnswer(inputValue.trim());+ }, [inputValue, submitAnswer]);++ if (state === 'loading') {+ return (+ <div className="flex items-center justify-center h-64">+ <div className="text-gray-400">Loading drill...</div>+ </div>+ );+ }++ if (state !== 'drilling' || !currentDrill) return null;++ const question = currentDrill.questions[currentQuestionIndex];+ const timePct = timeLimitMs > 0 ? (timeLeft / timeLimitMs) * 100 : 0;+ const progressPct = totalQuestions > 0 ? ((currentQuestionIndex) / totalQuestions) * 100 : 0;++ // Timer bar color+ let timerColor = 'bg-port-accent';+ if (timePct <= 10) timerColor = 'bg-port-error';+ else if (timePct <= 25) timerColor = 'bg-port-warning';++ return (+ <div className="max-w-lg mx-auto space-y-6">+ {/* Drill header */}+ <div className="flex items-center justify-between text-sm text-gray-400">+ <span>{DRILL_LABELS[currentDrill.type] || currentDrill.type}</span>+ <span>Drill {currentDrillIndex + 1} of {drillCount}</span>+ </div>++ {/* Timer bar */}+ <div className="w-full h-2 bg-port-border rounded-full overflow-hidden">+ <div+ className={`h-full ${timerColor} transition-all duration-100`}+ style={{ width: `${timePct}%` }}+ />+ </div>++ {/* Time remaining */}+ <div className="text-center text-sm text-gray-500">+ {Math.ceil(timeLeft / 1000)}s remaining+ </div>++ {/* Question */}+ <div className="text-center py-8">+ <div className="text-4xl font-mono font-bold text-white">+ {question?.prompt}+ </div>+ </div>++ {/* Input */}+ <form onSubmit={handleSubmit} className="flex gap-3">+ <input+ ref={inputRef}+ type="number"+ inputMode="numeric"+ value={inputValue}+ onChange={e => setInputValue(e.target.value)}+ placeholder="Answer"+ autoFocus+ className="flex-1 bg-port-bg border border-port-border rounded-lg px-4 py-3 text-xl font-mono text-white text-center placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ <button+ type="submit"+ disabled={inputValue.trim() === ''}+ className="px-6 py-3 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white font-medium rounded-lg transition-colors"+ >+ Enter+ </button>+ </form>++ {/* Skip */}+ <div className="text-center">+ <button+ onClick={skipQuestion}+ className="text-sm text-gray-500 hover:text-gray-300 transition-colors"+ >+ Skip+ </button>+ </div>++ {/* Progress bar */}+ <div className="space-y-1">+ <div className="flex justify-between text-xs text-gray-500">+ <span>Question {currentQuestionIndex + 1} of {totalQuestions}</span>+ <span>{Math.round(progressPct)}%</span>+ </div>+ <div className="w-full h-1.5 bg-port-border rounded-full overflow-hidden">+ <div+ className="h-full bg-port-accent/60 transition-all"+ style={{ width: `${progressPct}%` }}+ />+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/meatspace/post/PostHistory.jsx b/client/src/components/meatspace/post/PostHistory.jsxnew file mode 100644index 0000000000..3617e89e50--- /dev/null+++ b/client/src/components/meatspace/post/PostHistory.jsx@@ -0,0 +1,183 @@+import { useState, useEffect } from 'react';+import { ArrowLeft, ChevronDown, ChevronRight } from 'lucide-react';+import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';+import { getPostSessions, getPostStats } from '../../../services/api';++const DRILL_LABELS = {+ 'doubling-chain': 'Doubling Chain',+ 'serial-subtraction': 'Serial Subtraction',+ 'multiplication': 'Multiplication',+ 'powers': 'Powers',+ 'estimation': 'Estimation'+};++const RANGES = [+ { label: '7d', days: 7 },+ { label: '30d', days: 30 },+ { label: '90d', days: 90 },+ { label: 'All', days: 0 }+];++export default function PostHistory({ onBack }) {+ const [sessions, setSessions] = useState([]);+ const [stats, setStats] = useState(null);+ const [range, setRange] = useState(30);+ const [expandedId, setExpandedId] = useState(null);++ useEffect(() => {+ loadData();+ }, [range]);++ async function loadData() {+ const from = range > 0+ ? new Date(Date.now() - range * 86400000).toISOString().split('T')[0]+ : undefined;+ const [s, st] = await Promise.all([+ getPostSessions(from),+ getPostStats(range || 365)+ ]);+ setSessions((s || []).slice().reverse());+ setStats(st);+ }++ const chartData = sessions.slice().reverse().map(s => ({+ date: s.date,+ score: s.score+ }));++ return (+ <div className="space-y-6 max-w-3xl">+ {/* Header */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <button onClick={onBack} className="text-gray-400 hover:text-white transition-colors">+ <ArrowLeft size={20} />+ </button>+ <h2 className="text-xl font-bold text-white">POST History</h2>+ </div>+ <div className="flex gap-1">+ {RANGES.map(r => (+ <button+ key={r.label}+ onClick={() => setRange(r.days)}+ className={`px-3 py-1 text-xs rounded-lg transition-colors ${+ range === r.days+ ? 'bg-port-accent/20 text-port-accent'+ : 'text-gray-500 hover:text-white'+ }`}+ >+ {r.label}+ </button>+ ))}+ </div>+ </div>++ {/* Stats Summary */}+ {stats && stats.sessionCount > 0 && (+ <div className="grid grid-cols-3 gap-4">+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className="text-2xl font-mono font-bold text-white">{stats.sessionCount}</div>+ <div className="text-xs text-gray-500">Sessions</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className={`text-2xl font-mono font-bold ${+ stats.overall >= 80 ? 'text-port-success' :+ stats.overall >= 50 ? 'text-port-warning' : 'text-port-error'+ }`}>{stats.overall}</div>+ <div className="text-xs text-gray-500">Avg Score</div>+ </div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 text-center">+ <div className="text-2xl font-mono font-bold text-white">+ {Object.keys(stats.byDrill || {}).length}+ </div>+ <div className="text-xs text-gray-500">Drill Types</div>+ </div>+ </div>+ )}++ {/* Chart */}+ {chartData.length > 1 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Score Trend</h3>+ <ResponsiveContainer width="100%" height={200}>+ <LineChart data={chartData}>+ <CartesianGrid stroke="#2a2a2a" strokeDasharray="3 3" />+ <XAxis dataKey="date" tick={{ fontSize: 11, fill: '#666' }} />+ <YAxis domain={[0, 100]} tick={{ fontSize: 11, fill: '#666' }} />+ <Tooltip+ contentStyle={{ backgroundColor: '#1a1a1a', border: '1px solid #2a2a2a', borderRadius: 8 }}+ labelStyle={{ color: '#999' }}+ />+ <Line type="monotone" dataKey="score" stroke="#3b82f6" strokeWidth={2} dot={{ r: 3 }} />+ </LineChart>+ </ResponsiveContainer>+ </div>+ )}++ {/* Session List */}+ <div className="bg-port-card border border-port-border rounded-lg overflow-hidden">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-port-border text-gray-500 text-left">+ <th className="px-4 py-2 font-medium w-8"></th>+ <th className="px-4 py-2 font-medium">Date</th>+ <th className="px-4 py-2 font-medium">Duration</th>+ <th className="px-4 py-2 font-medium">Modules</th>+ <th className="px-4 py-2 font-medium text-right">Score</th>+ </tr>+ </thead>+ <tbody>+ {sessions.flatMap(s => {+ const expanded = expandedId === s.id;+ const durationMin = Math.round((s.durationMs || 0) / 60000);+ const scoreColor = s.score >= 80 ? 'text-port-success' :+ s.score >= 50 ? 'text-port-warning' : 'text-port-error';++ const rows = [+ <tr+ key={s.id}+ onClick={() => setExpandedId(expanded ? null : s.id)}+ className="border-b border-port-border/50 hover:bg-port-bg/50 cursor-pointer"+ >+ <td className="px-4 py-2 text-gray-500">+ {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ </td>+ <td className="px-4 py-2 text-white">{s.date}</td>+ <td className="px-4 py-2 text-gray-400">{durationMin}m</td>+ <td className="px-4 py-2 text-gray-400">{(s.modules || []).join(', ')}</td>+ <td className={`px-4 py-2 text-right font-mono font-medium ${scoreColor}`}>{s.score}</td>+ </tr>+ ];++ if (expanded) {+ for (const [i, task] of (s.tasks || []).entries()) {+ const correct = task.questions?.filter(q => q.correct).length || 0;+ const total = task.questions?.length || 0;+ rows.push(+ <tr key={`${s.id}-${i}`} className="bg-port-bg/30">+ <td></td>+ <td className="px-4 py-1.5 text-gray-500 text-xs" colSpan={2}>+ {DRILL_LABELS[task.type] || task.type}+ </td>+ <td className="px-4 py-1.5 text-gray-500 text-xs">+ {correct}/{total} correct+ </td>+ <td className="px-4 py-1.5 text-right text-gray-400 text-xs font-mono">+ {task.score}+ </td>+ </tr>+ );+ }+ }++ return rows;+ })}+ </tbody>+ </table>+ {sessions.length === 0 && (+ <div className="text-center text-gray-500 py-8">No sessions found for this range.</div>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/meatspace/post/PostSessionLauncher.jsx b/client/src/components/meatspace/post/PostSessionLauncher.jsxnew file mode 100644index 0000000000..9e83d84df7--- /dev/null+++ b/client/src/components/meatspace/post/PostSessionLauncher.jsx@@ -0,0 +1,154 @@+import { useState } from 'react';+import { Zap, History, Settings, Play } from 'lucide-react';++const DRILL_LABELS = {+ 'doubling-chain': 'Doubling Chain',+ 'serial-subtraction': 'Serial Subtraction',+ 'multiplication': 'Multiplication',+ 'powers': 'Powers',+ 'estimation': 'Estimation'+};++export default function PostSessionLauncher({ config, recentSessions, onStart, onViewHistory, onViewConfig }) {+ const [tags, setTags] = useState({ sleep: '', caffeine: '', stress: '' });++ if (!config) {+ return <div className="text-gray-500">Loading configuration...</div>;+ }++ const today = new Date().toISOString().split('T')[0];+ const todaySession = recentSessions?.find(s => s.date === today);+ const lastThree = (recentSessions || []).slice(-3).reverse();++ const enabledDrills = Object.entries(config.mentalMath?.drillTypes || {})+ .filter(([, cfg]) => cfg.enabled);++ function handleStart() {+ const drillConfigs = enabledDrills.map(([type, cfg]) => ({+ type,+ config: {+ steps: cfg.steps,+ count: cfg.count,+ maxDigits: cfg.maxDigits,+ subtrahend: cfg.subtrahend,+ startRange: cfg.startRange,+ bases: cfg.bases,+ maxExponent: cfg.maxExponent,+ tolerancePct: cfg.tolerancePct+ },+ timeLimitSec: cfg.timeLimitSec || 120+ }));+ onStart(drillConfigs);+ }++ return (+ <div className="space-y-6 max-w-2xl">+ {/* Header */}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <Zap size={24} className="text-port-accent" />+ <h2 className="text-xl font-bold text-white">Power On Self Test</h2>+ </div>+ <div className="flex gap-2">+ <button+ onClick={onViewHistory}+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-400 hover:text-white bg-port-card border border-port-border rounded-lg transition-colors"+ >+ <History size={14} />+ History+ </button>+ <button+ onClick={onViewConfig}+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-400 hover:text-white bg-port-card border border-port-border rounded-lg transition-colors"+ >+ <Settings size={14} />+ Config+ </button>+ </div>+ </div>++ {/* Today's Status */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <div className="flex items-center justify-between">+ <span className="text-gray-400 text-sm">Today's Status</span>+ {todaySession ? (+ <span className="text-port-success text-sm font-medium">+ Completed — Score: {todaySession.score}+ </span>+ ) : (+ <span className="text-port-warning text-sm font-medium">Not yet completed</span>+ )}+ </div>+ </div>++ {/* Enabled Drills */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Enabled Drills</h3>+ <div className="space-y-2">+ {enabledDrills.map(([type, cfg]) => (+ <div key={type} className="flex items-center justify-between text-sm">+ <span className="text-white">{DRILL_LABELS[type] || type}</span>+ <span className="text-gray-500">+ {cfg.steps ? `${cfg.steps} steps` : cfg.count ? `${cfg.count} questions` : ''}+ {cfg.timeLimitSec ? ` · ${cfg.timeLimitSec}s` : ''}+ </span>+ </div>+ ))}+ {enabledDrills.length === 0 && (+ <p className="text-gray-500 text-sm">No drills enabled. Configure drills to get started.</p>+ )}+ </div>+ </div>++ {/* Condition Tags */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Conditions (optional)</h3>+ <div className="grid grid-cols-3 gap-3">+ {Object.entries(tags).map(([key, value]) => (+ <div key={key}>+ <label className="text-xs text-gray-500 mb-1 block capitalize">{key}</label>+ <input+ type="text"+ value={value}+ onChange={e => setTags(prev => ({ ...prev, [key]: e.target.value }))}+ placeholder={key === 'sleep' ? 'good/poor' : key === 'caffeine' ? '1 cup' : 'low/high'}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white placeholder-gray-600 focus:border-port-accent focus:outline-none"+ />+ </div>+ ))}+ </div>+ </div>++ {/* Start Button */}+ <button+ onClick={handleStart}+ disabled={enabledDrills.length === 0}+ className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"+ >+ <Play size={18} />+ Start POST+ </button>++ {/* Recent Scores */}+ {lastThree.length > 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Recent Sessions</h3>+ <div className="space-y-2">+ {lastThree.map(s => (+ <div key={s.id} className="flex items-center justify-between text-sm">+ <span className="text-gray-400">{s.date}</span>+ <span className={`font-mono font-medium ${+ s.score >= 80 ? 'text-port-success' :+ s.score >= 50 ? 'text-port-warning' :+ 'text-port-error'+ }`}>+ {s.score}+ </span>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/post/PostSessionResults.jsx b/client/src/components/meatspace/post/PostSessionResults.jsxnew file mode 100644index 0000000000..46a5088d89--- /dev/null+++ b/client/src/components/meatspace/post/PostSessionResults.jsx@@ -0,0 +1,101 @@+import { useState } from 'react';+import { CheckCircle, Save, ArrowLeft } from 'lucide-react';++const DRILL_LABELS = {+ 'doubling-chain': 'Doubling Chain',+ 'serial-subtraction': 'Serial Subtraction',+ 'multiplication': 'Multiplication',+ 'powers': 'Powers',+ 'estimation': 'Estimation'+};++export default function PostSessionResults({ session, onSaved, onBack }) {+ const { drillResults, sessionScore, state, saveSession } = session;+ const [tags, setTags] = useState({});++ const scoreColor = sessionScore >= 80 ? 'text-port-success' :+ sessionScore >= 50 ? 'text-port-warning' : 'text-port-error';++ async function handleSave() {+ // Filter out empty tags+ const cleanTags = {};+ for (const [k, v] of Object.entries(tags)) {+ if (v.trim()) cleanTags[k] = v.trim();+ }+ await saveSession(cleanTags);+ onSaved();+ }++ return (+ <div className="max-w-2xl mx-auto space-y-6">+ {/* Overall Score */}+ <div className="text-center py-8">+ <div className="flex items-center justify-center gap-3 mb-2">+ <CheckCircle size={28} className={scoreColor} />+ <span className="text-sm text-gray-400">Session Score</span>+ </div>+ <div className={`text-6xl font-mono font-bold ${scoreColor}`}>+ {sessionScore}+ </div>+ </div>++ {/* Per-drill Breakdown */}+ <div className="bg-port-card border border-port-border rounded-lg p-4">+ <h3 className="text-sm font-medium text-gray-400 mb-3">Drill Breakdown</h3>+ <div className="space-y-3">+ {drillResults.map((result, i) => {+ const correct = result.questions.filter(q => q.correct).length;+ const total = result.questions.length;+ const accuracyPct = total > 0 ? Math.round((correct / total) * 100) : 0;+ const answered = result.questions.filter(q => q.answered !== null);+ const avgMs = answered.length > 0+ ? Math.round(answered.reduce((s, q) => s + q.responseMs, 0) / answered.length)+ : 0;++ const drillScoreColor = result.score >= 80 ? 'text-port-success' :+ result.score >= 50 ? 'text-port-warning' : 'text-port-error';++ return (+ <div key={i} className="flex items-center justify-between">+ <div>+ <span className="text-white text-sm">{DRILL_LABELS[result.type] || result.type}</span>+ <span className="text-gray-500 text-xs ml-2">+ {accuracyPct}% accuracy · {(avgMs / 1000).toFixed(1)}s avg+ </span>+ </div>+ <span className={`font-mono font-medium ${drillScoreColor}`}>+ {result.score}+ </span>+ </div>+ );+ })}+ </div>+ </div>++ {/* Save Button */}+ {state === 'complete' && (+ <button+ onClick={handleSave}+ className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-port-success hover:bg-port-success/80 text-white font-medium rounded-lg transition-colors"+ >+ <Save size={18} />+ Save Session+ </button>+ )}++ {state === 'saving' && (+ <div className="text-center text-gray-400 py-3">Saving...</div>+ )}++ {state === 'saved' && (+ <button+ onClick={onBack}+ className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-port-card border border-port-border hover:border-port-accent text-white font-medium rounded-lg transition-colors"+ >+ <ArrowLeft size={18} />+ Back to Launcher+ </button>+ )}+ </div>+ );+}diff --git a/client/src/components/meatspace/tabs/PostTab.jsx b/client/src/components/meatspace/tabs/PostTab.jsxnew file mode 100644index 0000000000..fd08aed0fe--- /dev/null+++ b/client/src/components/meatspace/tabs/PostTab.jsx@@ -0,0 +1,117 @@+import { useState, useEffect } from 'react';+import { getPostConfig, getPostSessions } from '../../../services/api';+import { usePostSession } from '../../../hooks/usePostSession';+import PostSessionLauncher from '../post/PostSessionLauncher';+import PostDrillRunner from '../post/PostDrillRunner';+import PostSessionResults from '../post/PostSessionResults';+import PostHistory from '../post/PostHistory';+import PostDrillConfig from '../post/PostDrillConfig';++export default function PostTab() {+ const [view, setView] = useState('launcher');+ const [config, setConfig] = useState(null);+ const [recentSessions, setRecentSessions] = useState([]);+ const session = usePostSession();++ useEffect(() => {+ loadData();+ }, []);++ async function loadData() {+ const [cfg, sessions] = await Promise.all([+ getPostConfig(),+ getPostSessions()+ ]);+ setConfig(cfg);+ setRecentSessions(sessions);+ }++ function handleStart(drillConfigs) {+ session.startSession(drillConfigs);+ setView('running');+ }++ function handleDrillComplete() {+ setView('results');+ }++ async function handleSaved() {+ await loadData();+ setView('launcher');+ session.reset();+ }++ function handleViewHistory() {+ setView('history');+ }++ function handleViewConfig() {+ setView('config');+ }++ function handleConfigSaved(newConfig) {+ setConfig(newConfig);+ setView('launcher');+ }++ function handleBack() {+ if (session.state === 'idle' || session.state === 'saved') {+ setView('launcher');+ }+ }++ // When session completes (all drills done), transition to results+ useEffect(() => {+ if (session.state === 'complete' && view === 'running') {+ setView('results');+ }+ }, [session.state, view]);++ // When between drills, auto-advance+ useEffect(() => {+ if (session.state === 'between-drills') {+ session.nextDrill();+ }+ }, [session.state]);++ switch (view) {+ case 'running':+ return (+ <PostDrillRunner+ session={session}+ />+ );+ case 'results':+ return (+ <PostSessionResults+ session={session}+ onSaved={handleSaved}+ onBack={handleBack}+ />+ );+ case 'history':+ return (+ <PostHistory+ onBack={() => setView('launcher')}+ />+ );+ case 'config':+ return (+ <PostDrillConfig+ config={config}+ onSaved={handleConfigSaved}+ onBack={() => setView('launcher')}+ />+ );+ default:+ return (+ <PostSessionLauncher+ config={config}+ recentSessions={recentSessions}+ onStart={handleStart}+ onViewHistory={handleViewHistory}+ onViewConfig={handleViewConfig}+ />+ );+ }+}diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsnew file mode 100644index 0000000000..f118cc64bb--- /dev/null+++ b/client/src/hooks/usePostSession.js@@ -0,0 +1,201 @@+import { useState, useCallback, useRef } from 'react';+import { generatePostDrill, submitPostSession } from '../services/api';+import toast from 'react-hot-toast';++// States: idle → loading → drilling → between-drills → complete → saving → saved+const STATES = {+ IDLE: 'idle',+ LOADING: 'loading',+ DRILLING: 'drilling',+ BETWEEN_DRILLS: 'between-drills',+ COMPLETE: 'complete',+ SAVING: 'saving',+ SAVED: 'saved'+};++export function usePostSession() {+ const [state, setState] = useState(STATES.IDLE);+ const [drills, setDrills] = useState([]); // queued drill configs+ const [currentDrillIndex, setCurrentDrillIndex] = useState(0);+ const [currentDrill, setCurrentDrill] = useState(null); // generated questions+ const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);+ const [answers, setAnswers] = useState([]); // answers for current drill+ const [drillResults, setDrillResults] = useState([]); // completed drill results+ const [sessionScore, setSessionScore] = useState(0);+ const [savedSession, setSavedSession] = useState(null);+ const questionStartRef = useRef(Date.now());+ const drillStartRef = useRef(Date.now());++ const startSession = useCallback(async (drillConfigs) => {+ // drillConfigs: [{ type, config, timeLimitSec }]+ setState(STATES.LOADING);+ setDrills(drillConfigs);+ setCurrentDrillIndex(0);+ setDrillResults([]);+ setSavedSession(null);++ // Generate first drill+ const first = drillConfigs[0];+ const drill = await generatePostDrill(first.type, first.config);+ setCurrentDrill({ ...drill, timeLimitSec: first.timeLimitSec });+ setCurrentQuestionIndex(0);+ setAnswers([]);+ questionStartRef.current = Date.now();+ drillStartRef.current = Date.now();+ setState(STATES.DRILLING);+ }, []);++ const submitAnswer = useCallback((value) => {+ if (state !== STATES.DRILLING || !currentDrill) return;++ const q = currentDrill.questions[currentQuestionIndex];+ const responseMs = Date.now() - questionStartRef.current;+ const numValue = value === null ? null : Number(value);++ // For estimation drills, check within tolerance+ let correct;+ if (currentDrill.type === 'estimation') {+ const tolerance = (currentDrill.config?.tolerancePct || 10) / 100;+ correct = numValue !== null && Math.abs(numValue - q.expected) <= Math.abs(q.expected * tolerance);+ } else {+ correct = numValue === q.expected;+ }++ const answer = {+ prompt: q.prompt,+ expected: q.expected,+ answered: numValue,+ correct,+ responseMs+ };++ const newAnswers = [...answers, answer];+ setAnswers(newAnswers);++ // Check if drill is complete+ if (currentQuestionIndex + 1 >= currentDrill.questions.length) {+ finishDrill(newAnswers);+ } else {+ setCurrentQuestionIndex(currentQuestionIndex + 1);+ questionStartRef.current = Date.now();+ }+ }, [state, currentDrill, currentQuestionIndex, answers]);++ const skipQuestion = useCallback(() => {+ submitAnswer(null);+ }, [submitAnswer]);++ const finishDrill = useCallback((finalAnswers) => {+ const totalMs = Date.now() - drillStartRef.current;+ const timeLimitMs = (currentDrill?.timeLimitSec || 120) * 1000;++ // Compute score+ const correct = finalAnswers.filter(a => a.correct).length;+ const total = finalAnswers.length;+ const correctRatio = total > 0 ? correct / total : 0;+ const answered = finalAnswers.filter(a => a.answered !== null);+ const totalResponseMs = answered.reduce((sum, a) => sum + a.responseMs, 0);+ const avgResponseMs = answered.length > 0 ? totalResponseMs / answered.length : timeLimitMs;+ const speedBonus = Math.max(0, 1 - avgResponseMs / timeLimitMs);+ const score = Math.min(100, Math.max(0, Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100)));++ const result = {+ module: 'mental-math',+ type: currentDrill.type,+ config: currentDrill.config,+ questions: finalAnswers,+ score,+ totalMs+ };++ const newResults = [...drillResults, result];+ setDrillResults(newResults);++ // Check if there are more drills+ if (currentDrillIndex + 1 < drills.length) {+ setState(STATES.BETWEEN_DRILLS);+ } else {+ // Session complete+ const avgScore = Math.round(newResults.reduce((s, r) => s + r.score, 0) / newResults.length);+ setSessionScore(avgScore);+ setState(STATES.COMPLETE);+ }+ }, [currentDrill, drillResults, currentDrillIndex, drills]);++ const nextDrill = useCallback(async () => {+ const nextIndex = currentDrillIndex + 1;+ setCurrentDrillIndex(nextIndex);+ setState(STATES.LOADING);++ const next = drills[nextIndex];+ const drill = await generatePostDrill(next.type, next.config);+ setCurrentDrill({ ...drill, timeLimitSec: next.timeLimitSec });+ setCurrentQuestionIndex(0);+ setAnswers([]);+ questionStartRef.current = Date.now();+ drillStartRef.current = Date.now();+ setState(STATES.DRILLING);+ }, [currentDrillIndex, drills]);++ const timeExpired = useCallback(() => {+ if (state !== STATES.DRILLING || !currentDrill) return;++ // Mark remaining questions as unanswered+ const remaining = currentDrill.questions.slice(currentQuestionIndex).map(q => ({+ prompt: q.prompt,+ expected: q.expected,+ answered: null,+ correct: false,+ responseMs: 0+ }));++ const finalAnswers = [...answers, ...remaining];+ setAnswers(finalAnswers);+ finishDrill(finalAnswers);+ }, [state, currentDrill, currentQuestionIndex, answers, finishDrill]);++ const saveSession = useCallback(async (tags = {}) => {+ setState(STATES.SAVING);+ const session = await submitPostSession({+ cadence: 'daily',+ modules: ['mental-math'],+ tasks: drillResults,+ tags+ });+ setSavedSession(session);+ toast.success(`POST complete — score: ${session.score}`);+ setState(STATES.SAVED);+ return session;+ }, [drillResults]);++ const reset = useCallback(() => {+ setState(STATES.IDLE);+ setDrills([]);+ setCurrentDrillIndex(0);+ setCurrentDrill(null);+ setCurrentQuestionIndex(0);+ setAnswers([]);+ setDrillResults([]);+ setSessionScore(0);+ setSavedSession(null);+ }, []);++ return {+ state,+ currentDrill,+ currentQuestionIndex,+ currentDrillIndex,+ drillCount: drills.length,+ answers,+ drillResults,+ sessionScore,+ savedSession,+ startSession,+ submitAnswer,+ skipQuestion,+ nextDrill,+ timeExpired,+ saveSession,+ reset+ };+}diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsxindex 79124161fd..55b789e585 100644--- a/client/src/pages/MeatSpace.jsx+++ b/client/src/pages/MeatSpace.jsx@@ -13,6 +13,7 @@ import GenomeTab from '../components/meatspace/tabs/GenomeTab';import HealthTab from '../components/meatspace/tabs/HealthTab';import ImportTab from '../components/meatspace/tabs/ImportTab';import LifestyleTab from '../components/meatspace/tabs/LifestyleTab';+import PostTab from '../components/meatspace/tabs/PostTab';export default function MeatSpace() {const { tab } = useParams();@@ -45,6 +46,8 @@ export default function MeatSpace() {return <ImportTab />;case 'lifestyle':return <LifestyleTab />;+ case 'post':+ return <PostTab />;default:return <OverviewTab />;}diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 1c7c593932..62fb82565f 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1422,6 +1422,30 @@ export const updateEyeExam = (index, data) => request(`/meatspace/eyes/${index}`export const removeEyeExam = (index) => request(`/meatspace/eyes/${index}`, {method: 'DELETE'});++// MeatSpace - POST (Power On Self Test)+export const getPostConfig = () => request('/meatspace/post/config');+export const updatePostConfig = (data) => request('/meatspace/post/config', {+ method: 'PUT',+ body: JSON.stringify(data)+});+export const getPostSessions = (from, to) => {+ const params = new URLSearchParams();+ if (from) params.set('from', from);+ if (to) params.set('to', to);+ return request(`/meatspace/post/sessions?${params}`);+};+export const getPostSession = (id) => request(`/meatspace/post/sessions/${id}`);+export const submitPostSession = (data) => request('/meatspace/post/sessions', {+ method: 'POST',+ body: JSON.stringify(data)+});+export const getPostStats = (days) => request(`/meatspace/post/stats${days ? `?days=${days}` : ''}`);+export const generatePostDrill = (type, config = {}) => request('/meatspace/post/drill', {+ method: 'POST',+ body: JSON.stringify({ type, config })+});+// JIRAexport const getJiraInstances = () => request('/jira/instances');export const getJiraProjects = (instanceId) => request(`/jira/instances/${instanceId}/projects`);diff --git a/server/lib/postValidation.js b/server/lib/postValidation.jsnew file mode 100644index 0000000000..ccc320fe90--- /dev/null+++ b/server/lib/postValidation.js@@ -0,0 +1,69 @@+import { z } from 'zod';++// =============================================================================+// POST (Power On Self Test) VALIDATION SCHEMAS+// =============================================================================++const dateRegex = /^\d{4}-\d{2}-\d{2}$/;++// Tags for session conditions (sleep, caffeine, stress, etc.)+export const postTagsSchema = z.record(z.string().max(200));++// Individual question result+const questionResultSchema = z.object({+ prompt: z.string(),+ expected: z.number(),+ answered: z.number().nullable(),+ correct: z.boolean(),+ responseMs: z.number().min(0)+});++// Task result within a session+const taskResultSchema = z.object({+ module: z.string(),+ type: z.string(),+ config: z.record(z.unknown()).optional().default({}),+ questions: z.array(questionResultSchema),+ score: z.number().min(0).max(100),+ totalMs: z.number().min(0)+});++// Full session submission+export const postSessionSubmitSchema = z.object({+ cadence: z.enum(['daily', 'weekly', 'monthly']).optional().default('daily'),+ modules: z.array(z.string()).min(1),+ tasks: z.array(taskResultSchema).min(1),+ tags: postTagsSchema.optional().default({})+});++// Drill type configuration+const drillTypeConfigSchema = z.object({+ enabled: z.boolean().optional(),+ steps: z.number().int().min(1).max(50).optional(),+ subtrahend: z.number().int().min(1).max(100).optional(),+ startRange: z.array(z.number()).length(2).optional(),+ timeLimitSec: z.number().int().min(10).max(600).optional(),+ count: z.number().int().min(1).max(50).optional(),+ maxDigits: z.number().int().min(1).max(4).optional(),+ bases: z.array(z.number().int().min(2).max(20)).optional(),+ maxExponent: z.number().int().min(2).max(20).optional(),+ tolerancePct: z.number().min(1).max(50).optional()+});++// Config update (partial)+export const postConfigUpdateSchema = z.object({+ mentalMath: z.object({+ enabled: z.boolean().optional(),+ drillTypes: z.record(drillTypeConfigSchema).optional()+ }).optional(),+ sessionModules: z.array(z.string()).optional(),+ scoring: z.object({+ weights: z.record(z.number().min(0).max(1)).optional()+ }).optional()+}).partial();++// Drill generation request+export const postDrillRequestSchema = z.object({+ type: z.enum(['doubling-chain', 'serial-subtraction', 'multiplication', 'powers', 'estimation']),+ config: drillTypeConfigSchema.optional().default({})+});diff --git a/server/routes/meatspace.js b/server/routes/meatspace.jsindex ebb795244d..484649eedf 100644--- a/server/routes/meatspace.js+++ b/server/routes/meatspace.js@@ -12,9 +12,15 @@ import {eyeExamSchema,eyeExamUpdateSchema,} from '../lib/meatspaceValidation.js';+import {+ postSessionSubmitSchema,+ postConfigUpdateSchema,+ postDrillRequestSchema,+} from '../lib/postValidation.js';import * as meatspaceService from '../services/meatspace.js';import * as alcoholService from '../services/meatspaceAlcohol.js';import * as healthService from '../services/meatspaceHealth.js';+import * as postService from '../services/meatspacePost.js';const router = Router();@@ -253,4 +259,81 @@ router.delete('/eyes/:index', asyncHandler(async (req, res) => {}));+// =============================================================================+// POST (Power On Self Test)+// =============================================================================++/**+ * GET /api/meatspace/post/config+ * Drill configuration and weights+ */+router.get('/post/config', asyncHandler(async (req, res) => {+ const config = await postService.getPostConfig();+ res.json(config);+}));++/**+ * PUT /api/meatspace/post/config+ * Update drill configuration+ */+router.put('/post/config', asyncHandler(async (req, res) => {+ const data = validateRequest(postConfigUpdateSchema, req.body);+ const config = await postService.updatePostConfig(data);+ res.json(config);+}));++/**+ * GET /api/meatspace/post/sessions+ * Session history with optional date range+ */+router.get('/post/sessions', asyncHandler(async (req, res) => {+ const sessions = await postService.getPostSessions(req.query.from, req.query.to);+ res.json(sessions);+}));++/**+ * GET /api/meatspace/post/sessions/:id+ * Single session by ID+ */+router.get('/post/sessions/:id', asyncHandler(async (req, res) => {+ const session = await postService.getPostSession(req.params.id);+ if (!session) {+ throw new ServerError('Session not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(session);+}));++/**+ * POST /api/meatspace/post/sessions+ * Submit a completed session+ */+router.post('/post/sessions', asyncHandler(async (req, res) => {+ const data = validateRequest(postSessionSubmitSchema, req.body);+ const session = await postService.submitPostSession(data);+ res.status(201).json(session);+}));++/**+ * GET /api/meatspace/post/stats+ * Rolling averages and trends+ */+router.get('/post/stats', asyncHandler(async (req, res) => {+ const days = req.query.days ? parseInt(req.query.days, 10) : 30;+ const stats = await postService.getPostStats(days);+ res.json(stats);+}));++/**+ * POST /api/meatspace/post/drill+ * Generate a drill (questions only, no answers submitted)+ */+router.post('/post/drill', asyncHandler(async (req, res) => {+ const data = validateRequest(postDrillRequestSchema, req.body);+ const drill = postService.generateDrill(data.type, data.config);+ if (!drill) {+ throw new ServerError('Unknown drill type', { status: 400, code: 'INVALID_DRILL_TYPE' });+ }+ res.json(drill);+}));+export default router;diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsnew file mode 100644index 0000000000..986176e3dc--- /dev/null+++ b/server/services/meatspacePost.js@@ -0,0 +1,262 @@+/**+ * MeatSpace POST (Power On Self Test) Service+ *+ * Drill generators, scoring, and session CRUD for cognitive self-tests.+ * Reads/writes to meatspace data files.+ */++import { writeFile } from 'fs/promises';+import { join } from 'path';+import { randomUUID } from 'crypto';+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';++const MEATSPACE_DIR = PATHS.meatspace;+const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');+const CONFIG_FILE = join(MEATSPACE_DIR, 'post-config.json');++const DEFAULT_CONFIG = {+ mentalMath: {+ enabled: true,+ drillTypes: {+ 'doubling-chain': { enabled: true, steps: 8, timeLimitSec: 60 },+ 'serial-subtraction': { enabled: true, steps: 10, subtrahend: 7, startRange: [100, 200], timeLimitSec: 90 },+ 'multiplication': { enabled: true, count: 10, maxDigits: 2, timeLimitSec: 120 },+ 'powers': { enabled: true, bases: [2, 3, 5], maxExponent: 10, count: 8, timeLimitSec: 90 },+ 'estimation': { enabled: true, count: 5, tolerancePct: 10, timeLimitSec: 120 }+ }+ },+ sessionModules: ['mental-math'],+ scoring: { weights: { 'mental-math': 1.0 } }+};++async function ensureMeatspaceDir() {+ await ensureDir(MEATSPACE_DIR);+}++// =============================================================================+// CONFIG+// =============================================================================++export async function getPostConfig() {+ const config = await readJSONFile(CONFIG_FILE, DEFAULT_CONFIG);+ return { ...DEFAULT_CONFIG, ...config };+}++export async function updatePostConfig(updates) {+ const config = await getPostConfig();+ const merged = deepMerge(config, updates);+ await ensureMeatspaceDir();+ await writeFile(CONFIG_FILE, JSON.stringify(merged, null, 2));+ console.log(`🧪 POST config updated`);+ return merged;+}++// =============================================================================+// SESSIONS+// =============================================================================++export async function getPostSessions(from, to) {+ const data = await readJSONFile(SESSIONS_FILE, { sessions: [] });+ let sessions = data.sessions || [];+ if (from) sessions = sessions.filter(s => s.date >= from);+ if (to) sessions = sessions.filter(s => s.date <= to);+ return sessions;+}++export async function getPostSession(id) {+ const data = await readJSONFile(SESSIONS_FILE, { sessions: [] });+ return (data.sessions || []).find(s => s.id === id) || null;+}++export async function submitPostSession(sessionData) {+ const data = await readJSONFile(SESSIONS_FILE, { sessions: [] });+ const now = new Date().toISOString();+ const session = {+ id: randomUUID(),+ date: now.split('T')[0],+ startedAt: now,+ completedAt: now,+ durationMs: sessionData.tasks.reduce((sum, t) => sum + t.totalMs, 0),+ cadence: sessionData.cadence || 'daily',+ modules: sessionData.modules,+ tasks: sessionData.tasks,+ score: computeSessionScore(sessionData.tasks, sessionData.modules),+ tags: sessionData.tags || {}+ };++ data.sessions.push(session);+ data.sessions.sort((a, b) => a.date.localeCompare(b.date));+ await ensureMeatspaceDir();+ await writeFile(SESSIONS_FILE, JSON.stringify(data, null, 2));+ console.log(`🧪 POST session saved: score=${session.score} modules=${session.modules.join(',')}`);+ return session;+}++export async function getPostStats(days = 30) {+ const sessions = await getPostSessions();+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - days);+ const cutoffStr = cutoff.toISOString().split('T')[0];+ const recent = sessions.filter(s => s.date >= cutoffStr);++ if (recent.length === 0) {+ return { days, sessionCount: 0, overall: null, byModule: {}, byDrill: {} };+ }++ const scores = recent.map(s => s.score);+ const overall = Math.round(scores.reduce((a, b) => a + b, 0) / scores.length);++ const byModule = {};+ const byDrill = {};+ for (const session of recent) {+ for (const task of session.tasks) {+ if (!byModule[task.module]) byModule[task.module] = [];+ byModule[task.module].push(task.score);++ const key = `${task.module}:${task.type}`;+ if (!byDrill[key]) byDrill[key] = [];+ byDrill[key].push(task.score);+ }+ }++ const avg = arr => Math.round(arr.reduce((a, b) => a + b, 0) / arr.length);+ for (const key of Object.keys(byModule)) byModule[key] = avg(byModule[key]);+ for (const key of Object.keys(byDrill)) byDrill[key] = avg(byDrill[key]);++ return { days, sessionCount: recent.length, overall, byModule, byDrill };+}++// =============================================================================+// DRILL GENERATORS (pure functions)+// =============================================================================++export function generateDoublingChain(startValue, steps = 8) {+ const start = startValue ?? (Math.floor(Math.random() * 7) + 3); // 3-9+ const questions = [];+ let current = start;+ for (let i = 0; i < steps; i++) {+ const next = current * 2;+ questions.push({ prompt: `${current} x 2`, expected: next });+ current = next;+ }+ return { type: 'doubling-chain', config: { startValue: start, steps }, questions };+}++export function generateSerialSubtraction(start, subtrahend = 7, steps = 10) {+ const startVal = start ?? (Math.floor(Math.random() * 101) + 100); // 100-200+ const questions = [];+ let current = startVal;+ for (let i = 0; i < steps; i++) {+ const next = current - subtrahend;+ questions.push({ prompt: `${current} - ${subtrahend}`, expected: next });+ current = next;+ }+ return { type: 'serial-subtraction', config: { startValue: startVal, subtrahend, steps }, questions };+}++export function generateMultiplication(count = 10, maxDigits = 2) {+ const maxVal = Math.pow(10, maxDigits) - 1;+ const minVal = maxDigits > 1 ? Math.pow(10, maxDigits - 1) : 1;+ const questions = [];+ for (let i = 0; i < count; i++) {+ const a = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;+ const b = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;+ questions.push({ prompt: `${a} x ${b}`, expected: a * b });+ }+ return { type: 'multiplication', config: { count, maxDigits }, questions };+}++export function generatePowers(bases = [2, 3, 5], maxExponent = 10, count = 8) {+ const questions = [];+ for (let i = 0; i < count; i++) {+ const base = bases[Math.floor(Math.random() * bases.length)];+ const exp = Math.floor(Math.random() * (maxExponent - 1)) + 2; // 2 to maxExponent+ questions.push({ prompt: `${base}^${exp}`, expected: Math.pow(base, exp) });+ }+ return { type: 'powers', config: { bases, maxExponent, count }, questions };+}++export function generateEstimation(count = 5) {+ const ops = ['+', '-', 'x'];+ const questions = [];+ for (let i = 0; i < count; i++) {+ const a = Math.floor(Math.random() * 900) + 100; // 100-999+ const b = Math.floor(Math.random() * 900) + 100;+ const op = ops[Math.floor(Math.random() * ops.length)];+ let expected;+ let prompt;+ if (op === '+') {+ expected = a + b;+ prompt = `${a} + ${b}`;+ } else if (op === '-') {+ expected = a - b;+ prompt = `${a} - ${b}`;+ } else {+ expected = a * b;+ prompt = `${a} x ${b}`;+ }+ questions.push({ prompt, expected });+ }+ return { type: 'estimation', config: { count }, questions };+}++export function generateDrill(type, config = {}) {+ switch (type) {+ case 'doubling-chain':+ return generateDoublingChain(config.startValue, config.steps);+ case 'serial-subtraction':+ return generateSerialSubtraction(config.startValue, config.subtrahend, config.steps);+ case 'multiplication':+ return generateMultiplication(config.count, config.maxDigits);+ case 'powers':+ return generatePowers(config.bases, config.maxExponent, config.count);+ case 'estimation':+ return generateEstimation(config.count);+ default:+ return null;+ }+}++// =============================================================================+// SCORING (pure functions)+// =============================================================================++export function scoreDrill(type, questions, timeLimitMs) {+ if (!questions?.length) return 0;++ const answered = questions.filter(q => q.answered !== null && q.answered !== undefined);+ const correct = questions.filter(q => q.correct);+ const correctRatio = correct.length / questions.length;++ const totalResponseMs = answered.reduce((sum, q) => sum + (q.responseMs || 0), 0);+ const avgResponseMs = answered.length > 0 ? totalResponseMs / answered.length : timeLimitMs;++ // For estimation drills, accuracy is based on tolerance rather than exact match+ // but we use the pre-computed correct flag from the client+ const speedBonus = Math.max(0, 1 - avgResponseMs / timeLimitMs);+ const score = Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100);+ return Math.min(100, Math.max(0, score));+}++function computeSessionScore(tasks, modules) {+ if (!tasks?.length) return 0;+ const totalScore = tasks.reduce((sum, t) => sum + t.score, 0);+ return Math.round(totalScore / tasks.length);+}++// =============================================================================+// UTILITY+// =============================================================================++function deepMerge(target, source) {+ const result = { ...target };+ for (const key of Object.keys(source)) {+ if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key]) &&+ target[key] && typeof target[key] === 'object' && !Array.isArray(target[key])) {+ result[key] = deepMerge(target[key], source[key]);+ } else {+ result[key] = source[key];+ }+ }+ return result;+}diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsnew file mode 100644index 0000000000..5ccf3181ab--- /dev/null+++ b/server/services/meatspacePost.test.js@@ -0,0 +1,311 @@+import { describe, it, expect } from 'vitest';++// Inline pure functions to avoid mocking file I/O++function generateDoublingChain(startValue, steps = 8) {+ const start = startValue ?? (Math.floor(Math.random() * 7) + 3);+ const questions = [];+ let current = start;+ for (let i = 0; i < steps; i++) {+ const next = current * 2;+ questions.push({ prompt: `${current} x 2`, expected: next });+ current = next;+ }+ return { type: 'doubling-chain', config: { startValue: start, steps }, questions };+}++function generateSerialSubtraction(start, subtrahend = 7, steps = 10) {+ const startVal = start ?? (Math.floor(Math.random() * 101) + 100);+ const questions = [];+ let current = startVal;+ for (let i = 0; i < steps; i++) {+ const next = current - subtrahend;+ questions.push({ prompt: `${current} - ${subtrahend}`, expected: next });+ current = next;+ }+ return { type: 'serial-subtraction', config: { startValue: startVal, subtrahend, steps }, questions };+}++function generateMultiplication(count = 10, maxDigits = 2) {+ const maxVal = Math.pow(10, maxDigits) - 1;+ const minVal = maxDigits > 1 ? Math.pow(10, maxDigits - 1) : 1;+ const questions = [];+ for (let i = 0; i < count; i++) {+ const a = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;+ const b = Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;+ questions.push({ prompt: `${a} x ${b}`, expected: a * b });+ }+ return { type: 'multiplication', config: { count, maxDigits }, questions };+}++function generatePowers(bases = [2, 3, 5], maxExponent = 10, count = 8) {+ const questions = [];+ for (let i = 0; i < count; i++) {+ const base = bases[Math.floor(Math.random() * bases.length)];+ const exp = Math.floor(Math.random() * (maxExponent - 1)) + 2;+ questions.push({ prompt: `${base}^${exp}`, expected: Math.pow(base, exp) });+ }+ return { type: 'powers', config: { bases, maxExponent, count }, questions };+}++function generateEstimation(count = 5) {+ const ops = ['+', '-', 'x'];+ const questions = [];+ for (let i = 0; i < count; i++) {+ const a = Math.floor(Math.random() * 900) + 100;+ const b = Math.floor(Math.random() * 900) + 100;+ const op = ops[Math.floor(Math.random() * ops.length)];+ let expected, prompt;+ if (op === '+') { expected = a + b; prompt = `${a} + ${b}`; }+ else if (op === '-') { expected = a - b; prompt = `${a} - ${b}`; }+ else { expected = a * b; prompt = `${a} x ${b}`; }+ questions.push({ prompt, expected });+ }+ return { type: 'estimation', config: { count }, questions };+}++function scoreDrill(type, questions, timeLimitMs) {+ if (!questions?.length) return 0;+ const answered = questions.filter(q => q.answered !== null && q.answered !== undefined);+ const correct = questions.filter(q => q.correct);+ const correctRatio = correct.length / questions.length;+ const totalResponseMs = answered.reduce((sum, q) => sum + (q.responseMs || 0), 0);+ const avgResponseMs = answered.length > 0 ? totalResponseMs / answered.length : timeLimitMs;+ const speedBonus = Math.max(0, 1 - avgResponseMs / timeLimitMs);+ const score = Math.round((correctRatio * 0.8 + speedBonus * 0.2) * 100);+ return Math.min(100, Math.max(0, score));+}++// =============================================================================+// DOUBLING CHAIN TESTS+// =============================================================================++describe('generateDoublingChain', () => {+ it('generates correct number of steps', () => {+ const result = generateDoublingChain(5, 6);+ expect(result.questions).toHaveLength(6);+ expect(result.type).toBe('doubling-chain');+ });++ it('each value doubles from the previous', () => {+ const result = generateDoublingChain(7, 4);+ expect(result.questions[0].expected).toBe(14);+ expect(result.questions[1].expected).toBe(28);+ expect(result.questions[2].expected).toBe(56);+ expect(result.questions[3].expected).toBe(112);+ });++ it('uses random start 3-9 when not provided', () => {+ const result = generateDoublingChain(undefined, 3);+ const start = result.config.startValue;+ expect(start).toBeGreaterThanOrEqual(3);+ expect(start).toBeLessThanOrEqual(9);+ });++ it('stores config with start value and steps', () => {+ const result = generateDoublingChain(4, 5);+ expect(result.config).toEqual({ startValue: 4, steps: 5 });+ });+});++// =============================================================================+// SERIAL SUBTRACTION TESTS+// =============================================================================++describe('generateSerialSubtraction', () => {+ it('generates correct number of steps', () => {+ const result = generateSerialSubtraction(100, 7, 5);+ expect(result.questions).toHaveLength(5);+ expect(result.type).toBe('serial-subtraction');+ });++ it('each value decreases by subtrahend', () => {+ const result = generateSerialSubtraction(100, 7, 4);+ expect(result.questions[0].expected).toBe(93);+ expect(result.questions[1].expected).toBe(86);+ expect(result.questions[2].expected).toBe(79);+ expect(result.questions[3].expected).toBe(72);+ });++ it('uses random start 100-200 when not provided', () => {+ const result = generateSerialSubtraction(undefined, 7, 3);+ const start = result.config.startValue;+ expect(start).toBeGreaterThanOrEqual(100);+ expect(start).toBeLessThanOrEqual(200);+ });+});++// =============================================================================+// MULTIPLICATION TESTS+// =============================================================================++describe('generateMultiplication', () => {+ it('generates requested number of questions', () => {+ const result = generateMultiplication(5, 2);+ expect(result.questions).toHaveLength(5);+ expect(result.type).toBe('multiplication');+ });++ it('operands are within digit limits for 2-digit', () => {+ const result = generateMultiplication(20, 2);+ for (const q of result.questions) {+ // Parse operands from prompt "A x B"+ const [a, b] = q.prompt.split(' x ').map(Number);+ expect(a).toBeGreaterThanOrEqual(10);+ expect(a).toBeLessThanOrEqual(99);+ expect(b).toBeGreaterThanOrEqual(10);+ expect(b).toBeLessThanOrEqual(99);+ expect(q.expected).toBe(a * b);+ }+ });++ it('1-digit mode produces single digit operands', () => {+ const result = generateMultiplication(10, 1);+ for (const q of result.questions) {+ const [a, b] = q.prompt.split(' x ').map(Number);+ expect(a).toBeGreaterThanOrEqual(1);+ expect(a).toBeLessThanOrEqual(9);+ expect(b).toBeGreaterThanOrEqual(1);+ expect(b).toBeLessThanOrEqual(9);+ }+ });+});++// =============================================================================+// POWERS TESTS+// =============================================================================++describe('generatePowers', () => {+ it('generates requested number of questions', () => {+ const result = generatePowers([2, 3], 8, 6);+ expect(result.questions).toHaveLength(6);+ expect(result.type).toBe('powers');+ });++ it('uses only specified bases', () => {+ const result = generatePowers([2, 5], 10, 20);+ for (const q of result.questions) {+ const base = parseInt(q.prompt.split('^')[0]);+ expect([2, 5]).toContain(base);+ }+ });++ it('expected values are correct', () => {+ const result = generatePowers([2], 5, 10);+ for (const q of result.questions) {+ const [base, exp] = q.prompt.split('^').map(Number);+ expect(q.expected).toBe(Math.pow(base, exp));+ }+ });++ it('exponents are at least 2', () => {+ const result = generatePowers([2, 3, 5], 10, 30);+ for (const q of result.questions) {+ const exp = parseInt(q.prompt.split('^')[1]);+ expect(exp).toBeGreaterThanOrEqual(2);+ }+ });+});++// =============================================================================+// ESTIMATION TESTS+// =============================================================================++describe('generateEstimation', () => {+ it('generates requested number of questions', () => {+ const result = generateEstimation(3);+ expect(result.questions).toHaveLength(3);+ expect(result.type).toBe('estimation');+ });++ it('expected values match the operation', () => {+ const result = generateEstimation(20);+ for (const q of result.questions) {+ if (q.prompt.includes(' + ')) {+ const [a, b] = q.prompt.split(' + ').map(Number);+ expect(q.expected).toBe(a + b);+ } else if (q.prompt.includes(' - ')) {+ const [a, b] = q.prompt.split(' - ').map(Number);+ expect(q.expected).toBe(a - b);+ } else {+ const [a, b] = q.prompt.split(' x ').map(Number);+ expect(q.expected).toBe(a * b);+ }+ }+ });++ it('operands are 3-digit numbers (100-999)', () => {+ const result = generateEstimation(20);+ for (const q of result.questions) {+ const nums = q.prompt.match(/\d+/g).map(Number);+ for (const n of nums) {+ expect(n).toBeGreaterThanOrEqual(100);+ expect(n).toBeLessThanOrEqual(999);+ }+ }+ });+});++// =============================================================================+// SCORING TESTS+// =============================================================================++describe('scoreDrill', () => {+ it('returns 0 for empty questions', () => {+ expect(scoreDrill('multiplication', [], 60000)).toBe(0);+ expect(scoreDrill('multiplication', null, 60000)).toBe(0);+ });++ it('100% accuracy with fast responses gives high score', () => {+ const questions = [+ { prompt: '5 x 3', expected: 15, answered: 15, correct: true, responseMs: 1000 },+ { prompt: '7 x 4', expected: 28, answered: 28, correct: true, responseMs: 1500 },+ { prompt: '6 x 8', expected: 48, answered: 48, correct: true, responseMs: 2000 }+ ];+ const score = scoreDrill('multiplication', questions, 120000);+ expect(score).toBeGreaterThanOrEqual(90);+ expect(score).toBeLessThanOrEqual(100);+ });++ it('0% accuracy gives 0', () => {+ const questions = [+ { prompt: '5 x 3', expected: 15, answered: 10, correct: false, responseMs: 1000 },+ { prompt: '7 x 4', expected: 28, answered: 30, correct: false, responseMs: 1500 }+ ];+ const score = scoreDrill('multiplication', questions, 60000);+ // 0 accuracy * 0.8 = 0, plus small speed bonus+ expect(score).toBeLessThanOrEqual(20);+ });++ it('unanswered questions count against accuracy', () => {+ const questions = [+ { prompt: '5 x 3', expected: 15, answered: 15, correct: true, responseMs: 1000 },+ { prompt: '7 x 4', expected: 28, answered: null, correct: false, responseMs: 0 }+ ];+ const score = scoreDrill('multiplication', questions, 60000);+ // 50% accuracy = 40 base, plus speed bonus+ expect(score).toBeGreaterThanOrEqual(40);+ expect(score).toBeLessThanOrEqual(60);+ });++ it('slow responses reduce speed bonus', () => {+ const fast = [+ { prompt: '5 x 3', expected: 15, answered: 15, correct: true, responseMs: 1000 }+ ];+ const slow = [+ { prompt: '5 x 3', expected: 15, answered: 15, correct: true, responseMs: 55000 }+ ];+ const fastScore = scoreDrill('multiplication', fast, 60000);+ const slowScore = scoreDrill('multiplication', slow, 60000);+ expect(fastScore).toBeGreaterThan(slowScore);+ });++ it('score is clamped between 0 and 100', () => {+ const questions = [+ { prompt: '1 x 1', expected: 1, answered: 1, correct: true, responseMs: 100 }+ ];+ const score = scoreDrill('multiplication', questions, 120000);+ expect(score).toBeLessThanOrEqual(100);+ expect(score).toBeGreaterThanOrEqual(0);+ });+});