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

perf: count universes and works without materializing every record (#2729)

[._.]/ Adam Eivy3b40137fa278
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b63ae0348d..e6c47772d1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -45,6 +45,7 @@
## Character Sheet
- `[issue-2673]` **Your Character level is now your age.** The Character's level is reframed as life experience — `level = floor(age in years)`, derived on read from your canonical birth date instead of being ground out of XP thresholds (JIRA tickets + CoS tasks). XP survives as a cumulative stat but no longer drives level, and the CyberCity HUD badge now shows the age-based level with a progress bar toward your next birthday (a friendly "set birth date" prompt when no birth date is set yet). Existing character records keep loading unchanged, and the derived level is excluded from cross-machine sync so peers never fight over a stale value.
+- `[issue-2729]` The Character page loads faster the more you've written. Your Wordsmith skill used to be scored by loading every universe you own (plus their entire render history) and rebuilding every Writers Room work with all its drafts, just to count them — so the page got slower with each world and story you added. It now counts them directly in the database, leaving the score itself unchanged.
## Creative Commissions
diff --git a/server/services/characterSkills.js b/server/services/characterSkills.js
index 55c61ffd97..8df058082c 100644
--- a/server/services/characterSkills.js
+++ b/server/services/characterSkills.js
@@ -38,8 +38,8 @@
* reporting failure, `readSkill` already classifies it correctly.
*/
-import { listUniverses } from './universeBuilder.js';
-import { listWorks } from './writersRoom/local.js';
+import { countUniverses } from './universeBuilder.js';
+import { countWorks } from './writersRoom/local.js';
import { getCatalogStats } from './catalogDB.js';
import { getPostSessions } from './meatspacePost.js';
import { getAllTrainingEntries } from './meatspacePostTraining.js';
@@ -102,16 +102,17 @@ export const SKILLS = [
// omitting it would leave a writing-only user stuck at level 0 in the very skill named
// for their work.
//
- // listUniverses()/listWorks() materialize every record (and the universe-run history) for
- // a `.length` — cheap count helpers are tracked in #2729. Bounded for now: the CyberCity
- // poll passes `?skills=0`, so this only runs on an explicit /character read.
+ // All four reads are tallies, never listings (#2729): countUniverses/countWorks are
+ // COUNT(*)s that exclude tombstones exactly as listUniverses()/listWorks() filter them,
+ // so this no longer materializes every universe record, the universe-run history, or
+ // every work's rebuilt manifest just to read a `.length`.
compute: async () => {
- const [universes, works, catalog] = await Promise.all([
- listUniverses(),
- listWorks(),
+ const [universeCount, workCount, catalog] = await Promise.all([
+ countUniverses(),
+ countWorks(),
getCatalogStats(),
]);
- return universes.length + works.length + catalog.total + catalog.scraps;
+ return universeCount + workCount + catalog.total + catalog.scraps;
},
},
{
diff --git a/server/services/characterSkills.test.js b/server/services/characterSkills.test.js
index a837067fa8..bc5ff576bc 100644
--- a/server/services/characterSkills.test.js
+++ b/server/services/characterSkills.test.js
@@ -4,8 +4,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// 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: [],
- works: [],
+ universes: 0,
+ works: 0,
catalog: { total: 0, scraps: 0 },
sessions: [],
training: [],
@@ -19,8 +19,8 @@ const stats = vi.hoisted(() => ({
// 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('./writersRoom/local.js', () => ({ listWorks: vi.fn(async () => stats.works) }));
+vi.mock('./universeBuilder.js', () => ({ countUniverses: vi.fn(async () => stats.universes) }));
+vi.mock('./writersRoom/local.js', () => ({ countWorks: vi.fn(async () => stats.works) }));
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) }));
@@ -30,20 +30,20 @@ vi.mock('./memoryBackend.js', () => ({ countMemories: vi.fn(async () => stats.me
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 { countUniverses } from './universeBuilder.js';
import { getCatalogStats } from './catalogDB.js';
import { getLoggingStats } from './meatspaceLoggingStats.js';
import { countMemories } from './memoryBackend.js';
import { countAssets } from './mediaAssetIndex/db.js';
-import { listWorks } from './writersRoom/local.js';
+import { countWorks } from './writersRoom/local.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.works = [];
+ stats.universes = 0;
+ stats.works = 0;
stats.catalog = { total: 0, scraps: 0 };
stats.sessions = [];
stats.training = [];
@@ -51,8 +51,8 @@ beforeEach(() => {
stats.goals = { goals: [] };
stats.memories = 0;
stats.assets = 0;
- vi.mocked(listUniverses).mockImplementation(async () => stats.universes);
- vi.mocked(listWorks).mockImplementation(async () => stats.works);
+ vi.mocked(countUniverses).mockImplementation(async () => stats.universes);
+ vi.mocked(countWorks).mockImplementation(async () => stats.works);
vi.mocked(getCatalogStats).mockImplementation(async () => stats.catalog);
vi.mocked(getLoggingStats).mockImplementation(async () => stats.logging);
vi.mocked(countMemories).mockImplementation(async () => stats.memories);
@@ -156,8 +156,8 @@ describe('getCharacterSkills — empty domains', () => {
describe('getCharacterSkills — populated domains', () => {
it('derives Wordsmith from universes + Writers Room works + catalog ingredients + scraps', async () => {
- stats.universes = rows(3);
- stats.works = rows(2);
+ stats.universes = 3;
+ stats.works = 2;
stats.catalog = { total: 8, scraps: 2 }; // 3 + 2 + 8 + 2 = 15, scale 2 → 15/2+1 = 8.5 → 3
const wordsmith = byId(await getCharacterSkills(), 'wordsmith');
expect(wordsmith.value).toBe(15);
@@ -168,7 +168,7 @@ describe('getCharacterSkills — populated domains', () => {
it('levels Wordsmith for a Writers-Room-only user with no universes or catalog', async () => {
// The skill is named for Create AND Writers Room; a writing-only user was stuck at 0
// while their work went uncounted.
- stats.works = rows(7);
+ stats.works = 7;
const wordsmith = byId(await getCharacterSkills(), 'wordsmith');
expect(wordsmith.value).toBe(7);
expect(wordsmith.level).toBe(levelFromValue(7, 2));
@@ -266,7 +266,7 @@ describe('getCharacterSkills — stat-read failure (must NOT collapse into a fak
});
it('never rejects, even when every domain is unreadable', async () => {
- vi.mocked(listUniverses).mockImplementation(fail('universe store'));
+ vi.mocked(countUniverses).mockImplementation(fail('universe store'));
vi.mocked(getCatalogStats).mockImplementation(fail('catalog'));
vi.mocked(getLoggingStats).mockImplementation(fail('logging stats'));
vi.mocked(countMemories).mockImplementation(fail('memory backend'));
@@ -280,7 +280,7 @@ describe('getCharacterSkills — stat-read failure (must NOT collapse into a fak
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);
+ stats.universes = 3;
vi.mocked(getCatalogStats).mockImplementation(fail('catalog'));
expect(byId(await getCharacterSkills(), 'wordsmith')).toMatchObject({
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 2bfe2caed7..678088700d 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -715,6 +715,32 @@ describe("universeBuilder service", () => {
expect(all[0].updatedAt).toBe(all[0].deletedAt);
});
+ it("countUniverses excludes tombstones and agrees with listUniverses().length", async () => {
+ // countUniverses is the cheap tally the character skill registry reads instead
+ // of materializing every record + the run history (#2729). Pin it against
+ // listUniverses so the two can never disagree — the specific bug a naive
+ // listIds().length would introduce is counting tombstones, since listIds()
+ // returns live + ephemeral + tombstones and leaves filtering to the service.
+ expect(await svc.countUniverses()).toBe(0);
+
+ const live = await seedWorld();
+ const doomed = await seedWorld({ name: "Doomed World" });
+ expect(await svc.countUniverses()).toBe(2);
+ expect(await svc.countUniverses()).toBe((await svc.listUniverses()).length);
+
+ await svc.deleteUniverse(doomed.id);
+ // The tombstone is still ON DISK (soft delete) — listIds() would still see it.
+ expect(await svc.listUniverses({ includeDeleted: true })).toHaveLength(2);
+ // ...but it must NOT be counted.
+ expect(await svc.countUniverses()).toBe(1);
+ expect(await svc.countUniverses()).toBe((await svc.listUniverses()).length);
+ expect((await svc.listUniverses()).map((u) => u.id)).toEqual([live.id]);
+
+ // includeDeleted mirrors listUniverses's own option, tombstones and all.
+ expect(await svc.countUniverses({ includeDeleted: true }))
+ .toBe((await svc.listUniverses({ includeDeleted: true })).length);
+ });
+
it("getUniverse returns 404 for tombstoned, includeDeleted exposes it", async () => {
const w = await seedWorld();
await svc.deleteUniverse(w.id);
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index 0032a75fb1..ae0773d477 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -77,6 +77,21 @@ export async function listUniverses({ includeDeleted = false } = {}) {
return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
+/**
+ * How many universes listUniverses() would return — without materializing any
+ * of them (#2729). A `COUNT(*)` on PG; a raw-record scan on the file backend.
+ *
+ * Use this for a tally (the Wordsmith skill's engagement score). It skips the
+ * run-history load, the per-record sanitize, and the sort that listUniverses()
+ * pays for, so `(await listUniverses()).length` should never appear again.
+ * Tombstones are excluded by default, exactly as listUniverses filters them —
+ * pinned by tests asserting the two agree on both backends.
+ */
+export async function countUniverses({ includeDeleted = false } = {}) {
+ await ensureDir(PATHS.data);
+ return store().countUniverses({ includeDeleted });
+}
+
export async function getUniverse(id, { includeDeleted = false } = {}) {
// Direct per-record load — no full collection scan needed for a by-id read.
// The store's sanitizer (sanitizeTemplate) runs on the loaded record, so the
diff --git a/server/services/universeBuilder/db.js b/server/services/universeBuilder/db.js
index a919f1d801..6758dc7608 100644
--- a/server/services/universeBuilder/db.js
+++ b/server/services/universeBuilder/db.js
@@ -50,6 +50,41 @@ export async function listRaw() {
return rows.map((r) => r.data);
}
+/**
+ * Cheap live-universe tally (#2729) — the count listUniverses().length used to
+ * pay for by materializing every JSONB record AND the whole run history.
+ *
+ * Reads the `deleted` MIRROR COLUMN, not the JSONB flag listUniverses filters
+ * on. Those cannot disagree: every write path derives both from the same
+ * `record` in the same statement with the same predicate — `writeRaw` above and
+ * the one-time file import (`scripts/migrateUniversesToDB.js`) each bind
+ * `record.deleted === true` into the column, and the sanitizer the service
+ * filters on (`sanitizeSoftDeleteFields`, lib/syncWire.js) computes
+ * `raw?.deleted === true` off the same field. There is no third writer, and no
+ * UPDATE that touches `deleted` without rewriting `data`. So the column is an
+ * exact mirror, and `WHERE deleted = FALSE` also hits the `idx_universes_live`
+ * partial index that exists for precisely this "live set" scan.
+ *
+ * Deliberately does NOT filter `ephemeral` — listUniverses() counts ephemeral
+ * universes too (it filters ONLY on `deleted`), so filtering here would
+ * undercount.
+ *
+ * Known boundary: a row whose `data` can't survive `sanitizeTemplate` (blank
+ * `name`, non-string `id`) is dropped by listUniverses's `.filter(Boolean)` but
+ * still counted here. Unreachable through the service — create/update/sync all
+ * sanitize before writing — and only a corrupt legacy record imported verbatim
+ * could hit it. Replicating the sanitizer's drop rules in SQL would couple this
+ * count to sanitizeTemplate's internals and silently drift when they change;
+ * a ±1 on an already-corrupt record is not worth that. The file backend's
+ * counterpart (store.js) has the same semantics, so the two agree.
+ */
+export async function countUniverses({ includeDeleted = false } = {}) {
+ const { rows } = includeDeleted
+ ? await query(`SELECT COUNT(*) AS count FROM universes`)
+ : await query(`SELECT COUNT(*) AS count FROM universes WHERE deleted = FALSE`);
+ return parseInt(rows[0].count, 10);
+}
+
/**
* Upsert one record. `data` is written verbatim (lossless); the typed mirror
* columns are bind-sanitized so a hand-edited/legacy record with a malformed
diff --git a/server/services/universeBuilder/db.test.js b/server/services/universeBuilder/db.test.js
index c596930de3..04cdb5a6e5 100644
--- a/server/services/universeBuilder/db.test.js
+++ b/server/services/universeBuilder/db.test.js
@@ -104,6 +104,35 @@ describe.skipIf(!dbReady)('universeBuilder DB adapter round-trip', () => {
expect(all.find((r) => r.id === 'u-1').logline).toBe('x');
});
+ it('countUniverses counts the live set without materializing it', async () => {
+ // The cheap tally the character skill registry reads (#2729). It counts the
+ // `deleted` MIRROR COLUMN, while the service filters listUniverses() on the
+ // JSONB flag — so this pins that the two can't drift: writeRaw derives both
+ // from the same record.deleted in one statement.
+ expect(await db.countUniverses()).toBe(0);
+
+ await db.writeRaw('live', U('live'));
+ await db.writeRaw('dead', U('dead', { deleted: true, deletedAt: '2026-02-02T00:00:00.000Z' }));
+ await db.writeRaw('ghost', U('ghost', { ephemeral: true }));
+
+ // listIds() sees all three; the tombstone must NOT be counted (the exact bug a
+ // naive listIds().length would introduce). Ephemeral universes DO count —
+ // listUniverses filters only on `deleted`, so filtering them here would undercount.
+ expect((await db.listIds())).toHaveLength(3);
+ expect(await db.countUniverses()).toBe(2);
+ // Agrees with the same filter the service applies to the JSONB flag on read.
+ expect(await db.countUniverses())
+ .toBe((await db.listRaw()).filter((r) => r?.deleted !== true).length);
+
+ expect(await db.countUniverses({ includeDeleted: true })).toBe(3);
+ expect(await db.countUniverses({ includeDeleted: true })).toBe((await db.listRaw()).length);
+
+ // Un-deleting through the normal write path rewrites both the column and the
+ // JSONB flag, so the count follows.
+ await db.writeRaw('dead', U('dead'));
+ expect(await db.countUniverses()).toBe(3);
+ });
+
it('tolerates a malformed timestamp without throwing (falls back)', async () => {
await db.writeRaw('u-bad', U('u-bad', { updatedAt: 'not-a-date', createdAt: 'nope' }));
const back = await db.readRaw('u-bad');
diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.js
index e2ea3a15e1..dc816c7b4c 100644
--- a/server/services/universeBuilder/store.js
+++ b/server/services/universeBuilder/store.js
@@ -81,14 +81,25 @@ function makeFileBackend(dir) {
idPattern: /^[A-Za-z0-9_-]{1,128}$/,
});
const runsOf = (ti) => (Array.isArray(ti.config?.runs) ? ti.config.runs : []);
+ const listRaw = async () => {
+ const ids = await cs.listIds();
+ const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));
+ return records.filter((r) => r != null);
+ };
return {
name: 'file',
readRaw: (id) => cs.loadOneRaw(id),
listIds: () => cs.listIds(),
- listRaw: async () => {
- const ids = await cs.listIds();
- const records = await Promise.all(ids.map((id) => cs.loadOneRaw(id)));
- return records.filter((r) => r != null);
+ listRaw,
+ // There is no cheap count on the file layout — `deleted` lives INSIDE each
+ // record, so knowing which ids are live means reading them all (listIds()
+ // alone can't tell). This still skips what made listUniverses() expensive:
+ // the run-history load and the per-record sanitize+sort. Matches the PG
+ // backend's semantics — `deleted !== true` is exactly the predicate
+ // sanitizeSoftDeleteFields applies before listUniverses filters on it.
+ countUniverses: async ({ includeDeleted = false } = {}) => {
+ const records = await listRaw();
+ return includeDeleted ? records.length : records.filter((r) => r?.deleted !== true).length;
},
writeRaw: (id, record) => cs.saveOneNow(id, record),
deleteRaw: (id) => cs.deleteOneNow(id),
@@ -127,6 +138,7 @@ function makePgBackend(db) {
readRaw: db.readRaw,
listIds: db.listIds,
listRaw: db.listRaw,
+ countUniverses: db.countUniverses,
writeRaw: db.writeRaw,
deleteRaw: db.deleteRaw,
loadRuns: db.loadRuns,
@@ -183,6 +195,7 @@ function createFacade({ dir, sanitizeRecord }) {
// Reads
listIds: async () => (await getBackend()).listIds(),
listRaw: async () => (await getBackend()).listRaw(),
+ countUniverses: async (opts) => (await getBackend()).countUniverses(opts),
loadOneRaw: async (id) => (await getBackend()).readRaw(id),
loadOne: async (id) => {
const raw = await (await getBackend()).readRaw(id);
diff --git a/server/services/universeBuilder/storeFacade.js b/server/services/universeBuilder/storeFacade.js
index 759fe82a3a..5e3e0d9125 100644
--- a/server/services/universeBuilder/storeFacade.js
+++ b/server/services/universeBuilder/storeFacade.js
@@ -7,9 +7,9 @@
* is SYNCHRONOUS — it owns the per-id write queue + the mutation epoch + applies
* `sanitizeTemplate` on read — and defers backend selection into each method, so
* this service keeps calling `store()` exactly as it did the collectionStore.
- * Methods used here: loadOne / loadOneRaw / listIds / queueRecordWrite /
- * writeRecord(id, rec) / deleteRecord(id) / loadRuns / appendRun /
- * removeRunsForUniverses. `writeRecord`/`deleteRecord` replace the inline
+ * Methods used here: loadOne / loadOneRaw / listIds / listRaw / countUniverses /
+ * queueRecordWrite / writeRecord(id, rec) / deleteRecord(id) / loadRuns /
+ * appendRun / removeRunsForUniverses. `writeRecord`/`deleteRecord` replace the inline
* ensureDir+atomicWrite(recordPath) / rm(recordDir) the file layout used, and
* bump the mutation epoch so dataSync re-sends the universe snapshot to peers
* (the storage swap stays invisible to federation — see the schema-design doc).
diff --git a/server/services/writersRoom/db.js b/server/services/writersRoom/db.js
index 5fbbaf5f4d..f4a31225ae 100644
--- a/server/services/writersRoom/db.js
+++ b/server/services/writersRoom/db.js
@@ -329,6 +329,22 @@ export async function listWorks() {
return works.rows.map((w) => rowsToManifest(w, draftsByWork.get(w.id) || []));
}
+/**
+ * Cheap live-work tally (#2729) — the count listWorks().length used to pay for
+ * by running the drafts query and rebuilding every work's full manifest.
+ *
+ * `deleted` here is a real column (not a JSONB mirror), and it is the SAME
+ * predicate listWorks() above filters on — so the two agree by construction.
+ * Unlike universeBuilder, no sanitizer sits between the row and the caller on
+ * this path, so there is no drop-on-read case to reconcile.
+ */
+export async function countWorks() {
+ const { rows } = await query(
+ `SELECT COUNT(*) AS count FROM writers_room_works WHERE deleted = FALSE`,
+ );
+ return parseInt(rows[0].count, 10);
+}
+
// Bind tuple for one draft-version row from a manifest draft entry.
function draftBinds(workId, draft) {
return [
diff --git a/server/services/writersRoom/db.test.js b/server/services/writersRoom/db.test.js
index 6c2c92cd70..e7f6dc878d 100644
--- a/server/services/writersRoom/db.test.js
+++ b/server/services/writersRoom/db.test.js
@@ -160,6 +160,24 @@ describe.skipIf(!dbReady)('Writers Room DB adapter round-trip', () => {
expect(await db.listWorkIds({ includeDeleted: true })).toEqual(expect.arrayContaining(['wr-work-1', 'wr-work-2']));
});
+ it('countWorks counts the live set without rebuilding any manifest', async () => {
+ // The cheap tally the character skill registry reads (#2729) instead of
+ // listWorks().length — which runs the drafts query and reassembles every
+ // manifest. Pin the two together so they can never disagree.
+ expect(await db.countWorks()).toBe(0);
+
+ await db.writeWork(manifest('wr-work-1'));
+ await db.writeWork(manifest('wr-work-2'));
+ expect(await db.countWorks()).toBe(2);
+ expect(await db.countWorks()).toBe((await db.listWorks()).length);
+
+ // A tombstoned work is retained for federation but must NOT be counted.
+ await db.deleteWork('wr-work-2');
+ expect(await db.listWorkIds({ includeDeleted: true })).toHaveLength(2);
+ expect(await db.countWorks()).toBe(1);
+ expect(await db.countWorks()).toBe((await db.listWorks()).length);
+ });
+
it('mergeWorksFromSync inserts a remote work and LWW-resolves a later edit', async () => {
const insert = await db.mergeWorksFromSync([manifest('wr-work-1', { title: 'Remote', updatedAt: '2026-02-01T00:00:00.000Z' })]);
expect(insert).toEqual({ applied: true, count: 1 });
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 329e1ffb76..80f3b3bae4 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -242,6 +242,19 @@ export async function listWorks() {
.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
}
+/**
+ * How many works listWorks() would return — without rebuilding a single
+ * manifest (#2729). A `COUNT(*)` on PG; the shared live-set read on the file
+ * backend. Tombstones are excluded on both, exactly as listWorks filters them.
+ *
+ * Use this for a tally (the Wordsmith skill's engagement score) so
+ * `(await listWorks()).length` — two queries plus every work's drafts[] — never
+ * has to run just to produce a number.
+ */
+export async function countWorks() {
+ return store().countWorks();
+}
+
export async function getWork(id) {
const manifest = await loadManifest(id);
if (!manifest) throw notFound('Work');
diff --git a/server/services/writersRoom/local.test.js b/server/services/writersRoom/local.test.js
index 357ccecae5..f9e4a93af1 100644
--- a/server/services/writersRoom/local.test.js
+++ b/server/services/writersRoom/local.test.js
@@ -15,7 +15,7 @@ const local = await import('./local.js');
const {
countWords, contentHash, buildSegmentIndex,
listFolders, createFolder, deleteFolder,
- listWorks, createWork, getWork, getWorkWithBody, updateWork, deleteWork,
+ listWorks, countWorks, createWork, getWork, getWorkWithBody, updateWork, deleteWork,
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
listExercises, createExercise, finishExercise, discardExercise,
resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, DEFAULT_LIVE_MODE,
@@ -201,6 +201,24 @@ describe('work CRUD', () => {
await expect(getWork(work.id)).rejects.toThrow(/not found/i);
expect(await listWorks()).toHaveLength(0);
});
+
+ it('countWorks excludes tombstones and agrees with listWorks().length', async () => {
+ // countWorks is the cheap tally the character skill registry reads instead of
+ // rebuilding every work's manifest + drafts[] for a `.length` (#2729). Pin it
+ // against listWorks so the two can never disagree — deleteWork soft-deletes
+ // (the tombstone stays on disk so the deletion federates), so a count that
+ // read the work directories alone would keep counting a deleted work forever.
+ expect(await countWorks()).toBe(0);
+
+ await createWork({ title: 'Kept' });
+ const doomed = await createWork({ title: 'Doomed' });
+ expect(await countWorks()).toBe(2);
+ expect(await countWorks()).toBe((await listWorks()).length);
+
+ await deleteWork(doomed.id);
+ expect(await countWorks()).toBe(1);
+ expect(await countWorks()).toBe((await listWorks()).length);
+ });
});
describe('draft body and versioning', () => {
diff --git a/server/services/writersRoom/store.js b/server/services/writersRoom/store.js
index fe8af2a5c8..b1f0f6b69d 100644
--- a/server/services/writersRoom/store.js
+++ b/server/services/writersRoom/store.js
@@ -95,6 +95,24 @@ function makeFileBackend() {
const entries = await readdir(wrWorksDir(), { withFileTypes: true });
return entries.filter((e) => e.isDirectory() && WORK_ID_RE.test(e.name)).map((e) => e.name);
};
+ // The live-work set, shared by listWorks + countWorks below so the listing and
+ // the tally can't disagree about which works exist.
+ //
+ // Tolerate a corrupted manifest per work (drop it) so one bad work doesn't 500
+ // the whole library — the pre-#1017 file behavior. Re-throw anything else
+ // (permission errors, EIO): masking those would hide a real outage behind a
+ // plausible-looking short count.
+ const loadLiveManifests = async () => {
+ const ids = await listWorkIds();
+ const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch((err) => {
+ if (err?.code === 'CORRUPTED_MANIFEST') {
+ console.warn(`⚠️ wr: dropped work ${id} from listing — corrupted manifest`);
+ return null;
+ }
+ throw err;
+ })));
+ return manifests.filter((m) => m != null && m.deleted !== true);
+ };
// Shared LWW merge for a body-less record array (folders/exercises) — mirrors
// mergeWorksFromSync below minus the per-work manifest file. Loads the array
@@ -209,21 +227,14 @@ function makeFileBackend() {
const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch(() => null)));
return ids.filter((_, i) => manifests[i] && manifests[i].deleted !== true);
},
- listWorks: async () => {
- const ids = await listWorkIds();
- // Tolerate a corrupted manifest per work (drop it from the listing) so one
- // bad work doesn't 500 the whole library — the pre-#1017 file behavior.
- // Re-throw anything else (permission errors, EIO) — masking those would
- // hide a real outage.
- const manifests = await Promise.all(ids.map((id) => loadManifest(id).catch((err) => {
- if (err?.code === 'CORRUPTED_MANIFEST') {
- console.warn(`⚠️ wr: dropped work ${id} from listing — corrupted manifest`);
- return null;
- }
- throw err;
- })));
- return manifests.filter((m) => m != null && m.deleted !== true);
- },
+ listWorks: loadLiveManifests,
+ // No cheap count on the file layout — `deleted` lives inside each manifest,
+ // so the live set can only be known by reading them. Counting the shared
+ // live-set reader makes agreement with listWorks structural rather than a
+ // duplicated filter that could drift. The file backend is a dev/test escape
+ // hatch (never a deployment mode), so its cost here is not worth splitting
+ // the two readers apart to shave.
+ countWorks: async () => (await loadLiveManifests()).length,
writeWork: async (manifest) => { await saveManifest(manifest.id, manifest); return manifest; },
deleteWork: async (id) => {
// Soft-delete tombstone (#1565) so the deletion federates — mirror the PG
@@ -327,6 +338,7 @@ export function writersRoomStore() {
readWork: async (id, opts) => (await getBackend()).readWork(id, opts),
listWorkIds: async (opts) => (await getBackend()).listWorkIds(opts),
listWorks: async () => (await getBackend()).listWorks(),
+ countWorks: async () => (await getBackend()).countWorks(),
writeWork: async (manifest) => (await getBackend()).writeWork(manifest),
deleteWork: async (id) => (await getBackend()).deleteWork(id),
mergeWorksFromSync: async (remoteWorks, opts) => (await getBackend()).mergeWorksFromSync(remoteWorks, opts),