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

simplify character sheet: extract helpers, reuse existing utils

Adam Eivya50d23873af7
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
index 48404214ac..a3cbaf453b 100644
--- a/client/src/pages/CharacterSheet.jsx
+++ b/client/src/pages/CharacterSheet.jsx
@@ -3,22 +3,17 @@ import {
Sword, Star, Moon, ScrollText, Shield, Heart,
Sparkles, RefreshCw, Dices, X, ChevronDown, Zap
} from 'lucide-react';
+import { timeAgo } from '../utils/formatters';
-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)
- });
+const request = (endpoint, options = {}) =>
+ fetch(`/api/character${endpoint}`, {
+ headers: { 'Content-Type': 'application/json', ...options.headers },
+ ...options
+ }).then(r => r.json());
+
+const get = () => request('');
+const post = (path, body) => request(path, { method: 'POST', body: JSON.stringify(body) });
+const put = (body) => request('', { method: 'PUT', body: JSON.stringify(body) });
// D&D 5e XP thresholds (must match server)
const XP_THRESHOLDS = [
@@ -50,18 +45,6 @@ const EVENT_COLORS = {
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';
@@ -527,7 +510,7 @@ export default function CharacterSheet() {
)}
</div>
<span className="text-xs text-gray-600 whitespace-nowrap mt-0.5">
- {relativeTime(evt.timestamp)}
+ {timeAgo(evt.timestamp)}
</span>
</div>
);
diff --git a/server/routes/character.js b/server/routes/character.js
index d73d9d5168..c5b59da787 100644
--- a/server/routes/character.js
+++ b/server/routes/character.js
@@ -97,12 +97,7 @@ router.post('/sync/tasks', asyncHandler(async (req, res) => {
// 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() }
- )
- );
+ const character = await characterService.saveCharacter(characterService.createDefaultCharacter());
res.json(character);
}));
diff --git a/server/services/character.js b/server/services/character.js
index f7679e0fb7..eca2ed4c02 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -1,45 +1,22 @@
/**
* Character Sheet Service
- * D&D-style character sheet tracking XP, HP, level, damage, rests, and events.
+ * D&D 5e-style character 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 { writeFile } from 'fs/promises';
+import { ensureDir, readJSONFile, 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
+ 0, 300, 900, 2700, 6500, 14000, 23000, 34000, 48000, 64000,
+ 85000, 100000, 120000, 140000, 165000, 195000, 225000, 265000, 305000, 355000
];
-/**
- * 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;
@@ -47,17 +24,38 @@ function getLevelFromXP(xp) {
return 1;
}
-/**
- * Calculate max HP: base 10 + (level * 5)
- */
function getMaxHP(level) {
return 10 + (level * 5);
}
-/**
- * Create default character data
- */
-function createDefaultCharacter() {
+function createEvent(type, description, overrides = {}) {
+ return {
+ id: crypto.randomUUID(),
+ type,
+ description,
+ xp: 0,
+ damage: 0,
+ diceNotation: null,
+ diceRolls: [],
+ hpRecovered: 0,
+ ...overrides,
+ timestamp: new Date().toISOString()
+ };
+}
+
+function recalcLevel(character) {
+ 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;
+ console.log(`🎉 Level up! ${oldLevel} -> ${character.level}`);
+ }
+ return leveledUp;
+}
+
+export function createDefaultCharacter() {
const now = new Date().toISOString();
return {
name: 'Adventurer',
@@ -74,23 +72,14 @@ function createDefaultCharacter() {
};
}
-/**
- * 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);
+ const data = await readJSONFile(CHARACTER_FILE, null);
+ if (data) return data;
+ const character = createDefaultCharacter();
+ await saveCharacter(character);
+ return character;
}
-/**
- * Save character data to disk
- */
export async function saveCharacter(data) {
await ensureDir(PATHS.data);
data.updatedAt = new Date().toISOString();
@@ -98,15 +87,9 @@ export async function saveCharacter(data) {
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}`);
- }
+ if (!match) throw new Error(`Invalid dice notation: ${notation}`);
const count = parseInt(match[1], 10);
const sides = parseInt(match[2], 10);
@@ -118,81 +101,36 @@ export function rollDice(notation) {
}
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()
- };
+ const leveledUp = recalcLevel(character);
- character.events.push(event);
+ character.events.push(createEvent('xp', description || `Gained ${amount} XP from ${source}`, { xp: amount }));
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);
+ character.events.push(createEvent('damage', description || `Took ${roll.total} damage (${diceNotation})`, {
+ damage: roll.total, diceNotation, diceRolls: roll.rolls
+ }));
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;
@@ -200,48 +138,24 @@ export async function takeRest(type) {
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);
+ character.hp = Math.min(character.maxHp, character.hp + Math.floor(character.maxHp * 0.25));
}
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);
+ character.events.push(createEvent('rest', `${type === 'long' ? 'Long' : 'Short'} rest — recovered ${hpRecovered} HP`, { hpRecovered }));
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) {
@@ -249,17 +163,14 @@ export async function addEvent(event) {
character.hp = Math.max(0, character.hp - roll.total);
}
- const logEntry = {
- id: crypto.randomUUID(),
- type: 'custom',
- description: event.description,
+ const leveledUp = recalcLevel(character);
+
+ const logEntry = createEvent('custom', 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()
- };
+ diceRolls: roll ? roll.rolls : []
+ });
character.events.push(logEntry);
await saveCharacter(character);
@@ -268,9 +179,6 @@ export async function addEvent(event) {
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();
@@ -278,8 +186,7 @@ export async function syncJiraXP() {
let totalXP = 0;
let ticketCount = 0;
- for (const [instanceId, instance] of Object.entries(instances)) {
- // Get projects for this instance
+ for (const [instanceId] of Object.entries(instances)) {
let projects;
try {
projects = await jiraService.getProjects(instanceId);
@@ -296,98 +203,47 @@ export async function syncJiraXP() {
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) {
+ for (const ticket of tickets.filter(t => t.statusCategory === 'Done' || t.status === 'Done')) {
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()
- });
+ character.events.push(createEvent('xp', `JIRA ${ticket.key}: ${ticket.summary} (${ticket.storyPoints || 0} pts)`, { xp }));
}
}
}
- // 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;
- }
-
+ const leveledUp = recalcLevel(character);
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 allTasks = [...(userTasks.tasks || []), ...(cosTasks.tasks || [])];
- const completedTasks = allTasks.filter(t => t.status === 'completed');
-
- for (const task of completedTasks) {
+ for (const task of allTasks.filter(t => t.status === 'completed')) {
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;
+ character.events.push(createEvent('xp', `Task: ${task.title || task.description || task.id}`, { xp }));
}
+ const leveledUp = recalcLevel(character);
await saveCharacter(character);
console.log(`✅ Synced ${taskCount} tasks for ${totalXP} XP`);