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: derive per-domain character skills on read (#2674)
[._.]/ Adam Eivy43aebd9f9985
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8b36594397..f7e62f94ca 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- [issue-2674] **Your Character sheet now has skills that reflect how you actually use PortOS.** Six skills — Wordsmith (Create/Writers Room), Mentalist (POST), Vitalist (health logging), Strategist (goal discipline), Archivist (Brain/memory), and Auteur (media) — level up from the work you've already done, on a curve where each doubling of use earns a level, so they climb quickly at first and then ask for real commitment. Nothing new is tracked to make this work: each skill reads the stats its domain already keeps, so the skills are accurate from the moment you upgrade rather than starting everyone at zero. A domain you've never touched is honestly level 0; a domain whose stats can't be read says "Unavailable" instead of pretending it's zero. Skills are computed fresh on every read and never saved or synced between your machines — usage differs per machine, so syncing them would let the laptop you barely open overwrite the desktop you live in.+- **Creative Director now has its own Model defaults.** The Creative Director index page gets a **Model defaults** button (deep-linkable at `?models=1`) that pins the provider + model every project uses for Treatment, Production plan, and Scene evaluation — the settings that previously existed only as three rows buried in the global AI Assignments table. Individual projects still override them from their own Models drawer, which now says which default it's inheriting; leaving a stage blank at the Creative Director level falls through to the system default provider, exactly as before. Both surfaces are the same drawer, so the two scopes can't drift.- **The Brain daily log now saves itself.** Your entry is saved automatically as you type (about a second and a half after you pause, and at least every ten seconds during a long uninterrupted writing run), when you click away from the editor, when you switch tabs or navigate away, and when you background the tab or app — so a closed laptop or a backgrounded phone no longer loses the day. The toolbar shows the current state (`Unsaved…` / `Saving…` / `Saved`) in place of a toast on every autosave; the Save button and ⌘S still work and still confirm with a toast. Autosave never reverts what you're typing mid-save, never writes one day's text into another when you change dates, keeps debouncing instead of retrying per keystroke when the server is unreachable, and deliberately stands down when a dictated voice segment arrives while you have unsaved edits (the toolbar says "Autosave paused — save to keep your edits") — a full-content save would otherwise drop the segment.diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsxindex 40361d0745..bbf8526d0d 100644--- a/client/src/pages/CharacterSheet.jsx+++ b/client/src/pages/CharacterSheet.jsx@@ -42,6 +42,44 @@ function hpColor(pct) {return 'bg-port-error';}+// Per-domain skills derived on read from each domain's existing stats (#2674). Deliberately+// a plain read-only card: Slice 5 (#2677) owns the page's framing/redesign, so this stays+// easy to restyle or relocate wholesale.+//+// `unavailable` renders as an explicit "—" rather than a 0: the server distinguishes an+// untouched domain (a real level 0) from one whose stat could not be read, and collapsing+// those here would re-introduce the exact lie the server's sentinel exists to prevent.+function SkillsCard({ skills }) {+ if (!skills?.length) return null;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4">+ <div className="flex items-center gap-1.5 mb-3">+ <Zap className="w-4 h-4 text-port-accent-2" />+ <h2 className="text-sm font-medium text-gray-300">Skills</h2>+ <span className="text-xs text-gray-500">— earned by using PortOS</span>+ </div>+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">+ {skills.map((skill) => (+ <div key={skill.id} className="bg-port-bg border border-port-border rounded-lg px-3 py-2">+ <div className="flex items-baseline justify-between gap-2">+ <span className="text-sm text-gray-300 truncate">{skill.label}</span>+ {skill.unavailable ? (+ <span className="text-sm text-gray-600" title="This domain's stats could not be read">—</span>+ ) : (+ <span className="text-sm font-semibold text-port-accent-2">Lv {skill.level}</span>+ )}+ </div>+ <div className="text-xs text-gray-500 mt-0.5">+ {skill.unavailable ? 'Unavailable' : `${skill.value} logged`}+ </div>+ </div>+ ))}+ </div>+ </div>+ );+}+export default function CharacterSheet() {const [char, setChar] = useState(null);const [loading, setLoading] = useState(true);@@ -463,6 +501,9 @@ export default function CharacterSheet() {)}</div>+ {/* Skills — derived per-domain from real PortOS usage (#2674) */}+ <SkillsCard skills={char.skills} />+{/* Quick Actions */}<div className="bg-port-card border border-port-border rounded-xl p-4"><div className="flex flex-wrap gap-2">diff --git a/server/routes/character.js b/server/routes/character.jsindex 522e5a75a8..a67d0c98b8 100644--- a/server/routes/character.js+++ b/server/routes/character.js@@ -1,6 +1,9 @@/*** Character Sheet Routes- * D&D-style character sheet with XP, HP, damage, rests, and event tracking.+ *+ * `GET /` returns the persisted record plus the fields derived on read: the+ * age-based `level`/`ageYears` (#2673) and the per-domain `skills` (#2674).+ * The XP/HP/damage/rest/event endpoints are retained for backward-compat.*/import { Router } from 'express';@@ -48,12 +51,7 @@ router.get('/', asyncHandler(async (req, res) => {// PUT /api/character - Update character name/classrouter.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;- if (data.avatarPath) character.avatarPath = data.avatarPath;- const updated = await characterService.saveCharacter(character);- res.json(updated);+ res.json(await characterService.updateCharacterFields(data));}));// POST /api/character/xp - Add XP manuallydiff --git a/server/services/character.js b/server/services/character.jsindex 30beebfe9c..b2ec21dba9 100644--- a/server/services/character.js+++ b/server/services/character.js@@ -6,6 +6,9 @@* (see #2673, epic #2672). `xp` survives only as a cumulative stat — it no longer* drives level. HP/damage/rest mechanics are retained for backward-compat with a* flat maxHp (no longer scaled off level).+ *+ * `skills` are likewise derived on read, from each domain's existing stats+ * (see `characterSkills.js`, #2674).*/import crypto from 'crypto';@@ -14,6 +17,7 @@ import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.jsimport * as jiraService from './jira.js';import * as cosService from './cos.js';import { getBirthDate } from './meatspace.js';+import { getCharacterSkills } from './characterSkills.js';const CHARACTER_FILE = path.join(PATHS.data, 'character.json');@@ -22,8 +26,9 @@ const CHARACTER_FILE = path.join(PATHS.data, 'character.json');const DEFAULT_MAX_HP = 15;// Derived fields getCharacter() attaches on read; they are stripped before persisting so a-// stale age-level never lands on disk or in the federated snapshot.-const DERIVED_FIELDS = ['level', 'ageYears'];+// stale age-level (or a per-machine usage-derived skill set) never lands on disk or in the+// federated snapshot. `skills` is per-machine by design — see characterSkills.js (#2674).+const DERIVED_FIELDS = ['level', 'ageYears', 'skills'];// Pure: fractional years lived since birthDate (whole years + progress toward the next// birthday), or null when birthDate is unset/invalid/future. Uses **calendar** birthdays,@@ -119,18 +124,34 @@ async function loadRawCharacter() {return character;}-// Attach the age-derived read-only fields (`ageYears`, `level`) to a raw record. `level` is-// null when no birthDate is set, so callers can render a "set your birth date" prompt.+// Attach the derived read-only fields to a raw record: `ageYears`/`level` from the canonical+// birthDate (#2673), and the per-domain `skills` from each domain's existing stats (#2674).+// `level` is null when no birthDate is set, so callers can render a "set your birth date"+// prompt. Neither is ever persisted — see DERIVED_FIELDS / saveCharacter.async function enrichCharacter(raw) {- const { birthDate } = await getBirthDate().catch(() => ({ birthDate: null }));+ const [{ birthDate }, skills] = await Promise.all([+ getBirthDate().catch(() => ({ birthDate: null })),+ getCharacterSkills(),+ ]);const ageYears = ageYearsFromBirthDate(birthDate);- return { ...raw, ageYears, level: levelFromAge(ageYears) };+ return { ...raw, ageYears, level: levelFromAge(ageYears), skills };}export async function getCharacter() {return enrichCharacter(await loadRawCharacter());}+// Apply a partial patch of human-authored fields (name/class/avatarPath). Reads the RAW+// record so the derived fan-out runs once — on the enriched record saveCharacter returns —+// rather than once here and once again on save.+export async function updateCharacterFields(patch = {}) {+ const character = await loadRawCharacter();+ for (const [key, value] of Object.entries(patch)) {+ if (value !== undefined) character[key] = value;+ }+ return saveCharacter(character);+}+// Federation wire projection: the persisted record plus a backward-compatible integer `level`// for pre-#2673 peers, whose CharacterSheet indexes XP thresholds by `character.level` and// NaNs without it. The level is the LEGACY xp-derived value (what those peers compute from the@@ -161,9 +182,7 @@ export async function saveCharacter(data) {// avatar-generation route fold persistence in (it already knows the character// context) instead of forcing a second `PUT /api/character` round-trip.export async function setAvatar(avatarPath) {- const character = await getCharacter();- character.avatarPath = avatarPath;- await saveCharacter(character);+ const character = await updateCharacterFields({ avatarPath });console.log(`🖼️ Character avatar set → ${avatarPath}`);return character;}@@ -186,7 +205,7 @@ export function rollDice(notation) {}export async function addXP(amount, source, description) {- const character = await getCharacter();+ const character = await loadRawCharacter();character.xp += amount;character.events.push(createEvent('xp', description || `Gained ${amount} XP from ${source}`, { xp: amount }));@@ -198,7 +217,7 @@ export async function addXP(amount, source, description) {}export async function takeDamage(diceNotation, description) {- const character = await getCharacter();+ const character = await loadRawCharacter();const roll = rollDice(diceNotation);character.hp = Math.max(0, character.hp - roll.total);@@ -213,7 +232,7 @@ export async function takeDamage(diceNotation, description) {}export async function takeRest(type) {- const character = await getCharacter();+ const character = await loadRawCharacter();const oldHp = character.hp;if (type === 'long') {@@ -232,7 +251,7 @@ export async function takeRest(type) {}export async function addEvent(event) {- const character = await getCharacter();+ const character = await loadRawCharacter();let roll = null;if (event.xp) {@@ -261,7 +280,7 @@ export async function addEvent(event) {const delay = ms => new Promise(r => setTimeout(r, ms));export async function syncJiraXP() {- const character = await getCharacter();+ const character = await loadRawCharacter();const config = await jiraService.getInstances();const instances = config.instances || {};let totalXP = 0;@@ -307,7 +326,7 @@ export async function syncJiraXP() {}export async function syncTaskXP() {- const character = await getCharacter();+ const character = await loadRawCharacter();const { user: userTasks, cos: cosTasks } = await cosService.getAllTasks();let totalXP = 0;let taskCount = 0;diff --git a/server/services/character.test.js b/server/services/character.test.jsindex 95c4dc3cf9..11880914f7 100644--- a/server/services/character.test.js+++ b/server/services/character.test.js@@ -20,11 +20,18 @@ vi.mock('../lib/fileUtils.js', () => ({}),}));-// character.js eagerly imports the jira/cos/meatspace services at module load; stub them-// so the unit under test loads without their dependency graphs. meatspace supplies the-// canonical birthDate that age-based level derives from (#2673).+// character.js eagerly imports the jira/cos/meatspace/characterSkills services at module+// load; stub them so the unit under test loads without their dependency graphs. meatspace+// supplies the canonical birthDate that age-based level derives from (#2673). The skill+// registry (#2674) fans out to every domain's stats and has its own suite+// (characterSkills.test.js) — here we only care THAT its output is attached on read and+// stripped on save, so a single sentinel skill stands in for the real six.+const FAKE_SKILLS = [{ id: 'wordsmith', label: 'Wordsmith', domain: 'create', level: 2, value: 7, unavailable: false }];vi.mock('./jira.js', () => ({}));vi.mock('./cos.js', () => ({}));+vi.mock('./characterSkills.js', () => ({+ getCharacterSkills: vi.fn(async () => FAKE_SKILLS),+}));vi.mock('./meatspace.js', () => ({getBirthDate: vi.fn(async () => ({ birthDate: store.birthDate })),}));@@ -139,6 +146,72 @@ describe('getWireCharacter federation projection', () => {const fresh = await characterService.getWireCharacter();expect(fresh.level).toBe(1); // 0 xp → level 1, never null});++ it('never federates the usage-derived skills', async () => {+ // Skills are per-machine (usage differs across a user's peers), so sending them would let+ // the least-used peer clobber the most-used one under LWW. getWireCharacter reads+ // character.json directly, so this holds as long as skills are never persisted.+ const wire = await characterService.getWireCharacter();+ expect(wire.skills).toBeUndefined();+ });+});++describe('getCharacter skills (derived on read, #2674)', () => {+ beforeEach(() => {+ store.value = { name: 'Gandalf', class: 'Wizard', xp: 0, hp: 15, maxHp: 15, events: [] };+ store.birthDate = null;+ });++ it('attaches the skill registry output on read', async () => {+ const character = await characterService.getCharacter();+ expect(character.skills).toEqual(FAKE_SKILLS);+ });++ it('never persists skills to character.json', async () => {+ const character = await characterService.getCharacter();+ expect(character.skills).toBeDefined();++ // Round-trip the enriched record straight back through save — the path a caller takes+ // when it reads, mutates, and writes — and the derived skills must not survive it.+ await characterService.saveCharacter(character);+ expect(store.value.skills).toBeUndefined();+ expect(store.value.level).toBeUndefined();+ expect(store.value.ageYears).toBeUndefined();+ });++ it('re-derives skills on the record that save returns', async () => {+ const saved = await characterService.saveCharacter(await characterService.getCharacter());+ expect(saved.skills).toEqual(FAKE_SKILLS);+ });++ it('keeps a stale persisted skills array from leaking through as truth', async () => {+ // An older/hand-edited character.json (or a peer that once persisted them) may carry a+ // stored skills key. The read must overwrite it with freshly-derived values.+ store.value = { ...store.value, skills: [{ id: 'stale', level: 99 }] };+ const character = await characterService.getCharacter();+ expect(character.skills).toEqual(FAKE_SKILLS);+ });+});++describe('updateCharacterFields', () => {+ beforeEach(() => {+ store.value = { name: 'Gandalf', class: 'Wizard', xp: 0, hp: 15, maxHp: 15, events: [] };+ store.birthDate = null;+ });++ it('applies only the provided fields and returns the enriched record', async () => {+ const updated = await characterService.updateCharacterFields({ name: 'Radagast' });+ expect(updated.name).toBe('Radagast');+ expect(updated.class).toBe('Wizard'); // untouched+ expect(updated.skills).toEqual(FAKE_SKILLS);+ expect(store.value.name).toBe('Radagast');+ });++ it('ignores undefined fields rather than writing them over existing values', async () => {+ await characterService.updateCharacterFields({ name: undefined, class: 'Ranger' });+ expect(store.value.name).toBe('Gandalf');+ expect(store.value.class).toBe('Ranger');+ });});describe('addXP decoupled from level', () => {diff --git a/server/services/characterSkills.js b/server/services/characterSkills.jsnew file mode 100644index 0000000000..df0f8d09bc--- /dev/null+++ b/server/services/characterSkills.js@@ -0,0 +1,182 @@+/**+ * Character Skill Registry (#2674, epic #2672)+ *+ * Derives per-domain "skills" — Wordsmith (Create), Mentalist (POST), Vitalist+ * (Health), Strategist (Goals), Archivist (Brain), Auteur (Media) — from the+ * stats each domain ALREADY exposes. There is deliberately **no new usage-event+ * bus**: every `compute()` composes an existing getter, so a domain the user has+ * never touched costs one cheap read and yields level 0.+ *+ * **Derived on read, never persisted.** `getCharacter()` attaches these to its+ * response; `saveCharacter()` strips them (they are in `character.js`'s+ * `DERIVED_FIELDS`), and the federation snapshot projects `character.json`+ * through `getWireCharacter()`, which reads the file directly and never sees+ * them. That is on purpose: usage differs per machine, so federating a+ * usage-derived value under LWW would let the peer you use *least* overwrite the+ * peer you use *most*.+ *+ * **Sentinel + validate.** A domain with no activity yields `level 0 / value 0`;+ * a domain whose stat read *fails* — or returns a non-finite value — yields+ * `{ level: null, value: null, unavailable: true }`. These two states must never+ * collapse: a fake 0 would read as "you have never written anything" when the+ * truth is "we could not tell".+ */++import { listUniverses } from './universeBuilder.js';+import { getCatalogStats } from './catalogDB.js';+import { getPostSessions } from './meatspacePost.js';+import { getAllTrainingEntries } from './meatspacePostTraining.js';+import { getLoggingStats } from './meatspaceLoggingStats.js';+import { getGoals } from './identity/goals.js';+import { countMemories } from './memoryBackend.js';+import { listAssets } from './mediaAssetIndex/db.js';++// Skills plateau rather than growing without bound — past this the curve is+// noise, and an unbounded level would dwarf the age-based character level.+export const MAX_SKILL_LEVEL = 20;++/**+ * Pure bucketed log curve: each *doubling* of `value` adds one level, so a skill+ * climbs quickly at first and then needs exponentially more use — the shape of an+ * RPG XP table, without a table to maintain.+ *+ * `scale` is the domain's "one unit of meaningful use" (a POST session is worth+ * more than a single health log), so every domain reaches level 1 at its own+ * natural cadence instead of forcing one global cadence onto all six.+ *+ * value 0 → 0 (empty domain → base level; never divides by zero)+ * value 1×scale → 1+ * value 3×scale → 2+ * value 7×scale → 3 … value (2^n − 1)×scale → n+ *+ * Non-finite/negative input floors to 0 rather than throwing — but note callers+ * must classify "unavailable" BEFORE reaching this curve (see `readSkill`), since+ * a 0 here means a genuinely empty domain.+ */+export function levelFromValue(value, scale) {+ if (!Number.isFinite(value) || value <= 0) return 0;+ const safeScale = Number.isFinite(scale) && scale > 0 ? scale : 1;+ return Math.min(MAX_SKILL_LEVEL, Math.floor(Math.log2(value / safeScale + 1)));+}++// Sentinel returned by a failed stat read. A unique Symbol (not null/0/-1) so it+// can never be mistaken for a real count a domain legitimately reported.+const STAT_UNAVAILABLE = Symbol('stat-unavailable');++/**+ * The registry. Each entry is `{ id, label, domain, scale, compute }`, where+ * `compute` resolves to a single non-negative number: the domain's cumulative+ * engagement.+ *+ * Values are **cumulative**, never streak-based: a streak resets to 0 after one+ * missed day, and a skill you have already earned should not un-learn itself+ * because you took a week off.+ */+export const SKILLS = [+ {+ id: 'wordsmith',+ label: 'Wordsmith',+ domain: 'create',+ // Worldbuilding is slow, high-effort work — a handful of records is already+ // real engagement, so the first level comes cheap.+ scale: 2,+ // Universes authored + catalog ingredients + captured scraps: the three+ // things Create/Writers Room actually produces.+ compute: async () => {+ const [universes, catalog] = await Promise.all([listUniverses(), getCatalogStats()]);+ return universes.length + catalog.total + catalog.scraps;+ },+ },+ {+ id: 'mentalist',+ label: 'Mentalist',+ domain: 'post',+ scale: 3,+ // Scored sessions + training-log entries (Morse / memory practice) — the same+ // "either counts as activity" union the unified POST streak uses, so this+ // can't disagree with what the Progress page calls practice.+ compute: async () => {+ const [sessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);+ return sessions.length + training.length;+ },+ },+ {+ id: 'vitalist',+ label: 'Vitalist',+ domain: 'health',+ // Health logs are near-daily and cheap to record, so the curve is stretched+ // to keep a single week of logging from vaulting to level 3.+ scale: 5,+ compute: async () => (await getLoggingStats()).totalLogged,+ },+ {+ id: 'strategist',+ label: 'Strategist',+ domain: 'goals',+ scale: 3,+ // Goal *discipline*, not goal count: check-ins plus recorded progress steps.+ // Filing ten goals and never revisiting them is not strategy.+ compute: async () => {+ const { goals } = await getGoals();+ return (goals || []).reduce(+ (sum, goal) => sum + (goal.checkIns?.length || 0) + (goal.progressHistory?.length || 0),+ 0+ );+ },+ },+ {+ id: 'archivist',+ label: 'Archivist',+ domain: 'brain',+ // Memories accrue fastest of any domain (a single Brain capture can mint+ // several), so this needs the flattest curve of the six.+ scale: 10,+ compute: async () => countMemories({}),+ },+ {+ id: 'auteur',+ label: 'Auteur',+ domain: 'media',+ scale: 5,+ // Rendered images + videos in the durable media asset index.+ compute: async () => (await listAssets()).length,+ },+];++/**+ * Resolve one skill to its response shape. The two failure-ish paths are kept+ * distinct on purpose (see the sentinel+validate note in the module header):+ * - `compute` rejects → unavailable (the domain could not be read)+ * - `compute` resolves non-finite → unavailable (the domain lied; a fake 0 here+ * would silently read as "no activity")+ * - `compute` resolves 0 → a real, earned level 0+ */+async function readSkill(skill) {+ const raw = await skill.compute().catch((err) => {+ console.warn(`⚠️ Character skill ${skill.id}: stat read failed — ${err.message}`);+ return STAT_UNAVAILABLE;+ });++ const base = { id: skill.id, label: skill.label, domain: skill.domain };++ if (raw === STAT_UNAVAILABLE || !Number.isFinite(raw) || raw < 0) {+ if (raw !== STAT_UNAVAILABLE) {+ console.warn(`⚠️ Character skill ${skill.id}: stat returned a non-countable value`);+ }+ // level/value stay null — NOT 0 — so no consumer can render an unread domain+ // as a legitimately empty one.+ return { ...base, level: null, value: null, unavailable: true };+ }++ return { ...base, level: levelFromValue(raw, skill.scale), value: raw, unavailable: false };+}++/**+ * Compute every skill. Domains are read in parallel and each failure is contained+ * to its own skill, so one unreachable domain (e.g. Postgres down for the catalog+ * or memory reads) degrades that entry to `unavailable` instead of failing the+ * whole `GET /api/character`.+ */+export async function getCharacterSkills() {+ return Promise.all(SKILLS.map(readSkill));+}diff --git a/server/services/characterSkills.test.js b/server/services/characterSkills.test.jsnew file mode 100644index 0000000000..c75f20a29f--- /dev/null+++ b/server/services/characterSkills.test.js@@ -0,0 +1,280 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// Each domain's stat getter is stubbed so the registry can be driven to its three+// interesting states — populated, empty, and read-failure — without any of the real+// dependency graphs (Postgres, the universe store, the meatspace files) loading.+const stats = vi.hoisted(() => ({+ universes: [],+ catalog: { total: 0, scraps: 0 },+ sessions: [],+ training: [],+ logging: { totalLogged: 0 },+ goals: { goals: [] },+ memories: 0,+ assets: [],+}));++// A domain "fails" by having its stub reject — the same way a real getter surfaces an+// unreachable Postgres or an unreadable data file.+const fail = (name) => () => Promise.reject(new Error(`${name} unavailable`));++vi.mock('./universeBuilder.js', () => ({ listUniverses: vi.fn(async () => stats.universes) }));+vi.mock('./catalogDB.js', () => ({ getCatalogStats: vi.fn(async () => stats.catalog) }));+vi.mock('./meatspacePost.js', () => ({ getPostSessions: vi.fn(async () => stats.sessions) }));+vi.mock('./meatspacePostTraining.js', () => ({ getAllTrainingEntries: vi.fn(async () => stats.training) }));+vi.mock('./meatspaceLoggingStats.js', () => ({ getLoggingStats: vi.fn(async () => stats.logging) }));+vi.mock('./identity/goals.js', () => ({ getGoals: vi.fn(async () => stats.goals) }));+vi.mock('./memoryBackend.js', () => ({ countMemories: vi.fn(async () => stats.memories) }));+vi.mock('./mediaAssetIndex/db.js', () => ({ listAssets: vi.fn(async () => stats.assets) }));++import { getCharacterSkills, levelFromValue, SKILLS, MAX_SKILL_LEVEL } from './characterSkills.js';+import { listUniverses } from './universeBuilder.js';+import { getCatalogStats } from './catalogDB.js';+import { getLoggingStats } from './meatspaceLoggingStats.js';+import { countMemories } from './memoryBackend.js';++const rows = (list) => Array.from({ length: list }, (_, i) => ({ id: `r${i}` }));++// Restore every stat to the "brand new install" baseline between tests so a test that+// populates one domain can't leak into the next one's empty-domain assertions.+beforeEach(() => {+ stats.universes = [];+ stats.catalog = { total: 0, scraps: 0 };+ stats.sessions = [];+ stats.training = [];+ stats.logging = { totalLogged: 0 };+ stats.goals = { goals: [] };+ stats.memories = 0;+ stats.assets = [];+ vi.mocked(listUniverses).mockImplementation(async () => stats.universes);+ vi.mocked(getCatalogStats).mockImplementation(async () => stats.catalog);+ vi.mocked(getLoggingStats).mockImplementation(async () => stats.logging);+ vi.mocked(countMemories).mockImplementation(async () => stats.memories);+ vi.spyOn(console, 'warn').mockImplementation(() => {});+});++afterEach(() => {+ vi.restoreAllMocks();+});++const byId = (skills, id) => skills.find((s) => s.id === id);++describe('levelFromValue (the compute curve)', () => {+ it('gives an empty domain level 0 rather than dividing by zero', () => {+ expect(levelFromValue(0, 5)).toBe(0);+ });++ it('adds one level per doubling of value: (2^n - 1) x scale -> n', () => {+ // scale=1 → the curve's raw shape: 1→1, 3→2, 7→3, 15→4, 31→5.+ expect(levelFromValue(1, 1)).toBe(1);+ expect(levelFromValue(3, 1)).toBe(2);+ expect(levelFromValue(7, 1)).toBe(3);+ expect(levelFromValue(15, 1)).toBe(4);+ expect(levelFromValue(31, 1)).toBe(5);+ });++ it('climbs monotonically — more use never lowers a level', () => {+ let prev = -1;+ for (let value = 0; value <= 500; value++) {+ const level = levelFromValue(value, 3);+ expect(level).toBeGreaterThanOrEqual(prev);+ prev = level;+ }+ });++ it('stretches the curve by scale, so each domain levels at its own cadence', () => {+ // The same raw count means less in a high-cadence domain (health logs, memories).+ expect(levelFromValue(10, 1)).toBeGreaterThan(levelFromValue(10, 10));+ // One full unit of `scale` is exactly level 1 in every domain.+ expect(levelFromValue(5, 5)).toBe(1);+ expect(levelFromValue(10, 10)).toBe(1);+ });++ it('is one level short of the next bucket at the boundary', () => {+ // Just under 3x scale is still level 1; 3x scale tips to 2.+ expect(levelFromValue(2.99 * 4, 4)).toBe(1);+ expect(levelFromValue(3 * 4, 4)).toBe(2);+ });++ it('plateaus at MAX_SKILL_LEVEL instead of growing without bound', () => {+ expect(levelFromValue(Number.MAX_SAFE_INTEGER, 1)).toBe(MAX_SKILL_LEVEL);+ });++ it('floors non-finite and negative input to 0', () => {+ for (const bad of [NaN, Infinity, -Infinity, undefined, null, -5]) {+ expect(levelFromValue(bad, 3)).toBe(0);+ }+ });++ it('falls back to scale 1 when a skill declares a nonsense scale', () => {+ for (const bad of [0, -1, NaN, undefined]) {+ expect(levelFromValue(1, bad)).toBe(1);+ }+ });+});++describe('the registry', () => {+ it('declares a unique id, label, domain, positive scale and compute for each skill', () => {+ const ids = new Set();+ for (const skill of SKILLS) {+ expect(skill.id).toMatch(/^[a-z]+$/);+ expect(ids.has(skill.id)).toBe(false);+ ids.add(skill.id);+ expect(skill.label).toBeTruthy();+ expect(skill.domain).toBeTruthy();+ expect(skill.scale).toBeGreaterThan(0);+ expect(typeof skill.compute).toBe('function');+ }+ });++ it('covers the four domains the acceptance criteria require, plus Brain and Media', () => {+ expect(SKILLS.map((s) => s.domain).sort()).toEqual(+ ['brain', 'create', 'goals', 'health', 'media', 'post']+ );+ });+});++describe('getCharacterSkills — empty domains', () => {+ it('yields a real, earned level 0 for every domain on a fresh install', async () => {+ const skills = await getCharacterSkills();++ expect(skills).toHaveLength(SKILLS.length);+ for (const skill of skills) {+ // The whole point of the sentinel: an untouched domain is 0/0 and NOT unavailable.+ expect(skill).toMatchObject({ level: 0, value: 0, unavailable: false });+ expect(skill.level).not.toBeNull();+ }+ });+});++describe('getCharacterSkills — populated domains', () => {+ it('derives Wordsmith from universes + catalog ingredients + scraps', async () => {+ stats.universes = rows(3);+ stats.catalog = { total: 8, scraps: 4 }; // 3 + 8 + 4 = 15, scale 2 → 15/2+1 = 8.5 → 3+ const wordsmith = byId(await getCharacterSkills(), 'wordsmith');+ expect(wordsmith.value).toBe(15);+ expect(wordsmith.level).toBe(3);+ expect(wordsmith.unavailable).toBe(false);+ });++ it('derives Mentalist from scored sessions AND training entries together', async () => {+ stats.sessions = rows(5);+ stats.training = rows(4);+ const mentalist = byId(await getCharacterSkills(), 'mentalist');+ expect(mentalist.value).toBe(9); // union, matching the unified POST streak's semantics+ expect(mentalist.level).toBe(levelFromValue(9, 3));+ });++ it('derives Vitalist from the cumulative health log total', async () => {+ stats.logging = { totalLogged: 35 };+ const vitalist = byId(await getCharacterSkills(), 'vitalist');+ expect(vitalist.value).toBe(35);+ expect(vitalist.level).toBe(3); // 35/5 + 1 = 8 → log2 = 3+ });++ it('derives Strategist from goal discipline (check-ins + progress), not goal count', async () => {+ stats.goals = {+ goals: [+ { checkIns: rows(4), progressHistory: rows(2) },+ { checkIns: rows(1), progressHistory: rows(0) },+ {}, // a goal filed and never revisited contributes nothing+ ],+ };+ const strategist = byId(await getCharacterSkills(), 'strategist');+ expect(strategist.value).toBe(7);+ expect(strategist.level).toBe(levelFromValue(7, 3));+ });++ it('derives Archivist from the memory count', async () => {+ stats.memories = 70;+ const archivist = byId(await getCharacterSkills(), 'archivist');+ expect(archivist.value).toBe(70);+ expect(archivist.level).toBe(3); // 70/10 + 1 = 8 → log2 = 3+ });++ it('derives Auteur from the media asset index', async () => {+ stats.assets = rows(20);+ const auteur = byId(await getCharacterSkills(), 'auteur');+ expect(auteur.value).toBe(20);+ expect(auteur.level).toBe(levelFromValue(20, 5));+ });++ it('leaves untouched domains at 0 while one domain climbs', async () => {+ stats.memories = 100;+ const skills = await getCharacterSkills();+ expect(byId(skills, 'archivist').level).toBeGreaterThan(0);+ for (const skill of skills.filter((s) => s.id !== 'archivist')) {+ expect(skill).toMatchObject({ level: 0, value: 0, unavailable: false });+ }+ });+});++describe('getCharacterSkills — stat-read failure (must NOT collapse into a fake 0)', () => {+ it('marks a skill unavailable with null level/value when its stat read rejects', async () => {+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));++ const archivist = byId(await getCharacterSkills(), 'archivist');+ expect(archivist.unavailable).toBe(true);+ // Null, not 0 — a 0 would read as "you have never saved a memory", which is a lie.+ expect(archivist.level).toBeNull();+ expect(archivist.value).toBeNull();+ expect(archivist.level).not.toBe(0);+ });++ it('contains a failure to its own skill — other domains still report', async () => {+ stats.logging = { totalLogged: 35 };+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));++ const skills = await getCharacterSkills();+ expect(byId(skills, 'archivist').unavailable).toBe(true);+ expect(byId(skills, 'vitalist')).toMatchObject({ level: 3, value: 35, unavailable: false });+ expect(skills).toHaveLength(SKILLS.length);+ });++ it('never rejects, even when every domain is unreadable', async () => {+ vi.mocked(listUniverses).mockImplementation(fail('universe store'));+ vi.mocked(getCatalogStats).mockImplementation(fail('catalog'));+ vi.mocked(getLoggingStats).mockImplementation(fail('logging stats'));+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));++ const skills = await getCharacterSkills();+ for (const id of ['wordsmith', 'vitalist', 'archivist']) {+ expect(byId(skills, id)).toMatchObject({ level: null, value: null, unavailable: true });+ }+ });++ it('marks a partially-failed multi-read skill unavailable rather than under-counting', async () => {+ // Wordsmith reads two stores. If only the catalog is down, reporting just the+ // universe count would silently understate the skill — "can't tell" is the honest answer.+ stats.universes = rows(3);+ vi.mocked(getCatalogStats).mockImplementation(fail('catalog'));++ expect(byId(await getCharacterSkills(), 'wordsmith')).toMatchObject({+ level: null, value: null, unavailable: true,+ });+ });++ it('treats a non-finite stat value as unavailable, not as 0', async () => {+ // A getter that resolves to undefined/NaN is a broken read, not an empty domain.+ for (const broken of [undefined, null, NaN, Infinity, 'twelve']) {+ vi.mocked(countMemories).mockImplementation(async () => broken);+ expect(byId(await getCharacterSkills(), 'archivist')).toMatchObject({+ level: null, value: null, unavailable: true,+ });+ }+ });++ it('treats a negative stat value as unavailable, not as level 0', async () => {+ vi.mocked(countMemories).mockImplementation(async () => -3);+ expect(byId(await getCharacterSkills(), 'archivist')).toMatchObject({+ level: null, value: null, unavailable: true,+ });+ });++ it('keeps id/label/domain on an unavailable skill so the UI can still name it', async () => {+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));+ expect(byId(await getCharacterSkills(), 'archivist')).toMatchObject({+ id: 'archivist', label: 'Archivist', domain: 'brain',+ });+ });+});