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

fix: stop federating stale derived character fields; cheapen the skill fan-out (#2674)

[._.]/ Adam Eivyab94abae2a5f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f7e62f94ca..4ec03625a3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,7 +2,7 @@
## 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.
+- [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, and a domain whose stats can't be read says "Unavailable" rather than pretending it's zero — currently for Wordsmith, Archivist, and Auteur, whose sources report failures; the three file-backed skills can't yet tell an unreadable file from an empty one, which is tracked separately. 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.
diff --git a/server/services/askService.js b/server/services/askService.js
index a2ef2b3f4d..22e7738b81 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -360,7 +360,8 @@ const MODE_DIRECTIVES = {
};
export async function buildPersonaPreamble() {
- const character = await getCharacter().catch(() => null);
+ // Only name/class are read below, so skip the skill fan-out — this runs per /ask question.
+ const character = await getCharacter({ withSkills: false }).catch(() => null);
// The character sheet is the closest thing to a persona surface today.
// Autobiography stories carry the voice; we sample the most recent one
// separately in the source pipeline. Keep this preamble small.
diff --git a/server/services/character.js b/server/services/character.js
index b2ec21dba9..ef1d6b14ac 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -128,17 +128,26 @@ async function loadRawCharacter() {
// 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) {
+// `withSkills: false` skips the skill fan-out (six domain stat reads) for callers that only
+// want the persisted fields plus the age level — deriving skills nobody reads is pure waste.
+// Skipping OMITS the key rather than setting it to [] or null: an absent `skills` means "not
+// computed", which must not be confused with "computed, and every domain is empty".
+async function enrichCharacter(raw, { withSkills = true } = {}) {
const [{ birthDate }, skills] = await Promise.all([
getBirthDate().catch(() => ({ birthDate: null })),
- getCharacterSkills(),
+ withSkills ? getCharacterSkills() : Promise.resolve(undefined),
]);
const ageYears = ageYearsFromBirthDate(birthDate);
- return { ...raw, ageYears, level: levelFromAge(ageYears), skills };
+ const enriched = { ...raw, ageYears, level: levelFromAge(ageYears) };
+ // Drop any stale persisted key when skills weren't computed, so a hand-edited
+ // character.json can't pass its own `skills` off as freshly derived.
+ if (withSkills) enriched.skills = skills;
+ else delete enriched.skills;
+ return enriched;
}
-export async function getCharacter() {
- return enrichCharacter(await loadRawCharacter());
+export async function getCharacter(options = {}) {
+ return enrichCharacter(await loadRawCharacter(), options);
}
// Apply a partial patch of human-authored fields (name/class/avatarPath). Reads the RAW
@@ -164,7 +173,15 @@ export async function updateCharacterFields(patch = {}) {
export async function getWireCharacter() {
const raw = await readJSONFile(CHARACTER_FILE, null);
if (!raw) return null;
- return { ...raw, level: legacyLevelFromXp(raw.xp) };
+ // Strip every derived field a hand-edited or legacy character.json might be carrying before
+ // it goes out on the wire: `level` is then re-added below as the legacy xp-derived value,
+ // but `skills`/`ageYears` must never federate at all (skills are per-machine — see
+ // characterSkills.js — and ageYears is a pure function of the peer's own birthDate). Without
+ // this, applyCharacterRemote's no-local branch writes the payload verbatim and a stale key
+ // would self-propagate across peers.
+ const wire = { ...raw };
+ for (const field of DERIVED_FIELDS) delete wire[field];
+ return { ...wire, level: legacyLevelFromXp(raw.xp) };
}
export async function saveCharacter(data) {
diff --git a/server/services/character.test.js b/server/services/character.test.js
index 11880914f7..6f5d5a3cf4 100644
--- a/server/services/character.test.js
+++ b/server/services/character.test.js
@@ -149,11 +149,27 @@ describe('getWireCharacter federation projection', () => {
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.
+ // the least-used peer clobber the most-used one under LWW.
const wire = await characterService.getWireCharacter();
expect(wire.skills).toBeUndefined();
});
+
+ it('strips a STALE derived field already sitting in character.json', async () => {
+ // The load-bearing case: saveCharacter never writes these, but a hand-edited file (or one
+ // from a peer that did) can carry them. applyCharacterRemote's no-local branch writes the
+ // wire payload verbatim, so anything that survives here self-propagates across peers.
+ store.value = {
+ ...store.value,
+ skills: [{ id: 'stale', level: 99 }],
+ ageYears: 999,
+ level: 99,
+ };
+
+ const wire = await characterService.getWireCharacter();
+ expect(wire.skills).toBeUndefined();
+ expect(wire.ageYears).toBeUndefined();
+ expect(wire.level).toBe(4); // re-derived from xp, NOT the stale 99
+ });
});
describe('getCharacter skills (derived on read, #2674)', () => {
@@ -191,6 +207,26 @@ describe('getCharacter skills (derived on read, #2674)', () => {
const character = await characterService.getCharacter();
expect(character.skills).toEqual(FAKE_SKILLS);
});
+
+ it('skips the skill fan-out entirely when withSkills is false', async () => {
+ const { getCharacterSkills } = await import('./characterSkills.js');
+ vi.mocked(getCharacterSkills).mockClear();
+
+ const character = await characterService.getCharacter({ withSkills: false });
+
+ expect(getCharacterSkills).not.toHaveBeenCalled();
+ // Absent, NOT [] — "not computed" must not read as "computed, every domain empty".
+ expect('skills' in character).toBe(false);
+ expect(character.level).toBeDefined(); // the cheap age level still resolves
+ });
+
+ it('drops a stale persisted skills key even when withSkills is false', async () => {
+ // Otherwise skipping the fan-out would hand the caller a hand-edited file's own `skills`
+ // array dressed up as derived output.
+ store.value = { ...store.value, skills: [{ id: 'stale', level: 99 }] };
+ const character = await characterService.getCharacter({ withSkills: false });
+ expect('skills' in character).toBe(false);
+ });
});
describe('updateCharacterFields', () => {
diff --git a/server/services/characterSkills.js b/server/services/characterSkills.js
index df0f8d09bc..ad25ffead4 100644
--- a/server/services/characterSkills.js
+++ b/server/services/characterSkills.js
@@ -9,9 +9,8 @@
*
* **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
+ * `DERIVED_FIELDS`), and `getWireCharacter()` strips them from the federation
+ * snapshot. 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*.
*
@@ -20,6 +19,23 @@
* `{ 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".
+ *
+ * **Known gap in that guarantee (#2726).** `readSkill` honours whatever a domain
+ * reports, but it can only *detect* a failure the getter actually surfaces — by
+ * rejecting, or by resolving something non-countable. Today only the DB-backed
+ * getters do that:
+ *
+ * - reports failure → `wordsmith`, `archivist`, `auteur` (a failed `query()` throws)
+ * - SWALLOWS failure → `mentalist`, `vitalist`, `strategist`
+ *
+ * The swallowing three bottom out in `readJSONFile`, which returns its default on
+ * *every* read error and not just ENOENT — so a corrupt or unreadable
+ * `post-sessions.json` is indistinguishable here from "no sessions yet" and reports a
+ * real-looking level 0. Closing it needs strict-read variants threaded through the
+ * shared file getters (the `readVideoHistoryStrict` `{ ok, list }` precedent in
+ * `mediaAssetIndex/db.js`), which is a wider change than this registry — tracked in
+ * #2726. Nothing here needs to change when it lands: the moment a getter starts
+ * reporting failure, `readSkill` already classifies it correctly.
*/
import { listUniverses } from './universeBuilder.js';
@@ -29,7 +45,7 @@ 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';
+import { countAssets } 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.
@@ -139,7 +155,7 @@ export const SKILLS = [
domain: 'media',
scale: 5,
// Rendered images + videos in the durable media asset index.
- compute: async () => (await listAssets()).length,
+ compute: async () => countAssets(),
},
];
diff --git a/server/services/characterSkills.test.js b/server/services/characterSkills.test.js
index c75f20a29f..efa69b4f90 100644
--- a/server/services/characterSkills.test.js
+++ b/server/services/characterSkills.test.js
@@ -11,7 +11,7 @@ const stats = vi.hoisted(() => ({
logging: { totalLogged: 0 },
goals: { goals: [] },
memories: 0,
- assets: [],
+ assets: 0,
}));
// A domain "fails" by having its stub reject — the same way a real getter surfaces an
@@ -25,13 +25,14 @@ vi.mock('./meatspacePostTraining.js', () => ({ getAllTrainingEntries: vi.fn(asyn
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) }));
+vi.mock('./mediaAssetIndex/db.js', () => ({ countAssets: 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';
+import { countAssets } from './mediaAssetIndex/db.js';
const rows = (list) => Array.from({ length: list }, (_, i) => ({ id: `r${i}` }));
@@ -45,11 +46,12 @@ beforeEach(() => {
stats.logging = { totalLogged: 0 };
stats.goals = { goals: [] };
stats.memories = 0;
- stats.assets = [];
+ stats.assets = 0;
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.mocked(countAssets).mockImplementation(async () => stats.assets);
vi.spyOn(console, 'warn').mockImplementation(() => {});
});
@@ -193,12 +195,21 @@ describe('getCharacterSkills — populated domains', () => {
});
it('derives Auteur from the media asset index', async () => {
- stats.assets = rows(20);
+ stats.assets = 20;
const auteur = byId(await getCharacterSkills(), 'auteur');
expect(auteur.value).toBe(20);
expect(auteur.level).toBe(levelFromValue(20, 5));
});
+ it('counts media assets without materializing every row', async () => {
+ // countAssets() is a COUNT(*); listAssets() selects and JSON-parses the full payload of
+ // every rendered image and video. GET /api/character is polled every 15s by the CyberCity
+ // HUD, so this must never regress back to `(await listAssets()).length`.
+ vi.mocked(countAssets).mockClear();
+ await getCharacterSkills();
+ expect(countAssets).toHaveBeenCalledTimes(1);
+ });
+
it('leaves untouched domains at 0 while one domain climbs', async () => {
stats.memories = 100;
const skills = await getCharacterSkills();
@@ -209,6 +220,13 @@ describe('getCharacterSkills — populated domains', () => {
});
});
+// NOTE ON WHAT THIS SUITE PROVES: these tests drive failure by making a stubbed getter
+// reject, which exercises readSkill's classification — the registry's own job. It does NOT
+// prove the real wiring can reach `unavailable`: `mentalist`, `vitalist`, and `strategist`
+// bottom out in readJSONFile, which swallows read errors and returns an empty default, so
+// those three can't currently reject at all. That gap is real, documented in the module
+// header, and tracked in #2726 (which owns the strict-read variants and the end-to-end
+// coverage). Do not read a green run here as "every domain reports failures correctly".
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'));
diff --git a/server/services/citysnapshots.js b/server/services/citysnapshots.js
index 8516000afd..470378fa8c 100644
--- a/server/services/citysnapshots.js
+++ b/server/services/citysnapshots.js
@@ -159,7 +159,9 @@ async function buildSnapshot() {
getPeers().catch(() => FAILED),
backup.getState().catch(() => FAILED),
getCountsByType().catch(() => FAILED),
- getCharacter().catch(() => FAILED),
+ // Only `character.level` is snapshotted (see the frame below), so skip the skill
+ // fan-out — this runs on every snapshot tick.
+ getCharacter({ withSkills: false }).catch(() => FAILED),
getMemoryStats().catch(() => FAILED),
getDiskPercent().catch(() => null),
]);
diff --git a/server/services/mediaAssetIndex/db.js b/server/services/mediaAssetIndex/db.js
index 44fb3b180a..e23bb68094 100644
--- a/server/services/mediaAssetIndex/db.js
+++ b/server/services/mediaAssetIndex/db.js
@@ -86,6 +86,21 @@ export async function listAssets({ kind } = {}) {
return result.rows.map(rowToAsset);
}
+/**
+ * Count index rows. Optional `kind` filter ('image' | 'video').
+ *
+ * Use this over `listAssets().length` when only the tally is wanted: listAssets selects and
+ * JSON-parses the full payload of every rendered image and video, which is a lot of work to
+ * throw away for one number (the character skill registry reads this on every
+ * `GET /api/character`).
+ */
+export async function countAssets({ kind } = {}) {
+ const result = kind
+ ? await query(`SELECT COUNT(*) AS count FROM media_assets WHERE kind = $1`, [kind])
+ : await query(`SELECT COUNT(*) AS count FROM media_assets`);
+ return parseInt(result.rows[0].count, 10);
+}
+
// Strict video-history reader for reconcile. The live store's loadHistory()
// (readJSONFile w/ [] default) intentionally collapses a MISSING file AND a
// corrupt/unreadable one to [] — fine for the live store, but catastrophic for