Skip to content

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

add Character Sheet page with D&D mechanics

Adam Eivydade5c975f67
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
new file mode 100644
index 0000000000..94b08ce7dd
--- /dev/null
+++ b/.changelog/NEXT.md
@@ -0,0 +1,2 @@
+### Added
+- Character Sheet page: D&D-style character tracking with XP, HP, leveling, dice-based damage, short/long rests, custom event logging, and JIRA/CoS task sync for XP
diff --git a/client/src/App.jsx b/client/src/App.jsx
index d40766867c..1e3afde456 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -24,6 +24,7 @@ import MeatSpace from './pages/MeatSpace';
import Post from './pages/Post';
import Review from './pages/Review';
import Loops from './pages/Loops';
+import CharacterSheet from './pages/CharacterSheet';
// Auto-reload on stale chunk errors (e.g., after a rebuild changes chunk hashes)
// Uses sessionStorage to prevent infinite reload loops (max 1 reload per session)
@@ -133,6 +134,7 @@ export default function App() {
<Route path="devtools/jira" element={<Jira />} />
<Route path="city" element={<CyberCity />} />
<Route path="city/settings" element={<CyberCity />} />
+ <Route path="character" element={<CharacterSheet />} />
<Route path="agents" element={<Agents />} />
<Route path="agents/:agentId" element={<Agents />} />
<Route path="agents/:agentId/:tab" element={<Agents />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 2b43aa9706..ec2d283f28 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -65,7 +65,8 @@ import {
RefreshCw,
Dog,
FilePen,
- MessageCircle
+ MessageCircle,
+ Swords
} from 'lucide-react';
/* global __APP_VERSION__ */
import Logo from './Logo';
@@ -113,6 +114,7 @@ const navItems = [
{ to: '/calendar/week', label: 'Week', icon: CalendarDays }
]
},
+ { to: '/character', label: 'Character', icon: Swords, single: true },
{
label: 'Chief of Staff',
icon: Crown,
@@ -671,7 +673,8 @@ export default function Layout() {
{/* Main content */}
{(() => {
- const isFullWidth = location.pathname.startsWith('/calendar') ||
+ const isFullWidth = location.pathname === '/character' ||
+ location.pathname.startsWith('/calendar') ||
location.pathname.startsWith('/cos') ||
location.pathname.startsWith('/brain') ||
location.pathname.startsWith('/digital-twin') ||
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
new file mode 100644
index 0000000000..48404214ac
--- /dev/null
+++ b/client/src/pages/CharacterSheet.jsx
@@ -0,0 +1,541 @@
+import { useState, useEffect, useCallback } from 'react';
+import {
+ Sword, Star, Moon, ScrollText, Shield, Heart,
+ Sparkles, RefreshCw, Dices, X, ChevronDown, Zap
+} from 'lucide-react';
+
+const API = '/api/character';
+const fetchJson = (url, opts) => fetch(url, opts).then(r => r.json());
+const get = () => fetchJson(API);
+const post = (path, body) =>
+ fetchJson(`${API}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body)
+ });
+const put = (body) =>
+ fetchJson(API, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body)
+ });
+
+// D&D 5e XP thresholds (must match server)
+const XP_THRESHOLDS = [
+ 0, 300, 900, 2700, 6500, 14000, 23000, 34000, 48000, 64000,
+ 85000, 100000, 120000, 140000, 165000, 195000, 225000, 265000, 305000, 355000
+];
+function xpForNextLevel(level) {
+ return level >= 20 ? XP_THRESHOLDS[19] : XP_THRESHOLDS[level];
+}
+function xpForCurrentLevel(level) {
+ return level <= 1 ? 0 : XP_THRESHOLDS[level - 1];
+}
+
+const EVENT_ICONS = {
+ damage: Sword,
+ xp: Star,
+ rest: Moon,
+ level_up: Sparkles,
+ custom: ScrollText,
+ sync: RefreshCw
+};
+
+const EVENT_COLORS = {
+ damage: 'text-port-error',
+ xp: 'text-port-warning',
+ rest: 'text-port-accent',
+ level_up: 'text-purple-400',
+ custom: 'text-gray-400',
+ sync: 'text-port-accent'
+};
+
+function relativeTime(ts) {
+ const diff = Date.now() - new Date(ts).getTime();
+ const mins = Math.floor(diff / 60000);
+ if (mins < 1) return 'just now';
+ if (mins < 60) return `${mins}m ago`;
+ const hrs = Math.floor(mins / 60);
+ if (hrs < 24) return `${hrs}h ago`;
+ const days = Math.floor(hrs / 24);
+ if (days < 30) return `${days}d ago`;
+ return `${Math.floor(days / 30)}mo ago`;
+}
+
+function hpColor(pct) {
+ if (pct > 50) return 'bg-port-success';
+ if (pct > 25) return 'bg-port-warning';
+ return 'bg-port-error';
+}
+
+export default function CharacterSheet() {
+ const [char, setChar] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [activeAction, setActiveAction] = useState(null);
+ const [editingName, setEditingName] = useState(false);
+ const [editingClass, setEditingClass] = useState(false);
+ const [nameVal, setNameVal] = useState('');
+ const [classVal, setClassVal] = useState('');
+ const [syncing, setSyncing] = useState(null);
+
+ // Form states
+ const [dmgDice, setDmgDice] = useState('1d6');
+ const [dmgDesc, setDmgDesc] = useState('');
+ const [xpAmount, setXpAmount] = useState('');
+ const [xpDesc, setXpDesc] = useState('');
+ const [evtDesc, setEvtDesc] = useState('');
+ const [evtXp, setEvtXp] = useState('');
+ const [evtDice, setEvtDice] = useState('');
+
+ const load = useCallback(async () => {
+ const data = await get();
+ setChar(data);
+ setNameVal(data.name || '');
+ setClassVal(data.class || '');
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(); }, [load]);
+
+ const toggleAction = (action) => {
+ setActiveAction(prev => prev === action ? null : action);
+ };
+
+ const handleDamage = async () => {
+ const result = await post('/damage', { diceNotation: dmgDice, description: dmgDesc || undefined });
+ setChar(result.character);
+ setActiveAction(null);
+ setDmgDice('1d6');
+ setDmgDesc('');
+ };
+
+ const handleShortRest = async () => {
+ const result = await post('/rest', { type: 'short' });
+ setChar(result.character);
+ };
+
+ const handleLongRest = async () => {
+ const result = await post('/rest', { type: 'long' });
+ setChar(result.character);
+ };
+
+ const handleAddXp = async () => {
+ if (!xpAmount) return;
+ const result = await post('/xp', { amount: Number(xpAmount), source: 'manual', description: xpDesc || undefined });
+ setChar(result.character);
+ setActiveAction(null);
+ setXpAmount('');
+ setXpDesc('');
+ };
+
+ const handleLogEvent = async () => {
+ if (!evtDesc) return;
+ const body = { description: evtDesc };
+ if (evtXp) body.xp = Number(evtXp);
+ if (evtDice) body.diceNotation = evtDice;
+ const result = await post('/event', body);
+ setChar(result.character);
+ setActiveAction(null);
+ setEvtDesc('');
+ setEvtXp('');
+ setEvtDice('');
+ };
+
+ const handleSync = async (type) => {
+ setSyncing(type);
+ const result = await post(`/sync/${type}`, {});
+ setChar(result.character);
+ setSyncing(null);
+ };
+
+ const handleNameSave = async () => {
+ if (nameVal.trim() && nameVal !== char.name) {
+ const data = await put({ name: nameVal.trim() });
+ setChar(data);
+ }
+ setEditingName(false);
+ };
+
+ const handleClassSave = async () => {
+ if (classVal.trim() && classVal !== char.class) {
+ const data = await put({ class: classVal.trim() });
+ setChar(data);
+ }
+ setEditingClass(false);
+ };
+
+ if (loading || !char) {
+ return (
+ <div className="h-full flex items-center justify-center text-gray-400">
+ <RefreshCw className="w-6 h-6 animate-spin mr-2" /> Loading character...
+ </div>
+ );
+ }
+
+ const hpPct = Math.max(0, Math.min(100, (char.hp / char.maxHp) * 100));
+ const nextLevelXP = xpForNextLevel(char.level);
+ const currentLevelXP = xpForCurrentLevel(char.level);
+ const levelRange = nextLevelXP - currentLevelXP;
+ const xpPct = char.level >= 20 ? 100 : Math.max(0, Math.min(100, ((char.xp - currentLevelXP) / levelRange) * 100));
+
+ return (
+ <div className="h-full flex flex-col overflow-hidden">
+ {/* Header */}
+ <div className="flex items-center justify-between px-6 py-4 border-b border-port-border bg-port-card">
+ <div className="flex items-center gap-3">
+ <Shield className="w-6 h-6 text-port-accent" />
+ <h1 className="text-xl font-semibold text-white">Character Sheet</h1>
+ </div>
+ <button
+ onClick={() => { setLoading(true); load(); }}
+ className="p-2 rounded-lg text-gray-400 hover:text-white hover:bg-port-border/50"
+ title="Refresh"
+ >
+ <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto p-4 md:p-6 space-y-4">
+ {/* Character Identity & Stats */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4 md:p-6">
+ <div className="flex flex-col md:flex-row md:items-start gap-4">
+ {/* Name, Class, Level */}
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-3 mb-1">
+ {editingName ? (
+ <input
+ autoFocus
+ value={nameVal}
+ onChange={e => setNameVal(e.target.value)}
+ onBlur={handleNameSave}
+ onKeyDown={e => e.key === 'Enter' && handleNameSave()}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-2xl font-bold text-white w-full max-w-xs"
+ />
+ ) : (
+ <h2
+ onClick={() => setEditingName(true)}
+ className="text-2xl font-bold text-white cursor-pointer hover:text-port-accent transition-colors truncate"
+ title="Click to edit name"
+ >
+ {char.name || 'Unnamed Hero'}
+ </h2>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ {editingClass ? (
+ <input
+ autoFocus
+ value={classVal}
+ onChange={e => setClassVal(e.target.value)}
+ onBlur={handleClassSave}
+ onKeyDown={e => e.key === 'Enter' && handleClassSave()}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-gray-300 w-full max-w-xs"
+ />
+ ) : (
+ <span
+ onClick={() => setEditingClass(true)}
+ className="text-sm text-gray-400 cursor-pointer hover:text-port-accent transition-colors"
+ title="Click to edit class"
+ >
+ {char.class || 'Adventurer'}
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Level Badge */}
+ <div className="flex-shrink-0 flex items-center gap-3">
+ <div className="relative w-20 h-20 flex items-center justify-center rounded-full border-2 border-port-accent bg-port-bg">
+ <div className="text-center">
+ <div className="text-2xl font-bold text-port-accent">{char.level}</div>
+ <div className="text-[10px] uppercase tracking-wider text-gray-500">Level</div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* HP Bar */}
+ <div className="mt-4">
+ <div className="flex items-center justify-between mb-1">
+ <div className="flex items-center gap-1.5 text-sm font-medium text-gray-300">
+ <Heart className="w-4 h-4 text-port-error" />
+ HP
+ </div>
+ <span className="text-sm text-gray-400">
+ {char.hp} / {char.maxHp}
+ </span>
+ </div>
+ <div className="h-5 bg-port-bg rounded-full overflow-hidden border border-port-border">
+ <div
+ className={`h-full rounded-full transition-all duration-500 ease-out ${hpColor(hpPct)}`}
+ style={{ width: `${hpPct}%` }}
+ />
+ </div>
+ </div>
+
+ {/* XP Bar */}
+ <div className="mt-3">
+ <div className="flex items-center justify-between mb-1">
+ <div className="flex items-center gap-1.5 text-sm font-medium text-gray-300">
+ <Sparkles className="w-4 h-4 text-port-warning" />
+ XP
+ </div>
+ <span className="text-sm text-gray-400">
+ {char.xp} / {nextLevelXP}
+ </span>
+ </div>
+ <div className="h-3 bg-port-bg rounded-full overflow-hidden border border-port-border">
+ <div
+ className="h-full rounded-full transition-all duration-500 ease-out bg-port-warning"
+ style={{ width: `${xpPct}%` }}
+ />
+ </div>
+ </div>
+ </div>
+
+ {/* Quick Actions */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex flex-wrap gap-2">
+ <button
+ onClick={() => toggleAction('damage')}
+ className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
+ activeAction === 'damage'
+ ? 'bg-port-error text-white'
+ : 'bg-port-error/20 text-port-error hover:bg-port-error/30'
+ }`}
+ >
+ <Sword className="w-4 h-4" /> Take Damage
+ <ChevronDown className={`w-3 h-3 transition-transform ${activeAction === 'damage' ? 'rotate-180' : ''}`} />
+ </button>
+
+ <button
+ onClick={handleShortRest}
+ className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors"
+ >
+ <Moon className="w-4 h-4" /> Short Rest
+ </button>
+
+ <button
+ onClick={handleLongRest}
+ className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium bg-port-success/20 text-port-success hover:bg-port-success/30 transition-colors"
+ >
+ <Zap className="w-4 h-4" /> Long Rest
+ </button>
+
+ <button
+ onClick={() => toggleAction('xp')}
+ className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
+ activeAction === 'xp'
+ ? 'bg-port-warning text-black'
+ : 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'
+ }`}
+ >
+ <Star className="w-4 h-4" /> Add XP
+ <ChevronDown className={`w-3 h-3 transition-transform ${activeAction === 'xp' ? 'rotate-180' : ''}`} />
+ </button>
+
+ <button
+ onClick={() => toggleAction('event')}
+ className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
+ activeAction === 'event'
+ ? 'bg-purple-500 text-white'
+ : 'bg-purple-500/20 text-purple-400 hover:bg-purple-500/30'
+ }`}
+ >
+ <ScrollText className="w-4 h-4" /> Log Event
+ <ChevronDown className={`w-3 h-3 transition-transform ${activeAction === 'event' ? 'rotate-180' : ''}`} />
+ </button>
+
+ <button
+ onClick={() => handleSync('jira')}
+ disabled={syncing === 'jira'}
+ className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium bg-port-border/50 text-gray-300 hover:bg-port-border hover:text-white transition-colors disabled:opacity-50"
+ >
+ <RefreshCw className={`w-4 h-4 ${syncing === 'jira' ? 'animate-spin' : ''}`} /> Sync JIRA
+ </button>
+
+ <button
+ onClick={() => handleSync('tasks')}
+ disabled={syncing === 'tasks'}
+ className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium bg-port-border/50 text-gray-300 hover:bg-port-border hover:text-white transition-colors disabled:opacity-50"
+ >
+ <RefreshCw className={`w-4 h-4 ${syncing === 'tasks' ? 'animate-spin' : ''}`} /> Sync Tasks
+ </button>
+ </div>
+
+ {/* Inline Action Forms */}
+ {activeAction === 'damage' && (
+ <div className="mt-3 p-3 bg-port-bg rounded-lg border border-port-error/30 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-port-error">Roll Damage</span>
+ <button onClick={() => setActiveAction(null)} className="text-gray-500 hover:text-white">
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ <div className="flex flex-col sm:flex-row gap-2">
+ <div className="flex items-center gap-2">
+ <Dices className="w-4 h-4 text-gray-400" />
+ <input
+ value={dmgDice}
+ onChange={e => setDmgDice(e.target.value)}
+ placeholder="1d8"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-sm text-white w-24"
+ />
+ </div>
+ <input
+ value={dmgDesc}
+ onChange={e => setDmgDesc(e.target.value)}
+ placeholder="Description (optional)"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-sm text-white flex-1"
+ />
+ <button
+ onClick={handleDamage}
+ className="px-4 py-1.5 bg-port-error text-white rounded text-sm font-medium hover:bg-port-error/80 transition-colors"
+ >
+ Roll
+ </button>
+ </div>
+ </div>
+ )}
+
+ {activeAction === 'xp' && (
+ <div className="mt-3 p-3 bg-port-bg rounded-lg border border-port-warning/30 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-port-warning">Add Experience</span>
+ <button onClick={() => setActiveAction(null)} className="text-gray-500 hover:text-white">
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ <div className="flex flex-col sm:flex-row gap-2">
+ <input
+ type="number"
+ value={xpAmount}
+ onChange={e => setXpAmount(e.target.value)}
+ placeholder="XP amount"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-sm text-white w-28"
+ />
+ <input
+ value={xpDesc}
+ onChange={e => setXpDesc(e.target.value)}
+ placeholder="Description (optional)"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-sm text-white flex-1"
+ />
+ <button
+ onClick={handleAddXp}
+ className="px-4 py-1.5 bg-port-warning text-black rounded text-sm font-medium hover:bg-port-warning/80 transition-colors"
+ >
+ Add
+ </button>
+ </div>
+ </div>
+ )}
+
+ {activeAction === 'event' && (
+ <div className="mt-3 p-3 bg-port-bg rounded-lg border border-purple-500/30 space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium text-purple-400">Log Event</span>
+ <button onClick={() => setActiveAction(null)} className="text-gray-500 hover:text-white">
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+ <div className="flex flex-col gap-2">
+ <input
+ value={evtDesc}
+ onChange={e => setEvtDesc(e.target.value)}
+ placeholder="What happened?"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-sm text-white"
+ />
+ <div className="flex flex-col sm:flex-row gap-2">
+ <input
+ type="number"
+ value={evtXp}
+ onChange={e => setEvtXp(e.target.value)}
+ placeholder="XP (optional)"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-sm text-white w-28"
+ />
+ <div className="flex items-center gap-2">
+ <Dices className="w-4 h-4 text-gray-400" />
+ <input
+ value={evtDice}
+ onChange={e => setEvtDice(e.target.value)}
+ placeholder="Dice (e.g. 2d6)"
+ className="bg-port-card border border-port-border rounded px-2 py-1.5 text-sm text-white w-32"
+ />
+ </div>
+ <button
+ onClick={handleLogEvent}
+ className="px-4 py-1.5 bg-purple-500 text-white rounded text-sm font-medium hover:bg-purple-500/80 transition-colors"
+ >
+ Log
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* Event Log */}
+ <div className="bg-port-card border border-port-border rounded-xl flex flex-col min-h-0">
+ <div className="flex items-center gap-2 px-4 py-3 border-b border-port-border">
+ <ScrollText className="w-4 h-4 text-gray-400" />
+ <h3 className="text-sm font-medium text-gray-300">Event Log</h3>
+ <span className="text-xs text-gray-500">({char.events?.length || 0} entries)</span>
+ </div>
+ <div className="overflow-y-auto max-h-[400px] divide-y divide-port-border/50">
+ {(!char.events || char.events.length === 0) ? (
+ <div className="px-4 py-8 text-center text-gray-500 text-sm">
+ No events yet. Take an action to begin your adventure.
+ </div>
+ ) : (
+ [...char.events].reverse().map((evt, i) => {
+ const Icon = EVENT_ICONS[evt.type] || ScrollText;
+ const color = EVENT_COLORS[evt.type] || 'text-gray-400';
+ return (
+ <div key={evt.id || i} className="px-4 py-3 flex items-start gap-3 hover:bg-port-bg/50 transition-colors">
+ <div className={`mt-0.5 ${color}`}>
+ <Icon className="w-4 h-4" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-baseline gap-2 flex-wrap">
+ <span className="text-sm text-white">{evt.description}</span>
+ {evt.xp > 0 && (
+ <span className="text-xs font-medium text-port-success">
+ +{evt.xp} XP
+ </span>
+ )}
+ {evt.damage > 0 && (
+ <span className="text-xs font-medium text-port-error">
+ -{evt.damage} HP
+ </span>
+ )}
+ {evt.hpRecovered > 0 && (
+ <span className="text-xs font-medium text-port-success">
+ +{evt.hpRecovered} HP
+ </span>
+ )}
+ </div>
+ {evt.diceNotation && (
+ <div className="flex items-center gap-1.5 mt-1">
+ <Dices className="w-3 h-3 text-gray-500" />
+ <span className="text-xs text-gray-500">
+ {evt.diceNotation}
+ {evt.diceRolls && evt.diceRolls.length > 0 && (
+ <> = [{evt.diceRolls.join(', ')}] = {evt.damage}</>
+ )}
+ </span>
+ </div>
+ )}
+ </div>
+ <span className="text-xs text-gray-600 whitespace-nowrap mt-0.5">
+ {relativeTime(evt.timestamp)}
+ </span>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/server/index.js b/server/index.js
index 26d744d7cb..df569a2c4e 100644
--- a/server/index.js
+++ b/server/index.js
@@ -61,6 +61,7 @@ import settingsRoutes from './routes/settings.js';
import telegramRoutes from './routes/telegram.js';
import updateRoutes from './routes/update.js';
import loopsRoutes from './routes/loops.js';
+import characterRoutes from './routes/character.js';
import { ensureSelf, startPolling } from './services/instances.js';
import { initSyncLog } from './services/brainSyncLog.js';
import { backfillOriginInstanceId } from './services/brainStorage.js';
@@ -258,6 +259,7 @@ app.use('/api/settings', settingsRoutes);
app.use('/api/telegram', telegramRoutes);
app.use('/api/update', updateRoutes);
app.use('/api/loops', loopsRoutes);
+app.use('/api/character', characterRoutes);
// Initialize agent automation scheduler and action executor
automationScheduler.init().catch(err => console.error(`❌ Agent scheduler init failed: ${err.message}`));
diff --git a/server/routes/character.js b/server/routes/character.js
new file mode 100644
index 0000000000..d73d9d5168
--- /dev/null
+++ b/server/routes/character.js
@@ -0,0 +1,109 @@
+/**
+ * Character Sheet Routes
+ * D&D-style character sheet with XP, HP, damage, rests, and event tracking.
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as characterService from '../services/character.js';
+
+const router = Router();
+
+// Zod schemas for request validation
+const updateCharacterSchema = z.object({
+ name: z.string().min(1).max(100).optional(),
+ class: z.string().min(1).max(100).optional()
+});
+
+const addXPSchema = z.object({
+ amount: z.number().int().min(1),
+ source: z.string().min(1).max(200),
+ description: z.string().max(500).optional()
+});
+
+const takeDamageSchema = z.object({
+ diceNotation: z.string().regex(/^\d+d\d+([+-]\d+)?$/, 'Invalid dice notation (e.g. "1d8", "2d6+3")'),
+ description: z.string().max(500).optional()
+});
+
+const takeRestSchema = z.object({
+ type: z.enum(['short', 'long'])
+});
+
+const addEventSchema = z.object({
+ description: z.string().min(1).max(500),
+ xp: z.number().int().min(0).optional(),
+ diceNotation: z.string().regex(/^\d+d\d+([+-]\d+)?$/).optional(),
+ damageType: z.string().max(100).optional()
+});
+
+// GET /api/character - Get character sheet
+router.get('/', asyncHandler(async (req, res) => {
+ const character = await characterService.getCharacter();
+ res.json(character);
+}));
+
+// PUT /api/character - Update character name/class
+router.put('/', asyncHandler(async (req, res) => {
+ const data = validateRequest(updateCharacterSchema, req.body);
+ const character = await characterService.getCharacter();
+ if (data.name) character.name = data.name;
+ if (data.class) character.class = data.class;
+ const updated = await characterService.saveCharacter(character);
+ res.json(updated);
+}));
+
+// POST /api/character/xp - Add XP manually
+router.post('/xp', asyncHandler(async (req, res) => {
+ const { amount, source, description } = validateRequest(addXPSchema, req.body);
+ const result = await characterService.addXP(amount, source, description);
+ res.json(result);
+}));
+
+// POST /api/character/damage - Take damage
+router.post('/damage', asyncHandler(async (req, res) => {
+ const { diceNotation, description } = validateRequest(takeDamageSchema, req.body);
+ const result = await characterService.takeDamage(diceNotation, description);
+ res.json(result);
+}));
+
+// POST /api/character/rest - Take a rest
+router.post('/rest', asyncHandler(async (req, res) => {
+ const { type } = validateRequest(takeRestSchema, req.body);
+ const result = await characterService.takeRest(type);
+ res.json(result);
+}));
+
+// POST /api/character/event - Log custom event
+router.post('/event', asyncHandler(async (req, res) => {
+ const data = validateRequest(addEventSchema, req.body);
+ const result = await characterService.addEvent(data);
+ res.json(result);
+}));
+
+// POST /api/character/sync/jira - Sync JIRA tickets for XP
+router.post('/sync/jira', asyncHandler(async (req, res) => {
+ const result = await characterService.syncJiraXP();
+ res.json(result);
+}));
+
+// POST /api/character/sync/tasks - Sync CoS tasks for XP
+router.post('/sync/tasks', asyncHandler(async (req, res) => {
+ const result = await characterService.syncTaskXP();
+ res.json(result);
+}));
+
+// POST /api/character/reset - Reset character (fresh start)
+router.post('/reset', asyncHandler(async (req, res) => {
+ const character = await characterService.saveCharacter(
+ Object.assign(
+ { name: 'Adventurer', class: 'Developer', xp: 0, hp: 15, maxHp: 15, level: 1, events: [], syncedJiraTickets: [], syncedTaskIds: [] },
+ { createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
+ )
+ );
+ res.json(character);
+}));
+
+export default router;
diff --git a/server/services/character.js b/server/services/character.js
new file mode 100644
index 0000000000..f7679e0fb7
--- /dev/null
+++ b/server/services/character.js
@@ -0,0 +1,395 @@
+/**
+ * Character Sheet Service
+ * D&D-style character sheet tracking XP, HP, level, damage, rests, and events.
+ */
+
+import crypto from 'crypto';
+import path from 'path';
+import { readFile, writeFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import * as jiraService from './jira.js';
+import * as cosService from './cos.js';
+
+const CHARACTER_FILE = path.join(PATHS.data, 'character.json');
+
+// D&D 5e XP thresholds per level
+const XP_THRESHOLDS = [
+ 0, // Level 1
+ 300, // Level 2
+ 900, // Level 3
+ 2700, // Level 4
+ 6500, // Level 5
+ 14000, // Level 6
+ 23000, // Level 7
+ 34000, // Level 8
+ 48000, // Level 9
+ 64000, // Level 10
+ 85000, // Level 11
+ 100000, // Level 12
+ 120000, // Level 13
+ 140000, // Level 14
+ 165000, // Level 15
+ 195000, // Level 16
+ 225000, // Level 17
+ 265000, // Level 18
+ 305000, // Level 19
+ 355000 // Level 20
+];
+
+/**
+ * Calculate level from XP using D&D 5e thresholds
+ */
+function getLevelFromXP(xp) {
+ for (let i = XP_THRESHOLDS.length - 1; i >= 0; i--) {
+ if (xp >= XP_THRESHOLDS[i]) return i + 1;
+ }
+ return 1;
+}
+
+/**
+ * Calculate max HP: base 10 + (level * 5)
+ */
+function getMaxHP(level) {
+ return 10 + (level * 5);
+}
+
+/**
+ * Create default character data
+ */
+function createDefaultCharacter() {
+ const now = new Date().toISOString();
+ return {
+ name: 'Adventurer',
+ class: 'Developer',
+ xp: 0,
+ hp: 15,
+ maxHp: 15,
+ level: 1,
+ events: [],
+ syncedJiraTickets: [],
+ syncedTaskIds: [],
+ createdAt: now,
+ updatedAt: now
+ };
+}
+
+/**
+ * Load character data, creating defaults if file doesn't exist
+ */
+export async function getCharacter() {
+ await ensureDir(PATHS.data);
+ if (!existsSync(CHARACTER_FILE)) {
+ const character = createDefaultCharacter();
+ await saveCharacter(character);
+ return character;
+ }
+ const content = await readFile(CHARACTER_FILE, 'utf-8');
+ return JSON.parse(content);
+}
+
+/**
+ * Save character data to disk
+ */
+export async function saveCharacter(data) {
+ await ensureDir(PATHS.data);
+ data.updatedAt = new Date().toISOString();
+ await writeFile(CHARACTER_FILE, JSON.stringify(data, null, 2));
+ return data;
+}
+
+/**
+ * Parse dice notation like "1d8", "2d6+3", "1d20-1"
+ * Returns { rolls, modifier, total }
+ */
+export function rollDice(notation) {
+ const match = notation.match(/^(\d+)d(\d+)([+-]\d+)?$/);
+ if (!match) {
+ throw new Error(`Invalid dice notation: ${notation}`);
+ }
+
+ const count = parseInt(match[1], 10);
+ const sides = parseInt(match[2], 10);
+ const modifier = match[3] ? parseInt(match[3], 10) : 0;
+
+ const rolls = [];
+ for (let i = 0; i < count; i++) {
+ rolls.push(Math.floor(Math.random() * sides) + 1);
+ }
+
+ const total = rolls.reduce((sum, r) => sum + r, 0) + modifier;
+
+ return { rolls, modifier, total: Math.max(0, total) };
+}
+
+/**
+ * Add XP and check for level up
+ * Returns { character, leveledUp, newLevel }
+ */
+export async function addXP(amount, source, description) {
+ const character = await getCharacter();
+ const oldLevel = character.level;
+
+ character.xp += amount;
+ character.level = getLevelFromXP(character.xp);
+ character.maxHp = getMaxHP(character.level);
+
+ // If leveled up, heal to new max HP
+ const leveledUp = character.level > oldLevel;
+ if (leveledUp) {
+ character.hp = character.maxHp;
+ console.log(`🎉 Level up! ${oldLevel} -> ${character.level}`);
+ }
+
+ const event = {
+ id: crypto.randomUUID(),
+ type: 'xp',
+ description: description || `Gained ${amount} XP from ${source}`,
+ xp: amount,
+ damage: 0,
+ diceNotation: null,
+ diceRolls: [],
+ hpRecovered: 0,
+ timestamp: new Date().toISOString()
+ };
+
+ character.events.push(event);
+ await saveCharacter(character);
+
+ console.log(`✨ +${amount} XP (${source}) — total ${character.xp} XP, level ${character.level}`);
+ return { character, leveledUp, newLevel: character.level };
+}
+
+/**
+ * Roll dice and apply damage
+ * Returns { character, roll, totalDamage }
+ */
+export async function takeDamage(diceNotation, description) {
+ const character = await getCharacter();
+ const roll = rollDice(diceNotation);
+
+ character.hp = Math.max(0, character.hp - roll.total);
+
+ const event = {
+ id: crypto.randomUUID(),
+ type: 'damage',
+ description: description || `Took ${roll.total} damage (${diceNotation})`,
+ xp: 0,
+ damage: roll.total,
+ diceNotation,
+ diceRolls: roll.rolls,
+ hpRecovered: 0,
+ timestamp: new Date().toISOString()
+ };
+
+ character.events.push(event);
+ await saveCharacter(character);
+
+ console.log(`💥 ${roll.total} damage (${diceNotation}: [${roll.rolls}]+${roll.modifier}) — ${character.hp}/${character.maxHp} HP`);
+ return { character, roll, totalDamage: roll.total };
+}
+
+/**
+ * Take a short or long rest
+ * Returns { character, hpRecovered }
+ */
+export async function takeRest(type) {
+ const character = await getCharacter();
+ const oldHp = character.hp;
+
+ if (type === 'long') {
+ character.hp = character.maxHp;
+ } else {
+ const recovery = Math.floor(character.maxHp * 0.25);
+ character.hp = Math.min(character.maxHp, character.hp + recovery);
+ }
+
+ const hpRecovered = character.hp - oldHp;
+
+ const event = {
+ id: crypto.randomUUID(),
+ type: 'rest',
+ description: `${type === 'long' ? 'Long' : 'Short'} rest — recovered ${hpRecovered} HP`,
+ xp: 0,
+ damage: 0,
+ diceNotation: null,
+ diceRolls: [],
+ hpRecovered,
+ timestamp: new Date().toISOString()
+ };
+
+ character.events.push(event);
+ await saveCharacter(character);
+
+ console.log(`🛏️ ${type} rest — recovered ${hpRecovered} HP (${character.hp}/${character.maxHp})`);
+ return { character, hpRecovered };
+}
+
+/**
+ * Log a custom event with optional XP and/or damage
+ */
+export async function addEvent(event) {
+ const character = await getCharacter();
+ const oldLevel = character.level;
+ let roll = null;
+ let leveledUp = false;
+
+ if (event.xp) {
+ character.xp += event.xp;
+ character.level = getLevelFromXP(character.xp);
+ character.maxHp = getMaxHP(character.level);
+ leveledUp = character.level > oldLevel;
+ if (leveledUp) {
+ character.hp = character.maxHp;
+ }
+ }
+
+ if (event.diceNotation) {
+ roll = rollDice(event.diceNotation);
+ character.hp = Math.max(0, character.hp - roll.total);
+ }
+
+ const logEntry = {
+ id: crypto.randomUUID(),
+ type: 'custom',
+ description: event.description,
+ xp: event.xp || 0,
+ damage: roll ? roll.total : 0,
+ diceNotation: event.diceNotation || null,
+ diceRolls: roll ? roll.rolls : [],
+ hpRecovered: 0,
+ timestamp: new Date().toISOString()
+ };
+
+ character.events.push(logEntry);
+ await saveCharacter(character);
+
+ console.log(`📝 Custom event: ${event.description}`);
+ return { character, event: logEntry, leveledUp };
+}
+
+/**
+ * Sync JIRA tickets for XP — awards XP for Done tickets not already tracked
+ */
+export async function syncJiraXP() {
+ const character = await getCharacter();
+ const config = await jiraService.getInstances();
+ const instances = config.instances || {};
+ let totalXP = 0;
+ let ticketCount = 0;
+
+ for (const [instanceId, instance] of Object.entries(instances)) {
+ // Get projects for this instance
+ let projects;
+ try {
+ projects = await jiraService.getProjects(instanceId);
+ } catch {
+ console.log(`⚠️ Could not fetch projects for JIRA instance ${instanceId}`);
+ continue;
+ }
+
+ for (const project of projects) {
+ let tickets;
+ try {
+ tickets = await jiraService.getMyCurrentSprintTickets(instanceId, project.key);
+ } catch {
+ console.log(`⚠️ Could not fetch tickets for ${project.key}`);
+ continue;
+ }
+ const doneTickets = tickets.filter(t =>
+ t.statusCategory === 'Done' || t.status === 'Done'
+ );
+
+ for (const ticket of doneTickets) {
+ if (character.syncedJiraTickets.includes(ticket.key)) continue;
+
+ const xp = (ticket.storyPoints || 1) * 50;
+ character.xp += xp;
+ totalXP += xp;
+ ticketCount++;
+
+ character.syncedJiraTickets.push(ticket.key);
+
+ character.events.push({
+ id: crypto.randomUUID(),
+ type: 'xp',
+ description: `JIRA ${ticket.key}: ${ticket.summary} (${ticket.storyPoints || 0} pts)`,
+ xp,
+ damage: 0,
+ diceNotation: null,
+ diceRolls: [],
+ hpRecovered: 0,
+ timestamp: new Date().toISOString()
+ });
+ }
+ }
+ }
+
+ // Recalculate level after all XP added
+ const oldLevel = character.level;
+ character.level = getLevelFromXP(character.xp);
+ character.maxHp = getMaxHP(character.level);
+ const leveledUp = character.level > oldLevel;
+ if (leveledUp) {
+ character.hp = character.maxHp;
+ }
+
+ await saveCharacter(character);
+
+ console.log(`🎫 Synced ${ticketCount} JIRA tickets for ${totalXP} XP`);
+ return { character, ticketCount, totalXP, leveledUp };
+}
+
+/**
+ * Sync CoS tasks for XP — awards 25 XP for completed tasks not already tracked
+ */
+export async function syncTaskXP() {
+ const character = await getCharacter();
+ const { user: userTasks, cos: cosTasks } = await cosService.getAllTasks();
+ let totalXP = 0;
+ let taskCount = 0;
+
+ const allTasks = [
+ ...(userTasks.tasks || []),
+ ...(cosTasks.tasks || [])
+ ];
+
+ const completedTasks = allTasks.filter(t => t.status === 'completed');
+
+ for (const task of completedTasks) {
+ if (character.syncedTaskIds.includes(task.id)) continue;
+
+ const xp = 25;
+ character.xp += xp;
+ totalXP += xp;
+ taskCount++;
+
+ character.syncedTaskIds.push(task.id);
+
+ character.events.push({
+ id: crypto.randomUUID(),
+ type: 'xp',
+ description: `Task: ${task.title || task.description || task.id}`,
+ xp,
+ damage: 0,
+ diceNotation: null,
+ diceRolls: [],
+ hpRecovered: 0,
+ timestamp: new Date().toISOString()
+ });
+ }
+
+ // Recalculate level after all XP added
+ const oldLevel = character.level;
+ character.level = getLevelFromXP(character.xp);
+ character.maxHp = getMaxHP(character.level);
+ const leveledUp = character.level > oldLevel;
+ if (leveledUp) {
+ character.hp = character.maxHp;
+ }
+
+ await saveCharacter(character);
+
+ console.log(`✅ Synced ${taskCount} tasks for ${totalXP} XP`);
+ return { character, taskCount, totalXP, leveledUp };
+}