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: batch remaining tombstone base-hash evictions (#5532)

[._.]/ Adam Eivy72bb4cd56799
diff --git a/server/lib/README.md b/server/lib/README.md
index 915bfa5709..867a480b51 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -209,7 +209,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `borderKey.js` | Sharp-free image primitives shared by sprites and image-to-3D: statistics median, subsampled border-band sampling, solid-border coverage detection, and alpha meaningfulness/variation checks. |
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `loadAllResult` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. `loadAll` silently drops corrupt records; `loadAllResult()` → `{ records, failedIds }` keeps the "which ids failed to load" signal so a caller can tell a partial set from a complete one. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. **Type-index `config` slot** holds cross-record state (see the `TypeIndexConfig` typedef + header convention): `{ runs?: [], featureFlags?: {}, lockPolicies?: {} }` — `runs` is the shipped slot (universeBuilder's capped history log), the other two are reserved names; consumers may add their own keys but should reuse a reserved name when it fits and document the shape next to the consumer. `saveTypeIndex({ config })` shallow-merges `config` one level deep (a patched `runs` replaces the whole array), so a read-modify-write of a slot must load → mutate a copy → write inside `queueTypeIndexWrite(fn)`. |
-| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push, and every `pruneTombstoned*` eviction loop — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
+| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record loop — the peer:online convergence push and batched `pruneTombstoned*` eviction loops — collapses N `sync_base_hashes.json` rewrites into one terminal write (depth-counted, so concurrent batches merge too; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned, so covered prune paths don't let the side store grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |
| `agentInstructionsFile.js` | The `AGENTS.md` + bridge `CLAUDE.md` pair a repo carries (#4852). `writeAgentInstructions(repoPath, content)` writes the body to `AGENTS.md` and the one-line `@AGENTS.md` import beside it — use it in scaffolders instead of a bare `writeFile(join(repoPath, 'CLAUDE.md'), …)`, since a generated repo carrying only one name is unreadable to half the CLIs PortOS can point at it. Constants: `AGENT_INSTRUCTIONS_FILENAME`, `CLAUDE_BRIDGE_FILENAME`, `AGENT_INSTRUCTIONS_IMPORT`. |
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 3d70beceb6..182e4f97f3 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -364,10 +364,9 @@ export function flushBaseHashes() {
*
* Two caller shapes use it: the `peer:online` convergence walk
* `retryPendingPushesForPeer` (pushes — and stamps — every subscribed record in
- * sequence), and the direct await-separated eviction loops in the mood-board,
- * music-video-project, and commission-feedback prune paths. Each EVICTS a base
- * hash per hard-deleted record. Eviction only marks `_baseDirty` for a key the
- * map actually held, so a prune that removed nothing still costs zero writes.
+ * sequence), and `pruneTombstoned*` hard-prune loops that evict a base hash per
+ * hard-deleted record. Eviction only marks `_baseDirty` for a key the map
+ * actually held, so a prune that removed nothing still costs zero writes.
*
* Re-entrant (depth-counted) so nested scopes collapse to the outermost batch,
* and the terminal flush runs in `finally` so a thrown/rejected `fn` still
diff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.js
index 116498e1b2..6e93a16616 100644
--- a/server/lib/db.guards.test.js
+++ b/server/lib/db.guards.test.js
@@ -485,11 +485,10 @@ describe('DB-backed test files are covered by vitest.config.db.js', () => {
});
it('every explicit DB_TEST_INCLUDE entry resolves to a real file', () => {
- // Basename matching above proves a suite IS listed, but not that its include
- // PATH is correct — a wrong path (e.g. `../scripts/x` for a file under
- // `scripts/x`) matches no file in vitest yet is "covered" by basename, so the
- // suite silently never runs. Resolve each non-glob entry against the config
- // root (server/) and assert it exists.
+ // Path matching above proves a detected suite is covered, but it does not
+ // prove every explicit include path resolves to a file; a stale entry for a
+ // renamed or deleted suite would otherwise be invisible. Resolve each
+ // non-glob entry against the config root (server/) and assert it exists.
const SERVER = join(dirname(fileURLToPath(import.meta.url)), '..');
const broken = DB_TEST_INCLUDE
.filter((p) => !p.includes('*'))
diff --git a/server/services/creativeCommissions/feedbackStore.test.js b/server/services/creativeCommissions/feedbackStore.test.js
index 97c7323e0c..9588cfa078 100644
--- a/server/services/creativeCommissions/feedbackStore.test.js
+++ b/server/services/creativeCommissions/feedbackStore.test.js
@@ -186,6 +186,7 @@ describe('federation facades', () => {
const result = await pruneTombstonedCommissionFeedback(Date.parse('2030-01-01T00:00:00.000Z'));
expect(result).toEqual({ pruned: 2, ids: [oldOne.id, oldTwo.id] });
expect(writeCounter.baseHash).toBe(1);
+ cj.__resetBaseHashCacheForTests();
expect(await cj.getSyncBaseHash('commissionFeedback', oldOne.id)).toBeNull();
expect(await cj.getSyncBaseHash('commissionFeedback', oldTwo.id)).toBeNull();
expect(feedbackRecords.has(newer.id)).toBe(true);
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index c98481064e..e28ccd9ed9 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -65,6 +65,7 @@ import {
setSyncBaseHash,
deleteSyncBaseHash,
flushBaseHashes,
+ withBaseHashFlushBatch,
maybeJournalBeforeOverwrite,
} from '../../lib/conflictJournal.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
@@ -986,21 +987,23 @@ export async function pruneTombstonedCommissions(olderThanMs) {
// put, and the next sweep retries both halves — never an orphaned rating.
const candidates = await store.listPrunable(olderThanMs);
const ids = [];
- for (const id of candidates) {
- const pruned = await store.queueRecordWrite(id, async () => {
- // Recheck the backend's FULL prune predicate, not just deleted:true — a
- // peer merge that rewrote this tombstone with a fresher deletedAt mid-
- // sweep restarted its GC grace period, and hard-deleting it early would
- // let an offline peer resurrect the stale record.
- if (!(await store.isPrunable(id, olderThanMs))) return false;
- await tombstoneFeedbackForCommission(id);
- await store.deleteRaw(id);
- return true;
- });
- if (!pruned) continue;
- ids.push(id);
- await deleteSyncBaseHash(CREATIVE_COMMISSION_KIND, id).catch(() => {});
- }
+ await withBaseHashFlushBatch(async () => {
+ for (const id of candidates) {
+ const pruned = await store.queueRecordWrite(id, async () => {
+ // Recheck the backend's FULL prune predicate, not just deleted:true — a
+ // peer merge that rewrote this tombstone with a fresher deletedAt mid-
+ // sweep restarted its GC grace period, and hard-deleting it early would
+ // let an offline peer resurrect the stale record.
+ if (!(await store.isPrunable(id, olderThanMs))) return false;
+ await tombstoneFeedbackForCommission(id);
+ await store.deleteRaw(id);
+ return true;
+ });
+ if (!pruned) continue;
+ ids.push(id);
+ await deleteSyncBaseHash(CREATIVE_COMMISSION_KIND, id).catch(() => {});
+ }
+ });
return { pruned: ids.length, ids };
}
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index 15baecb53e..faba1e2e03 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -23,19 +23,36 @@ const makeMemStore = (type) => {
};
vi.mock('../../lib/collectionStore.js', () => ({ createCollectionStore: ({ type }) => makeMemStore(type) }));
vi.mock('../../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-test-data' } }));
-// Keep the federation side-effects (peer push, conflict-journal disk I/O) inert
-// so the store unit tests stay deterministic and offline.
+// Keep peer push inert, but model the conflict-journal batch boundary so the
+// prune test can assert that multiple evictions share one terminal flush.
vi.mock('../sharing/recordEvents.js', () => ({
emitRecordUpdated: vi.fn(), emitRecordDeleted: vi.fn(),
autoSubscribeRecordToAllPeers: vi.fn(() => Promise.resolve()),
}));
-vi.mock('../../lib/conflictJournal.js', () => ({
- contentHashForRecord: vi.fn(() => 'hash'),
- setSyncBaseHash: vi.fn(() => Promise.resolve()),
- deleteSyncBaseHash: vi.fn(() => Promise.resolve()),
- flushBaseHashes: vi.fn(() => Promise.resolve()),
- maybeJournalBeforeOverwrite: vi.fn(() => Promise.resolve()),
-}));
+const conflictJournalMock = vi.hoisted(() => {
+ const state = { batchDepth: 0, baseHashWrites: 0 };
+ const flushBaseHashes = vi.fn(async () => {
+ if (state.batchDepth === 0) state.baseHashWrites += 1;
+ });
+ return {
+ state,
+ contentHashForRecord: vi.fn(() => 'hash'),
+ setSyncBaseHash: vi.fn(() => Promise.resolve()),
+ deleteSyncBaseHash: vi.fn(() => flushBaseHashes()),
+ flushBaseHashes,
+ withBaseHashFlushBatch: vi.fn(async (fn) => {
+ state.batchDepth += 1;
+ try {
+ return await fn();
+ } finally {
+ state.batchDepth -= 1;
+ if (state.batchDepth === 0) await flushBaseHashes();
+ }
+ }),
+ maybeJournalBeforeOverwrite: vi.fn(() => Promise.resolve()),
+ };
+});
+vi.mock('../../lib/conflictJournal.js', () => conflictJournalMock);
const {
sanitizeCommission,
@@ -64,7 +81,13 @@ const {
} = await import('./store.js');
const { buildCommissionDirective } = await import('./abilityAdapters.js');
-beforeEach(() => { records.clear(); feedbackRecords.clear(); });
+beforeEach(() => {
+ records.clear();
+ feedbackRecords.clear();
+ conflictJournalMock.state.batchDepth = 0;
+ conflictJournalMock.state.baseHashWrites = 0;
+ vi.clearAllMocks();
+});
const validInput = () => ({
name: 'Nightly Surreal',
@@ -511,6 +534,28 @@ describe('deleteCommission', () => {
});
describe('pruneTombstonedCommissions', () => {
+ it('batches base-hash eviction for multiple tombstones', async () => {
+ const tombstone = (id, deletedAt) => ({
+ id, name: id, enabled: false, targetAbility: 'video', brief: {}, generation: {},
+ schedule: { kind: 'DAILY', atLocalTime: null, timezone: null }, runs: [], feedback: [],
+ assignment: null, createdAt: deletedAt, updatedAt: deletedAt, briefUpdatedAt: deletedAt,
+ deleted: true, deletedAt,
+ });
+ records.set('commission-prune-old-1', tombstone('commission-prune-old-1', '2020-01-01T00:00:00.000Z'));
+ records.set('commission-prune-old-2', tombstone('commission-prune-old-2', '2020-01-02T00:00:00.000Z'));
+ records.set('commission-prune-new', tombstone('commission-prune-new', '2099-01-01T00:00:00.000Z'));
+
+ const result = await pruneTombstonedCommissions(Date.parse('2030-01-01T00:00:00.000Z'));
+
+ expect(result).toEqual({
+ pruned: 2,
+ ids: ['commission-prune-old-1', 'commission-prune-old-2'],
+ });
+ expect(conflictJournalMock.deleteSyncBaseHash).toHaveBeenCalledTimes(2);
+ expect(conflictJournalMock.state.baseHashWrites).toBe(1);
+ expect(records.has('commission-prune-new')).toBe(true);
+ });
+
it('tombstones the commission\'s feedback BEFORE the hard-prune so it GCs instead of staying live', async () => {
const created = await createCommission(validInput());
await recordCommissionRun(created.id, { id: 'run-A', status: 'completed' });
diff --git a/server/services/moodBoard/db.test.js b/server/services/moodBoard/db.test.js
index e843ef478b..df2c6318d0 100644
--- a/server/services/moodBoard/db.test.js
+++ b/server/services/moodBoard/db.test.js
@@ -214,6 +214,7 @@ describe.skipIf(!dbReady)('mood board federation (#1564)', () => {
const res = await db.pruneTombstonedBoards(Date.parse('2025-01-01T00:00:00.000Z'));
expect(res).toEqual({ pruned: 2 });
expect(testState.writeCounter.baseHash).toBe(1);
+ __resetBaseHashCacheForTests();
expect(await getSyncBaseHash('moodBoard', oldId)).toBeNull();
expect(await getSyncBaseHash('moodBoard', oldIdTwo)).toBeNull();
expect(await db.getBoard(newId, { includeDeleted: true })).not.toBeNull();
diff --git a/server/services/musicVideo/projectsDB.test.js b/server/services/musicVideo/projectsDB.test.js
index 013561ab20..cd93353445 100644
--- a/server/services/musicVideo/projectsDB.test.js
+++ b/server/services/musicVideo/projectsDB.test.js
@@ -92,6 +92,7 @@ describe.skipIf(!dbReady)('music video projects DB adapter', () => {
const result = await db.pruneTombstonedProjects(Date.parse('2030-01-01T00:00:00.000Z'));
expect(result).toEqual({ pruned: 2 });
expect(testState.writeCounter.baseHash).toBe(1);
+ __resetBaseHashCacheForTests();
expect(await getSyncBaseHash('musicVideoProject', oldOne.id)).toBeNull();
expect(await getSyncBaseHash('musicVideoProject', oldTwo.id)).toBeNull();
expect(await db.getProject(newer.id, { includeDeleted: true })).not.toBeNull();
diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.js
index 3ba5c8dab4..df5bcacf46 100644
--- a/server/services/musicVideo/projectsFile.test.js
+++ b/server/services/musicVideo/projectsFile.test.js
@@ -161,6 +161,7 @@ describe('projectsFile federation (#1770)', () => {
const res = await file.pruneTombstonedProjects(Date.parse('2010-01-01T00:00:00Z'));
expect(res).toEqual({ pruned: 2 });
expect(writeCounter.baseHash).toBe(1);
+ cj.__resetBaseHashCacheForTests();
expect(await cj.getSyncBaseHash('musicVideoProject', 'mv-old-tomb-1')).toBeNull();
expect(await cj.getSyncBaseHash('musicVideoProject', 'mv-old-tomb-2')).toBeNull();
expect((await file.listProjectIds({ includeDeleted: true })).sort()).toEqual([keep.id, 'mv-new-tomb'].sort());
diff --git a/server/services/writersRoom/sync.js b/server/services/writersRoom/sync.js
index 1ecba62b70..582986d116 100644
--- a/server/services/writersRoom/sync.js
+++ b/server/services/writersRoom/sync.js
@@ -17,7 +17,7 @@
import { rm } from 'fs/promises';
import { existsSync } from 'fs';
import { sha256File } from '../../lib/fileUtils.js';
-import { deleteSyncBaseHash } from '../../lib/conflictJournal.js';
+import { deleteSyncBaseHash, withBaseHashFlushBatch } from '../../lib/conflictJournal.js';
import { writersRoomStore } from './store.js';
import {
WRITERS_ROOM_WORK_KIND, WRITERS_ROOM_DRAFT_ASSET_KIND, draftAssetEntries,
@@ -65,11 +65,13 @@ export async function mergeWorksFromSync(remoteWorks, options = {}) {
*/
export async function pruneTombstonedWorks(olderThanMs) {
const { pruned, ids } = await store().pruneTombstonedWorks(olderThanMs);
- for (const id of ids) {
- if (typeof id !== 'string' || !WORK_ID_RE.test(id)) continue;
- await rm(wrWorkDir(id), { recursive: true, force: true }).catch(() => {});
- await deleteSyncBaseHash(WRITERS_ROOM_WORK_KIND, id);
- }
+ await withBaseHashFlushBatch(async () => {
+ for (const id of ids) {
+ if (typeof id !== 'string' || !WORK_ID_RE.test(id)) continue;
+ await rm(wrWorkDir(id), { recursive: true, force: true }).catch(() => {});
+ await deleteSyncBaseHash(WRITERS_ROOM_WORK_KIND, id);
+ }
+ });
return { pruned };
}
@@ -87,10 +89,12 @@ export async function pruneTombstonedWorks(olderThanMs) {
// cleanup — no work dir to rm). `idRe` rejects a junk id before the eviction.
async function pruneTombstonedBodyless(storePruneFn, kind, idRe, olderThanMs) {
const { pruned, ids } = await storePruneFn(olderThanMs);
- for (const id of ids) {
- if (typeof id !== 'string' || !idRe.test(id)) continue;
- await deleteSyncBaseHash(kind, id);
- }
+ await withBaseHashFlushBatch(async () => {
+ for (const id of ids) {
+ if (typeof id !== 'string' || !idRe.test(id)) continue;
+ await deleteSyncBaseHash(kind, id);
+ }
+ });
return { pruned };
}
diff --git a/server/services/writersRoom/sync.test.js b/server/services/writersRoom/sync.test.js
index d29070dd90..a45b688997 100644
--- a/server/services/writersRoom/sync.test.js
+++ b/server/services/writersRoom/sync.test.js
@@ -16,19 +16,30 @@ import { tmpdir } from 'os';
import { join } from 'path';
const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'wr-sync-test-'));
+const writeCounter = { baseHash: 0 };
vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
- return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },
+ atomicWrite: async (path, data) => {
+ if (typeof path === 'string' && path.endsWith('sync_base_hashes.json')) writeCounter.baseHash += 1;
+ return actual.atomicWrite(path, data);
+ },
+ };
});
const sync = await import('./sync.js');
const { writersRoomStore, _resetWritersRoomStore } = await import('./store.js');
const cj = await import('../../lib/conflictJournal.js');
+const { WRITERS_ROOM_WORK_KIND, WRITERS_ROOM_FOLDER_KIND } = await import('./syncLogic.js');
const { wrWorkDir, wrDraftPath } = await import('./_shared.js');
const WR = join(TEST_DATA_ROOT, 'writers-room');
const WORK = 'wr-work-11111111-1111-1111-1111-111111111111';
+const WORK_TWO = 'wr-work-33333333-3333-3333-3333-333333333333';
+const WORK_NEW = 'wr-work-66666666-6666-6666-6666-666666666666';
const DRAFT = 'wr-draft-22222222-2222-2222-2222-222222222222';
const work = (extra = {}) => ({
@@ -53,6 +64,7 @@ describe('Writers Room federation facade — file backend', () => {
rmSync(WR, { recursive: true, force: true });
_resetWritersRoomStore();
cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
});
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
@@ -96,6 +108,25 @@ describe('Writers Room federation facade — file backend', () => {
expect(await sync.getWorkForSync(WORK)).toBeNull();
});
+ it('pruneTombstonedWorks batches base-hash eviction for multiple tombstones', async () => {
+ await sync.mergeWorksFromSync([
+ work({ id: WORK, updatedAt: '2000-01-02T00:00:00.000Z', deleted: true, deletedAt: '2000-01-01T00:00:00.000Z' }),
+ work({ id: WORK_TWO, updatedAt: '2000-01-03T00:00:00.000Z', deleted: true, deletedAt: '2000-01-02T00:00:00.000Z' }),
+ work({ id: WORK_NEW, updatedAt: '2099-01-02T00:00:00.000Z', deleted: true, deletedAt: '2099-01-01T00:00:00.000Z' }),
+ ]);
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_WORK_KIND, WORK)).not.toBeNull();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_WORK_KIND, WORK_TWO)).not.toBeNull();
+
+ writeCounter.baseHash = 0;
+ const result = await sync.pruneTombstonedWorks(Date.parse('2025-01-01T00:00:00.000Z'));
+ expect(result).toEqual({ pruned: 2 });
+ expect(writeCounter.baseHash).toBe(1);
+ cj.__resetBaseHashCacheForTests();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_WORK_KIND, WORK)).toBeNull();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_WORK_KIND, WORK_TWO)).toBeNull();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_WORK_KIND, WORK_NEW)).not.toBeNull();
+ });
+
it('builds a draft-body manifest from the on-disk .md and diffs it against local', async () => {
writeBody('Once upon a time.');
const manifest = await sync.buildWorkBodyManifest(work());
@@ -129,6 +160,8 @@ describe('Writers Room federation facade — file backend', () => {
// ---------- folders + exercises (body-less records, #1645) ----------
const FOLDER = 'wr-folder-44444444-4444-4444-4444-444444444444';
+const FOLDER_TWO = 'wr-folder-77777777-7777-7777-7777-777777777777';
+const FOLDER_NEW = 'wr-folder-88888888-8888-8888-8888-888888888888';
const EXERCISE = 'wr-ex-55555555-5555-5555-5555-555555555555';
const folder = (extra = {}) => ({
id: FOLDER, name: 'Drafts', parentId: null, sortOrder: 0,
@@ -145,6 +178,7 @@ describe('Writers Room folder federation facade — file backend', () => {
rmSync(WR, { recursive: true, force: true });
_resetWritersRoomStore();
cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
});
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
@@ -166,6 +200,25 @@ describe('Writers Room folder federation facade — file backend', () => {
expect(await sync.pruneTombstonedFolders(Date.parse('2026-02-01T00:00:00.000Z'))).toEqual({ pruned: 1 });
expect(await sync.getFolderForSync(FOLDER)).toBeNull();
});
+
+ it('pruneTombstonedFolders batches base-hash eviction for multiple tombstones', async () => {
+ await sync.mergeFoldersFromSync([
+ folder({ id: FOLDER, updatedAt: '2000-01-02T00:00:00.000Z', deleted: true, deletedAt: '2000-01-01T00:00:00.000Z' }),
+ folder({ id: FOLDER_TWO, updatedAt: '2000-01-03T00:00:00.000Z', deleted: true, deletedAt: '2000-01-02T00:00:00.000Z' }),
+ folder({ id: FOLDER_NEW, updatedAt: '2099-01-02T00:00:00.000Z', deleted: true, deletedAt: '2099-01-01T00:00:00.000Z' }),
+ ]);
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_FOLDER_KIND, FOLDER)).not.toBeNull();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_FOLDER_KIND, FOLDER_TWO)).not.toBeNull();
+
+ writeCounter.baseHash = 0;
+ const result = await sync.pruneTombstonedFolders(Date.parse('2025-01-01T00:00:00.000Z'));
+ expect(result).toEqual({ pruned: 2 });
+ expect(writeCounter.baseHash).toBe(1);
+ cj.__resetBaseHashCacheForTests();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_FOLDER_KIND, FOLDER)).toBeNull();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_FOLDER_KIND, FOLDER_TWO)).toBeNull();
+ expect(await cj.getSyncBaseHash(WRITERS_ROOM_FOLDER_KIND, FOLDER_NEW)).not.toBeNull();
+ });
});
describe('Writers Room exercise federation facade — file backend', () => {
@@ -173,6 +226,7 @@ describe('Writers Room exercise federation facade — file backend', () => {
rmSync(WR, { recursive: true, force: true });
_resetWritersRoomStore();
cj.__resetBaseHashCacheForTests();
+ writeCounter.baseHash = 0;
});
afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));