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

refactor([conflict-journal-push-flush-coalesce]): tidy flush-batch from /simplify pass

[._.]/ Adam Eivyba1e5f3da46c
diff --git a/PLAN.md b/PLAN.md
index 71ebd02414..5ea414ae73 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,6 +6,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
Claimable, well-specified, no decision needed — `/claim`-able. Unordered.
+- [ ] [conflict-journal-subscribe-fanout-flush-coalesce] **Coalesce base-hash flushes across the auto-subscribe fan-out loops too.** `withBaseHashFlushBatch` (added in `[conflict-journal-push-flush-coalesce]`) now wraps the `retryPendingPushesForPeer` convergence walk, but two other multi-push loops in `server/services/sharing/peerSync.js` still flush per record: `autoSubscribeRecordToAllPeers` (~362, one record → N peers) and `autoSubscribePeerToAllRecords` (~393, N records → one peer, the category-toggle backfill). Wrapping them is NOT a simple `withBaseHashFlushBatch(async () => { for … })` like the convergence loop was — `subscribePeer` fires its initial `pushRecordToPeer(sub)` **fire-and-forget** (`peerSync.js` ~281, not awaited), so the async stamps/flushes escape the synchronous batch scope before the terminal flush fires and the coalescing is lost. Coalescing here requires either (a) threading an `awaitInitialPush`/batch-aware option through `subscribePeer` so the fan-out can await each initial push inside the batch, or (b) collecting the created subs and doing an explicit post-loop `withBaseHashFlushBatch` re-push. Both change the deliberately-non-blocking initial-push contract, so it's its own change + test surface. Surfaced by /simplify (efficiency) during the convergence-loop coalesce PR (2026-06-02).
- [ ] [conflict-journal-base-hash-prune] **`sync_base_hashes.json` grows unbounded.** `server/lib/conflictJournal.js` seeds a base hash per synced universe/series and never prunes entries for deleted/tombstoned records. Tiny per-entry, but a long-lived install accumulates dead keys. Add a sweep (drop keys whose record no longer resolves) to the tombstone GC path.
- [ ] [makesplitmigration-shared-factory] **Extract a shared `makeSplitMigration` factory into `scripts/migrations/_lib.js`.** The monolithic→per-record split scaffolding (`fileExists` / `readJsonStrict` / `readJsonTolerant` / `writeJson` + the `withFileTypes` already-split scan + the gate1/gate2/recovery/split/stamp/backup body) is now copied verbatim across **four** migrations: `034-split-universe-builder`, `035-split-pipeline-issues`, `036-split-pipeline-series`, `059-split-media-collections`. They differ only in `{ typeDirName, legacyFilename, backupSuffix, typeSchemaVersion, typeLabel, recordsKey, idPattern, buildConfig }` (e.g. `config: { runs }` for universes vs `config: {}` for collections). `_lib.js` already houses cross-migration families (`makePromptReplaceMigration`, layout helpers) — add a split family there and collapse the four to ~15-line config blocks. Pre-existing duplication; 059 was the 4th copy. Own change + test surface, so deferred out of the migration PR.
- [ ] [mediacollections-parallel-merge-prune] **Parallelize the multi-record loops in `mergeMediaCollectionsFromSync` and `pruneTombstonedCollections`.** Both iterate distinct record ids in a sequential `for await` over `queueRecordWrite` — different ids use different per-record queues, so a bounded `Promise.all` (use the shared bounded-concurrency mapper) would fan out the snapshot-apply batch (`dataSync.js` passes a full collections list) and the GC sweep. Most peer pushes carry a single record so the realized win is the snapshot/GC paths only; low priority.
diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.js
index 22cdbe9b8d..699a66b531 100644
--- a/server/lib/conflictJournal.js
+++ b/server/lib/conflictJournal.js
@@ -181,8 +181,9 @@ export async function deleteSyncBaseHash(kind, id) {
* `await flushBaseHashes()` resolves immediately rather than blocking inside
* the batch. */
export function flushBaseHashes() {
- if (_flushBatchDepth > 0) return _flushTail;
- if (!_baseDirty) return _flushTail;
+ // Defer while inside a batch, and no-op when nothing is dirty — either way the
+ // outstanding `_flushTail` thenable is the right thing to await.
+ if (_flushBatchDepth > 0 || !_baseDirty) return _flushTail;
_flushTail = _flushTail.then(async () => {
if (!_baseDirty) return;
_baseDirty = false;
@@ -201,12 +202,13 @@ export function flushBaseHashes() {
*
* The base-hash map already coalesces SYNCHRONOUS bursts (the `_baseDirty` flag
* means a run of `setSyncBaseHash` calls before a single `flushBaseHashes` pays
- * one write). What it can't collapse on its own is an AWAIT-SEPARATED loop: the
- * `peer:online` convergence walk (`retryPendingPushesForPeer`) pushes N records
- * in sequence, and each push's fire-and-forget `flushBaseHashes()` lands on the
- * settled `_flushTail` from the previous record — so a 50-record convergence
- * rewrites `sync_base_hashes.json` 50 times. Wrapping the loop in this scope
- * defers every interior flush; the single terminal write captures all N stamps.
+ * one write). What it can't collapse on its own is an AWAIT-SEPARATED loop that
+ * stamps + flushes per iteration: each flush lands on the previous one's settled
+ * `_flushTail`, so an N-iteration loop rewrites `sync_base_hashes.json` N times.
+ * Wrapping the loop in this scope defers every interior flush; the single
+ * terminal write captures all N stamps. (Caller in the tree today: the
+ * `peer:online` convergence walk `retryPendingPushesForPeer`, which pushes —
+ * and stamps — every subscribed record in sequence.)
*
* 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
@@ -214,6 +216,10 @@ export function flushBaseHashes() {
* debounce (tried and reverted — the unref'd timer leaked into `peerSync.test.js`'s
* settle-waits and made the suite flaky), this is deterministic: the flush is
* tied to the scope boundary, not a wall-clock timer, so tests just `await` it.
+ *
+ * Contract note: stamps performed inside the scope must have settled (the
+ * in-memory `setSyncBaseHash` awaited) before `fn` returns, or the terminal
+ * flush won't see `_baseDirty` for them. The current caller awaits its stamps.
*/
export async function withBaseHashFlushBatch(fn) {
_flushBatchDepth += 1;