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
fix: keep an unreadable sync base-hash file from silently disabling conflict detection (#7260)
Louis Deconinckc38a7dc4d139
diff --git a/client/src/components/sharing/ConflictsTab.jsx b/client/src/components/sharing/ConflictsTab.jsxindex c5470fdc50..06f17e7331 100644--- a/client/src/components/sharing/ConflictsTab.jsx+++ b/client/src/components/sharing/ConflictsTab.jsx@@ -19,11 +19,16 @@ const asText = (v) => {export default function ConflictsTab() {const [loading, setLoading] = useState(true);const [conflicts, setConflicts] = useState([]);+ // #7260 — when the server reports the sync base-hash store as unreadable,+ // detection is running fail-closed (every overwrite journals) but nothing+ // persists. Show it so an empty list can't read as "no conflicts".+ const [degraded, setDegraded] = useState(null);const load = useCallback(async () => {setLoading(true);const res = await listConflicts('pending', { silent: true }).catch(() => ({ conflicts: [] }));setConflicts(res.conflicts || []);+ setDegraded(res.conflictDetection?.degraded ? res.conflictDetection : null);setLoading(false);}, []);@@ -35,6 +40,11 @@ export default function ConflictsTab() {return (<div className="space-y-4">+ {degraded && (+ <div className="bg-port-warning/10 border border-port-warning/40 rounded-lg px-3 py-2 text-sm text-port-warning">+ ⚠️ Conflict detection is degraded — {degraded.reason || 'the sync base-hash store is unreadable'}. Overwrites are still archived here fail-closed.+ </div>+ )}<p className="text-sm text-gray-400">When two machines edited the same record, sync keeps the newest by timestamp — but the overwritten version isarchived here so nothing is lost. Restore yours, merge back specific fields, or discard.diff --git a/client/src/components/sharing/ConflictsTab.test.jsx b/client/src/components/sharing/ConflictsTab.test.jsxindex 27d41d6ccf..529e2976cb 100644--- a/client/src/components/sharing/ConflictsTab.test.jsx+++ b/client/src/components/sharing/ConflictsTab.test.jsx@@ -32,6 +32,18 @@ beforeEach(() => {});describe('ConflictsTab', () => {+ it('shows the degraded-detection banner when the base-hash store is latched (#7260)', async () => {+ api.listConflicts.mockResolvedValue({+ conflicts: [],+ conflictDetection: { degraded: true, reason: 'sync_base_hashes.json is present but unreadable — repair or delete it and restart' },+ });+ render(<ConflictsTab />);+ expect(await screen.findByText(/Conflict detection is degraded/)).toBeInTheDocument();+ expect(screen.getByText(/sync_base_hashes\.json/)).toBeInTheDocument();+ // The empty list still renders beneath the warning.+ expect(screen.getByText(/No pending conflicts/)).toBeInTheDocument();+ });+it('lists pending conflicts', async () => {render(<ConflictsTab />);await waitFor(() => expect(screen.getByText(/2 field\(s\)/)).toBeInTheDocument());diff --git a/server/lib/README.md b/server/lib/README.mdindex ad9b813390..9ccf9205d6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -280,7 +280,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)`. || `comparisonModelScope.js` | `catalogSlugForProviderModel(id)` / `providerCatalogSlugs(inventory)` — map a PortOS provider model id (Bedrock region prefixes, gateway namespaces, effort/quantization suffixes, dashed versions) onto an Artificial Analysis catalog slug, so the comparison chart and the shipped seed can be scoped to models the install can actually dispatch. Pure. |-| `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 base-hash-evicting `pruneTombstoned*` 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, so those 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. |+| `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 base-hash-evicting `pruneTombstoned*` 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, so those 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). The base-hash file is read STRICT (`readJSONFileStrict`): a present-but-unreadable `sync_base_hashes.json` latches `_persistBlocked` — `flushBaseHashes()` no-ops so the file is preserved, `maybeJournalBeforeOverwrite` journals every overwrite fail-closed, `detectConflict` reports `baseUnavailable`, and `isBaseHashPersistBlocked()` exposes the latch to the conflict-journal status payload (#7260). 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). `resolveCodeRootForModule(moduleUrl)` is the single source of truth for the "two directories above this file" depth assumption — `paths.js`'s `CODE_ROOT` and `services/userActions.js`'s data-root guard both derive through it so they cannot silently drift apart. `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. || `downloadPreflight.js` | Free-disk preflight + resumable weight download. `assessDownloadPreflight({ destPath, expectedBytes })` → `{ freeBytes, requiredBytes, headroomBytes, verdict: ok\|tight\|insufficient }`; `assertDownloadFits` throws typed `DISK_INSUFFICIENT` (507) when the volume cannot hold the payload. `streamResumableDownload` Range-resumes a `.partial` on transport failure, discards it on user cancel, and verifies a published sha256 before rename. `sweepOrphanedPartials(dirs, { maxAgeMs })` unlinks leftover `.partial` (+ `.partial.etag`) files older than 7 days (default) and skips recent/in-flight dests; missing dirs are a no-op. `probeRemoteSize` / `siblingDownloadMeta` / `verifyDownloadHash` are the size+digest helpers the four weight-download entry points share. `createDownloadSlot({ codePrefix, idleStallEnvVar, exclusive, keepPartialOnCancel })` is the one transfer-slot registry a weight download claims before its first await — in-flight map, abort controller carrying a cancel/stall reason, typed `<PREFIX>_DOWNLOAD_IN_FLIGHT`/`_STALLED`/`_CANCELLED` errors, a per-chunk progress throttle, and an `isInFlight(path)` predicate covering the dest, its `.partial`, and shards under a claimed directory. Call it at module scope only. `isAnyDownloadInFlight` answers for every registered slot at once, which is how the orphaned-partial GC protects live transfers. |diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex 5f3e7f5012..c7e49ed736 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -19,7 +19,11 @@** `base == null` ⇒ treat as a clean update (conservative: we only ever MISS* journaling the first divergence after this feature ships for a given record,- * never wedge and never false-positive on routine sequential updates).+ * never wedge and never false-positive on routine sequential updates) — UNLESS+ * the base-hash store itself is untrustworthy: a present-but-unreadable+ * `sync_base_hashes.json` latches `_persistBlocked` (#7260), under which every+ * overwrite journals fail-closed (an unknown baseline is a possible+ * divergence) and nothing ever writes back over the unreadable file.** The base hash advances to the remote's hash on EVERY accepted overwrite* (clean OR conflicting) — without that, the 60s snapshot loop would re-journal@@ -32,7 +36,7 @@import { join } from 'path';import { randomUUID, createHash } from 'crypto';-import { PATHS, atomicWrite, readJSONFile, ensureDir } from './fileUtils.js';+import { PATHS, atomicWrite, readJSONFileStrict, ensureDir } from './fileUtils.js';import { createCollectionStore } from './collectionStore.js';import { canonicalStringify, isPlainObject } from './objects.js';import { sanitizeRecordForWire, stripMusicVideoLocalRenderPins } from './syncWire.js';@@ -216,6 +220,17 @@ let _flushTail = Promise.resolve();// an await-separated multi-record push loop (peer:online convergence) collapses// N `sync_base_hashes.json` rewrites into one at the batch's terminal flush.let _flushBatchDepth = 0;+// Latched when the base-hash file was present-but-unreadable at load (#7260 —+// the `persistBlocked` shape from services/mediaJobQueue). flushBaseHashes()+// whole-file-REPLACES sync_base_hashes.json with the in-memory map, so+// persisting on top of a baseline we failed to read would discard every entry+// the process didn't happen to stamp — and unlike a rebuildable cache, the map+// records what the two machines last agreed on, which no longer exists+// anywhere once it is gone. While latched: nothing flushes (the file survives+// for the user to repair), and maybeJournalBeforeOverwrite fails CLOSED —+// "baseline unknown" is treated as "possible conflict" and journaled. The+// latch is process-lifetime; nothing in production calls __reset.+let _persistBlocked = false;const baseKey = (kind, id) => `${kind}:${id}`;@@ -223,8 +238,24 @@ async function ensureBaseLoaded() {if (_baseHashes) return _baseHashes;if (!_loadPromise) {_loadPromise = (async () => {- const obj = await readJSONFile(BASE_HASH_FILE(), {}, { logError: false });- _baseHashes = new Map(obj && typeof obj === 'object' ? Object.entries(obj) : []);+ // Strict (#7260): a present-but-unreadable file (EACCES, EIO,+ // truncated/partial bytes, a cloud-sync conflict copy) must NOT read as+ // a genuine empty — that silently disabled conflict detection and let+ // the next flush destroy every stored baseline. ENOENT is the only+ // trustworthy empty (first sync). `allowArray: false` makes an+ // array-shaped file unreadable; a non-object scalar parses `ok` but+ // still isn't a baseline map, so it latches too.+ const { ok, value } = await readJSONFileStrict(BASE_HASH_FILE(), {}, { allowArray: false });+ if (ok && isPlainObject(value)) {+ _baseHashes = new Map(Object.entries(value));+ } else {+ _persistBlocked = true;+ _baseHashes = new Map();+ // Name the recovery step: the latch is process-lifetime, so without+ // this the user has conflict detection that silently stops persisting+ // and no indication that repairing or deleting one file restores it.+ console.error(`❌ conflictJournal: ${BASE_HASH_FILE()} is present but unreadable — base hashes are preserved on disk (persistence latched off) and overwrites journal fail-closed; repair or delete it and restart to re-enable persistence`);+ }return _baseHashes;})();}@@ -332,11 +363,18 @@ export async function pruneOrphanedBaseHashes(resolves) {* stamps stay coalesced (`_baseDirty`) and the single disk write fires when the* outermost batch closes. Callers still get a thenable (`_flushTail`) so any* `await flushBaseHashes()` resolves immediately rather than blocking inside- * the batch. */+ * the batch.+ *+ * No-ops while `_persistBlocked` is latched (#7260): the read that seeded the+ * map was untrustworthy, so persisting it back would replace a file that may+ * hold the real baselines with whatever this process stamped since boot.+ * `deleteSyncBaseHash` / `pruneOrphanedBaseHashes` still evict in memory (the+ * session map stays coherent) but their flush is refused for the same reason. */export function flushBaseHashes() {- // 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;+ // Defer while inside a batch, refuse while the store is untrustworthy, and+ // no-op when nothing is dirty — each way the outstanding `_flushTail`+ // thenable is the right thing to await.+ if (_persistBlocked || _flushBatchDepth > 0 || !_baseDirty) return _flushTail;_flushTail = _flushTail.then(async () => {if (!_baseDirty) return;_baseDirty = false;@@ -415,7 +453,11 @@ export async function detectConflict({ kind, id, local, remote }) {const remoteHash = contentHashForRecord(kind, remote, { maxVersion });const isConflict = baseHash != null && localHash != null && remoteHash != null&& localHash !== baseHash && remoteHash !== baseHash && localHash !== remoteHash;- return { isConflict, baseHash, localHash, remoteHash };+ // `baseUnavailable` (#7260): the stored baseline file could not be read, so+ // `isConflict === false` here means "no base to compare against," NOT+ // "proven clean". Callers that journal must branch on this flag — the merge+ // path treats it as fail-closed (see maybeJournalBeforeOverwrite).+ return { isConflict, baseHash, localHash, remoteHash, baseUnavailable: _persistBlocked };}// User-authored content fields a restore/merge may write back, per kind. This@@ -667,9 +709,15 @@ export async function journalConflict({ kind, id, local, remote, source, hashes*/export async function maybeJournalBeforeOverwrite({ kind, id, local, remote, source }) {try {- const { isConflict, baseHash, localHash, remoteHash } = await detectConflict({ kind, id, local, remote });+ const { isConflict, baseHash, localHash, remoteHash, baseUnavailable } = await detectConflict({ kind, id, local, remote });const localIsTombstone = local?.deleted === true;- if (isConflict && localHash != null && !localIsTombstone) {+ // Fail CLOSED while the baseline store is untrustworthy (#7260): with the+ // base hashes unreadable we cannot prove this merge ISN'T a divergence, so+ // "baseline unknown" is treated as "possible conflict" and journaled. A+ // spurious journal entry costs the user one dismissal; a missed one costs+ // their edit. The nothing-to-lose guards still apply — an ephemeral local+ // (no hashable wire form) or a local tombstone has no content to preserve.+ if ((isConflict || baseUnavailable) && localHash != null && !localIsTombstone) {await journalConflict({ kind, id, local, remote, source, hashes: { baseHash, localHash, remoteHash } });}// Advance the base to an UNRESTRICTED (current-version) hash of `remote`,@@ -687,6 +735,22 @@ export async function maybeJournalBeforeOverwrite({ kind, id, local, remote, sou}}+/**+ * True while the `_persistBlocked` latch is held (#7260): the base-hash file+ * was present-but-unreadable at load, so persistence is latched off (the file+ * is preserved for repair) and overwrites journal fail-closed. Surfaced in+ * the conflict-journal status payload so an empty Conflicts list can't be+ * mistaken for "no conflicts" while detection is degraded.+ *+ * Awaits the memoized load so the flag reflects the file's actual state even+ * when no merge has touched the store yet this process — a status poll must+ * not report healthy just because nothing has read the file.+ */+export async function isBaseHashPersistBlocked() {+ await ensureBaseLoaded();+ return _persistBlocked;+}+// Test-only reset of the in-memory base-hash cache so suites that swap PATHS.data// between tests don't bleed state across the module-level cache.export function __resetBaseHashCacheForTests() {@@ -695,5 +759,6 @@ export function __resetBaseHashCacheForTests() {_baseDirty = false;_flushTail = Promise.resolve();_flushBatchDepth = 0;+ _persistBlocked = false;_store = null;}diff --git a/server/lib/conflictJournal.test.js b/server/lib/conflictJournal.test.jsindex 088643435f..0639543a66 100644--- a/server/lib/conflictJournal.test.js+++ b/server/lib/conflictJournal.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';-import { mkdtempSync, rmSync, mkdirSync } from 'fs';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { makePathsProxy } from './mockPathsDataRoot.js';@@ -554,3 +554,136 @@ describe('conflictJournal — withBaseHashFlushBatch coalescing', () => {expect(writeCounter.baseHash).toBe(0);});});++// #7260 — a present-but-unreadable sync_base_hashes.json must fail CLOSED:+// the file is never rewritten from the partial in-memory map, every overwrite+// journals (baseline unknown ⇒ possible conflict), and the latch is surfaced+// so an empty Conflicts list can't read as "no conflicts".+describe('conflictJournal — unreadable base-hash store fails closed (#7260)', () => {+ const baseHashPath = () => join(TEST_DATA_ROOT, 'sharing', 'sync_base_hashes.json');+ // Truncated mid-write bytes — a partial write from a hard power loss or a+ // cloud-sync conflict copy. Present (NOT ENOENT) but unparseable.+ const TRUNCATED = '{"universe:u-9":{"h":"deadbeef","v":1},"series:s-1":{"h":"abc';+ const plantTruncated = () => {+ mkdirSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true });+ writeFileSync(baseHashPath(), TRUNCATED);+ };++ beforeEach(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });+ cj.__resetBaseHashCacheForTests();+ writeCounter.baseHash = 0;+ });++ it('a truncated file survives setSyncBaseHash + flushBaseHashes byte-identical', async () => {+ plantTruncated();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ // The merge loop that used to destroy the file: stamp a fresh entry, flush.+ await cj.setSyncBaseHash('universe', 'u-2', cj.contentHashForRecord('universe', uni({ id: 'u-2' })));+ await cj.flushBaseHashes();+ expect(readFileSync(baseHashPath(), 'utf8')).toBe(TRUNCATED);+ expect(writeCounter.baseHash).toBe(0); // atomicWrite was never attempted+ expect(await cj.isBaseHashPersistBlocked()).toBe(true);+ // The in-memory stamp is still visible to reads (session coherence) — it+ // just can never reach disk.+ expect(await cj.getSyncBaseHash('universe', 'u-2'))+ .toBe(cj.contentHashForRecord('universe', uni({ id: 'u-2' })));+ errSpy.mockRestore();+ });++ it('a missing (ENOENT) file initializes empty and persists normally on first flush', async () => {+ expect(existsSync(baseHashPath())).toBe(false);+ const hash = cj.contentHashForRecord('universe', uni());+ await cj.setSyncBaseHash('universe', 'u-1', hash);+ await cj.flushBaseHashes();+ expect(writeCounter.baseHash).toBe(1);+ expect(JSON.parse(readFileSync(baseHashPath(), 'utf8'))['universe:u-1'].h).toBe(hash);+ expect(await cj.isBaseHashPersistBlocked()).toBe(false);+ });++ it('logs the unreadable state once — with the file path and a repair instruction', async () => {+ plantTruncated();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ await cj.getSyncBaseHash('universe', 'u-1'); // triggers the load + latch+ await cj.setSyncBaseHash('universe', 'u-2', 'h2'); // memoized — must not re-log+ await cj.detectConflict({ kind: 'universe', id: 'u-3', local: uni({ id: 'u-3' }), remote: uni({ id: 'u-3' }) });+ const latchLogs = errSpy.mock.calls+ .map((call) => call.join(' '))+ .filter((m) => m.includes('unreadable'));+ expect(latchLogs).toHaveLength(1);+ expect(latchLogs[0]).toContain(baseHashPath());+ expect(latchLogs[0]).toContain('repair or delete it and restart');+ errSpy.mockRestore();+ });++ it('journals the overwrite while latched — the local edit stays recoverable', async () => {+ plantTruncated();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const local = uni({ starterPrompt: 'precious local edit', updatedAt: '2026-05-02T00:00:00Z' });+ const remote = uni({ starterPrompt: 'REMOTE overwrite', updatedAt: '2026-05-03T00:00:00Z' });+ await cj.maybeJournalBeforeOverwrite({ kind: 'universe', id: 'u-1', local, remote, source: { via: 'sync', peerId: 'peer-B' } });+ const entries = await pendingEntries();+ expect(entries).toHaveLength(1);+ // Recovery path intact: the archived snapshots carry both versions and the+ // entry is a normal pending conflict the user can restore from.+ expect(entries[0]).toMatchObject({ recordKind: 'universe', recordId: 'u-1', status: 'pending', baseHash: null });+ expect(entries[0].localSnapshot.starterPrompt).toBe('precious local edit');+ expect(entries[0].remoteSnapshot.starterPrompt).toBe('REMOTE overwrite');+ errSpy.mockRestore();+ });++ it('detectConflict reports baseUnavailable without claiming a conflict it cannot prove', async () => {+ plantTruncated();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const r = await cj.detectConflict({ kind: 'universe', id: 'u-1', local: uni(), remote: uni({ starterPrompt: 'r' }) });+ expect(r.isConflict).toBe(false); // semantics unchanged — no base to compare+ expect(r.baseHash).toBeNull();+ expect(r.baseUnavailable).toBe(true); // "unknown", not "clean"+ errSpy.mockRestore();+ });++ it('deleteSyncBaseHash and pruneOrphanedBaseHashes refuse to flush while latched', async () => {+ plantTruncated();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ await cj.setSyncBaseHash('universe', 'u-a', 'h-a');+ await cj.setSyncBaseHash('universe', 'u-b', 'h-b');+ await cj.deleteSyncBaseHash('universe', 'u-a'); // flushes internally+ const { pruned } = await cj.pruneOrphanedBaseHashes(async () => false); // evicts u-b+ expect(pruned).toBe(1); // in-memory eviction still ran+ expect(readFileSync(baseHashPath(), 'utf8')).toBe(TRUNCATED);+ expect(writeCounter.baseHash).toBe(0);+ errSpy.mockRestore();+ });++ it('a directory where the file should be is present-but-unreadable too (EISDIR ≈ EACCES)', async () => {+ // Portable stand-in for EACCES/EIO — a readFile errno that is NOT ENOENT.+ mkdirSync(baseHashPath(), { recursive: true });+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ expect(await cj.isBaseHashPersistBlocked()).toBe(true);+ await cj.setSyncBaseHash('universe', 'u-1', 'h1');+ await cj.flushBaseHashes();+ expect(writeCounter.baseHash).toBe(0);+ errSpy.mockRestore();+ });++ it('still journals nothing-to-lose skips while latched (local tombstone, ephemeral local)', async () => {+ plantTruncated();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const remote = uni({ starterPrompt: 'REMOTE', updatedAt: '2026-05-03T00:00:00Z' });+ // Local tombstone — no content to preserve.+ await cj.maybeJournalBeforeOverwrite({+ kind: 'universe', id: 'u-t',+ local: uni({ id: 'u-t', deleted: true, deletedAt: '2026-05-02T00:00:00Z' }),+ remote, source: { via: 'sync' },+ });+ // Ephemeral local — no hashable wire form.+ await cj.maybeJournalBeforeOverwrite({+ kind: 'universe', id: 'u-e',+ local: uni({ id: 'u-e', ephemeral: true }),+ remote, source: { via: 'sync' },+ });+ expect(await pendingEntries()).toHaveLength(0);+ errSpy.mockRestore();+ });+});diff --git a/server/routes/conflictJournal.js b/server/routes/conflictJournal.jsindex 6d376ee363..5d242cb74a 100644--- a/server/routes/conflictJournal.js+++ b/server/routes/conflictJournal.js@@ -7,6 +7,7 @@ import { Router } from 'express';import { z } from 'zod';import { asyncHandler, createServiceErrorMapper } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';+import { isBaseHashPersistBlocked } from '../lib/conflictJournal.js';import * as resolver from '../services/conflictJournalResolver.js';const router = Router();@@ -35,7 +36,17 @@ const resolveSchema = z.object({router.get('/', asyncHandler(async (req, res) => {const { status } = validateRequest(listQuerySchema, req.query ?? {});- res.json({ conflicts: await resolver.listConflicts({ status: status ?? null }) });+ // #7260: while the sync base-hash file is present-but-unreadable the store is+ // latched — persistence is off and every overwrite journals fail-closed.+ // Surface the degradation so an empty `conflicts` list can't be mistaken for+ // "no conflicts"; the Conflicts tab renders this as a warning banner.+ const degraded = await isBaseHashPersistBlocked();+ res.json({+ conflicts: await resolver.listConflicts({ status: status ?? null }),+ conflictDetection: degraded+ ? { degraded: true, reason: 'sync_base_hashes.json is present but unreadable — repair or delete it and restart' }+ : { degraded: false },+ });}));router.get('/:id', asyncHandler(async (req, res) => {diff --git a/server/routes/conflictJournal.test.js b/server/routes/conflictJournal.test.jsindex 526d1d8da5..cbcec7df30 100644--- a/server/routes/conflictJournal.test.js+++ b/server/routes/conflictJournal.test.js@@ -14,6 +14,11 @@ const resolverMock = {};vi.mock('../services/conflictJournalResolver.js', () => resolverMock);+// The route's only lib import is the latch flag — doubled so the payload test+// controls it without depending on a real sync_base_hashes.json on disk.+const libMock = { isBaseHashPersistBlocked: vi.fn() };+vi.mock('../lib/conflictJournal.js', () => libMock);+const conflictJournalRoutes = (await import('./conflictJournal.js')).default;const makeApp = () => {@@ -25,7 +30,10 @@ const makeApp = () => {};describe('conflict-journal routes', () => {- beforeEach(() => vi.clearAllMocks());+ beforeEach(() => {+ vi.clearAllMocks();+ libMock.isBaseHashPersistBlocked.mockResolvedValue(false);+ });it('GET / lists conflicts (optionally filtered by status)', async () => {resolverMock.listConflicts.mockResolvedValue([{ id: 'e1', status: 'pending' }]);@@ -33,6 +41,20 @@ describe('conflict-journal routes', () => {expect(res.status).toBe(200);expect(res.body.conflicts).toHaveLength(1);expect(resolverMock.listConflicts).toHaveBeenCalledWith({ status: 'pending' });+ // Healthy store → the degraded flag is present and false.+ expect(res.body.conflictDetection).toEqual({ degraded: false });+ });++ it('GET / surfaces conflictDetection.degraded while the base-hash store is latched (#7260)', async () => {+ resolverMock.listConflicts.mockResolvedValue([]);+ libMock.isBaseHashPersistBlocked.mockResolvedValue(true);+ const res = await request(makeApp()).get('/api/conflict-journal');+ expect(res.status).toBe(200);+ expect(res.body.conflicts).toEqual([]);+ // An empty list must not read as "no conflicts" — the flag + reason say+ // detection is degraded instead.+ expect(res.body.conflictDetection.degraded).toBe(true);+ expect(res.body.conflictDetection.reason).toContain('sync_base_hashes.json');});it('GET / rejects an invalid status with 400', async () => {diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.jsindex 5e8d16fa8d..92743a5c3e 100644--- a/server/services/pipeline/issues.test.js+++ b/server/services/pipeline/issues.test.js@@ -24,6 +24,12 @@ tryReadFile: vi.fn().mockResolvedValue(null),fileStore.set(path, data);}),readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ // Strict-read counterpart (#7260): a held entry is a trustworthy read; a+ // missing one is the ENOENT "genuine empty". This in-memory model has no+ // present-but-unreadable state — conflictJournal.test.js covers the latch.+ readJSONFileStrict: vi.fn(async (path, fallback) => (fileStore.has(path)+ ? { ok: true, value: fileStore.get(path) }+ : { ok: true, value: fallback })),}));vi.mock('../../lib/conflictJournal.js', async (importOriginal) => {diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.jsindex 31c1d56bb8..b216a1dfc8 100644--- a/server/services/pipeline/series.test.js+++ b/server/services/pipeline/series.test.js@@ -14,6 +14,12 @@ tryReadFile: vi.fn().mockResolvedValue(null),fileStore.set(path, data);}),readJSONFile: vi.fn(async (path, fallback) => (fileStore.has(path) ? fileStore.get(path) : fallback)),+ // Strict-read counterpart (#7260): a held entry is a trustworthy read; a+ // missing one is the ENOENT "genuine empty". This in-memory model has no+ // present-but-unreadable state — conflictJournal.test.js covers the latch.+ readJSONFileStrict: vi.fn(async (path, fallback) => (fileStore.has(path)+ ? { ok: true, value: fileStore.get(path) }+ : { ok: true, value: fallback })),}));vi.mock('../../lib/conflictJournal.js', async (importOriginal) => {