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(mortalloom): retry on EAGAIN and pin against iCloud eviction (#450)
[._.]/ Adam Eivyc5dc3030aac5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5b15fe84e9..d5add3bc53 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -29,4 +29,5 @@- Auto-run the world → universe data rename on server boot. The conversion previously shipped as a manual CLI script (`server/scripts/migrateWorldToUniverse.js`) that nobody knew to invoke, so installs upgrading from the World Builder era kept stale `data/world-builder.json` files and never saw their worlds appear as universes. The new migration `031-world-to-universe-data-rename.js` does the file rename, top-level key rename (`worlds`→`universes`), `worldId`→`universeId` rewrite in `pipeline-series.json`, `worldRun`→`universeRun` rewrite in `media-jobs.json`, and also relinks any `"World: <name>"` render collections in `media-collections.json` to their universe by canonical-name match.- Universe Builder picker dropdown rendered beneath the tab subnav and downstream section cards in Lumen Glass / Blueprint Ops themes. Those themes ship a non-`none` `--port-backdrop-filter`, and the global rule in `index.css` applies it to every `.bg-port-card.border.rounded*` — which turns each such card into its own stacking context. The picker's `absolute z-30` dropdown was trapped inside the header card's context and couldn't paint over later sibling cards. Adding `relative z-30` to the picker's `<header>` lets that stacking context win against subsequent siblings so the dropdown overlays them as intended.- TUI agent raw-PTY buffer no longer truncates the head at ~640KB ("⚠️ raw PTY buffer exceeded 1MB — head dropped"). The buffer feeds `analyzeAgentFailure` at finalize, so silently slicing the head was the exact behavior the warning admitted to ("failure analysis may miss earlier symptoms"). `server/services/agentTuiSpawning.js` now spools raw PTY bytes to a per-agent `raw.txt` file in 250ms-debounced batches (mirroring the existing parsed-output pipeline that writes `output.txt`), so the in-memory footprint stays bounded regardless of run length. `analyzeAgentFailure` reads the **tail** of the file (last 1MB) on failure via a non-throwing `readFileTail` helper; successful runs skip the read entirely. The paste-marker poll keeps only a short-lived post-paste accumulator that lives for the paste window. A 256MB disk safety valve truncates `raw.txt` if a runaway agent exceeds the cap (preserves the most-recent bytes that `readFileTail` actually consumes; warns once and sets a `rawSpoolTruncated` agent-metadata flag). The old `rawBufferTruncated` flag is gone with the in-memory truncation logic.+- MortalLoom iCloud reads now survive macOS Optimize-Mac-Storage evictions. The prior fix tolerated `EAGAIN`/-11 from `bird`'s coordination locks by warning + returning `null`, but every dashboard `Proactive Alerts` poll (every 2 min via `useAutoRefetch`) still surfaced the warning whenever the file had been evicted: `existsSync` returns true on a placeholder, then `readFile` triggers an async download that doesn't return inline, so the read fails with EAGAIN. `server/services/mortalLoomStore.js` now (1) retries every transient `readFile`/`writeFile`/`stat` up to three times with 50ms then 100ms backoff before falling through to the warn path — covers the common <200ms coordination/materialize windows so transients are invisible to the UI; (2) fires `brctl download <path>` against the configured store path at server boot (and again whenever `settings:updated` flips MortalLoom sync on or changes the path) so macOS pre-materializes the file. Note that `brctl download` only triggers the download — it does **not** set a persistent "Keep Downloaded" flag (that requires Finder, or undocumented `brctl unevict`), so re-eviction under future disk pressure is still possible; the retry path is what guarantees the hardening, the pre-materialize just collapses the first-read latency. Best-effort and macOS-only — non-darwin and missing-`brctl` environments fall through to the retry path. Disabling sync clears the dedup cache so a later re-enable with the same path re-materializes instead of silently no-op'ing.- `GET /api/digital-twin/identity/goals` (and any other identity read that consults MortalLoom iCloud sync) 500'd with `Unknown system error -11, read` when the MortalLoom.json file in the iCloud ubiquity container was momentarily unreadable — typically while iCloud was mid-sync, downloading, or resolving a conflict. `readStore()` and `getStatus()` in `server/services/mortalLoomStore.js` now catch the transient `readFile`/`stat` failure, log a single warning with the errno, and return `null` / a null-summary response (matching the existing "file not present yet" path). ENOENT races between `existsSync` and `readFile`/`stat` (file disappears mid-call) are treated as silently absent rather than transient — no warning noise, and `getStatus()` reports `exists:false` instead of falsely reporting `exists:true,size:0`. `updateStore()` resolves the path once and threads it through both the read and the write so a settings change mid-call can't desync the overwrite guard from the actual write target; it also refuses to overwrite when the parsed store isn't a plain object (array/primitive) so `JSON.stringify` can't silently drop named properties. Read consumers (`mlArrayIfEnabled`, `mlGetProfileIfEnabled`, `readDailyLogIfEnabled`, `mlIdAtDateIndex`) already handled `null` as "fall through to local PortOS data," so the goals endpoint now serves local data instead of 500ing.diff --git a/server/index.js b/server/index.jsindex 0a8004147d..26ceaf9583 100644--- a/server/index.js+++ b/server/index.js@@ -77,6 +77,7 @@ import identityRoutes from './routes/identity.js';import instancesRoutes from './routes/instances.js';import meatspaceRoutes from './routes/meatspace.js';import mortallomRoutes from './routes/mortalloom.js';+import { initMortalLoomStore } from './services/mortalLoomStore.js';import reviewRoutes from './routes/review.js';import githubRoutes from './routes/github.js';import settingsRoutes from './routes/settings.js';@@ -599,6 +600,15 @@ ensureSelf()initComicPagesFilenameHook();initStoryboardsFilenameHook();initSeasonCoverFilenameHook();+ // Best-effort pre-materialize the MortalLoom iCloud store so the+ // dashboard's proactive-alerts poll (and other readers) don't trigger+ // on-demand downloads that surface as EAGAIN. `brctl download` only+ // materializes the file — it does not pin against future eviction, so+ // the retry-on-EAGAIN path inside the store is what guarantees the+ // hardening. Fire-and-forget — failures are logged.+ initMortalLoomStore().catch((err) => {+ console.warn(`⚠️ MortalLoom store init failed: ${err.message}`);+ });}).then(() => {// Sharing: attach chokidar watchers to every registered share bucket sodiff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex 3c381d473f..50a43efb4f 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -13,15 +13,60 @@ import { join } from 'path';import { readFile, writeFile, stat } from 'fs/promises';import { existsSync } from 'fs';import { randomUUID } from 'crypto';+import { spawn } from 'child_process';import { safeJSONParse, readJSONFile, dataPath, ensureDir } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';-import { getSettings } from './settings.js';+import { getSettings, settingsEvents } from './settings.js';const DEFAULT_ICLOUD_PATH = join(homedir(),'Library/Mobile Documents/iCloud~net~shadowpuppet~MeatSpaceTracker/Documents/MortalLoom.json');+// settings.json is shallow-merged and not schema-validated, so the path field+// can land here as any JSON shape (number, array, object, …). Calling .trim()+// on a non-string throws — and one of our call sites is an EventEmitter+// listener where an unhandled throw crashes the process. Centralize the+// "treat-as-string-or-fall-back" guard at every read.+function normalizePath(rawPath) {+ return (typeof rawPath === 'string' ? rawPath.trim() : '') || DEFAULT_ICLOUD_PATH;+}++// === Transient-error retry ===++// iCloud's `bird` daemon takes brief exclusive coordination locks during sync+// windows and on-demand materialization of evicted files. These surface as+// EAGAIN (errno -11) or EDEADLK from Node's fs calls. 50ms + 100ms covers the+// common sub-200ms coordination windows without making transients observable.+// Exposed (not const) so tests can set it to `[0, 0]` to keep the retry path+// covered without paying the backoff sleep. (An empty array would still work+// — and run faster still — but it would disable the retry loop entirely,+// which defeats the purpose of testing the retry behavior.)+export let TRANSIENT_RETRY_DELAYS_MS = [50, 100];+export function _setRetryDelaysForTest(delays) { TRANSIENT_RETRY_DELAYS_MS = delays; }++function isTransientFsError(err) {+ return !!err && (err.code === 'EAGAIN' || err.code === 'EDEADLK' || err.errno === -11);+}++/**+ * Run `fn()` (a thunk returning a Promise) with retry on transient iCloud+ * errors. Returns the resolved value on success; throws the original error on+ * the final failure so callers' existing `.catch()` handlers see the same+ * error shape as before. ENOENT and other non-transient errors bypass retry.+ */+async function withTransientRetry(fn) {+ for (let attempt = 0; ; attempt++) {+ let caught = null;+ const result = await fn().catch((err) => { caught = err; });+ if (!caught) return result;+ if (!isTransientFsError(caught) || attempt >= TRANSIENT_RETRY_DELAYS_MS.length) {+ throw caught;+ }+ await new Promise((r) => setTimeout(r, TRANSIENT_RETRY_DELAYS_MS[attempt]));+ }+}+const APP_STORE_ID = '6760883701';export const MORTALLOOM_APP_STORE_URL = `https://apps.apple.com/app/id${APP_STORE_ID}`;@@ -33,11 +78,138 @@ const ARRAY_KEYS = [export function defaultStorePath() { return DEFAULT_ICLOUD_PATH; }+// === Eviction pinning ===++// macOS Optimize-Mac-Storage can evict iCloud files. When that happens the+// path still appears to exist (placeholder), but `readFile` returns EAGAIN+// because the read triggers an async download that doesn't return inline.+// `brctl download <path>` is the documented verb to materialize the file+// now. It does NOT set a persistent retention flag against future eviction+// (that requires Finder's "Keep Downloaded" or undocumented `brctl unevict`),+// so re-eviction under future disk pressure is still possible — the retry-+// on-EAGAIN path handles that case. Best-effort, fire-and-forget; on+// non-macOS we never spawn brctl, and on macOS when brctl is unexpectedly+// missing (sandboxed env, removed binary) we warn ONCE and then fall+// through to the retry path silently — without the dedupe, every+// settings:updated would re-warn.++let lastPinnedPath = null;+let brctlMissingWarned = false;++function pinAgainstEviction(path) {+ if (process.platform !== 'darwin') return;+ if (!path || lastPinnedPath === path) return;+ lastPinnedPath = path;++ // detached + unref so a long-running `brctl download` (large evicted file,+ // slow network) can't keep the Node process alive on shutdown. Matches the+ // repo's fire-and-forget spawn pattern in server/routes/apps.js ++ // server/routes/brain.js.+ const child = spawn('brctl', ['download', path], { detached: true, stdio: 'ignore' });+ child.unref();+ // Capture `path` in each handler so a late-arriving error/exit from a stale+ // child (one whose path has since been replaced by a newer pinAgainstEviction+ // call) doesn't clear the dedupe cache for the *current* path. Without this+ // capture, the stale exit would null out lastPinnedPath even though the new+ // path's child is still in flight (or has already succeeded), defeating+ // dedupe and causing repeated spawns on subsequent settings:updated events.+ child.on('error', (err) => {+ if (lastPinnedPath === path) lastPinnedPath = null;+ if (err.code === 'ENOENT') {+ // brctl isn't in PATH. On darwin this is extremely unusual; surface it+ // once so operators in a sandbox aren't left wondering why pinning is+ // a silent no-op, then dedupe so we don't spam on every settings change.+ if (!brctlMissingWarned) {+ brctlMissingWarned = true;+ console.warn('⚠️ brctl not found on PATH; MortalLoom store pinning disabled (retry-on-EAGAIN path remains)');+ }+ return;+ }+ console.warn(`⚠️ brctl download failed for MortalLoom store: ${err.message}`);+ });+ child.on('exit', (code, signal) => {+ if (code === 0) {+ console.log(`📥 MortalLoom store pinned for download: ${path}`);+ return;+ }+ // Non-zero exit OR signal-kill (code===null,signal set). Either way the+ // pin didn't complete, so clear the dedupe cache to allow a retry on the+ // next settings:updated event. Without this, a SIGTERM'd brctl would+ // permanently mask its own retry. Guard with the captured `path` so a+ // stale child can't clear cache for a path that has already moved on.+ if (lastPinnedPath === path) lastPinnedPath = null;+ if (code !== null) {+ console.warn(`⚠️ brctl download exited ${code} for MortalLoom store: ${path}`);+ } else {+ console.warn(`⚠️ brctl download killed by ${signal} for MortalLoom store: ${path}`);+ }+ });+}++// Two flags, not one: the listener is durable (sync, idempotent) but the+// initial-pin step does awaits that can reject transiently (settings.json+// read failure). Coupling them under a single `initialized = true` set+// BEFORE the await would mean a transient boot failure permanently disables+// the initial pin — even though the listener got attached and a retry would+// succeed. Splitting them lets a caller re-invoke initMortalLoomStore() to+// retry the initial pin without duplicating the listener.+let listenerAttached = false;+let didInitialPin = false;++export function _resetMortalLoomInitForTest() {+ listenerAttached = false;+ didInitialPin = false;+ lastPinnedPath = null;+ brctlMissingWarned = false;+}++/**+ * Boot hook: pin the configured MortalLoom store against iCloud eviction when+ * sync is enabled, and re-pin if the user later toggles sync on or changes the+ * path. Safe to call multiple times — the durable listener attaches at most+ * once, and the initial-pin step retries on subsequent calls if a prior call's+ * await rejected.+ */+export async function initMortalLoomStore() {+ // Attach the settings listener FIRST so even a transient failure in the+ // immediate-pin step below doesn't leave the system without+ // re-pin-on-settings-change. The listener has no async dependencies and is+ // the durable half of this hook.+ if (!listenerAttached) {+ settingsEvents.on('settings:updated', (settings) => {+ if (!settings?.mortalloom?.enabled) {+ // Disable clears the dedup cache so a future re-enable (even with the+ // same path) triggers another materialize attempt — otherwise toggling+ // off → on with an unchanged path would silently no-op.+ lastPinnedPath = null;+ return;+ }+ pinAgainstEviction(normalizePath(settings.mortalloom.path));+ });+ listenerAttached = true;+ }++ if (didInitialPin) return;++ // The await below can throw under transient disk pressure on settings.json.+ // Only flip didInitialPin after it succeeds so a caller can retry the+ // boot pin on a subsequent invocation without re-attaching the listener.+ // Read settings ONCE and derive both enabled+path from the same snapshot —+ // a prior split into isMortalLoomEnabled() + resolvePath() did two reads+ // and could half-fail (first succeeds, second hits a transient and skips+ // the boot pin even though sync was confirmed enabled).+ const s = await getSettings();+ if (s?.mortalloom?.enabled) {+ pinAgainstEviction(normalizePath(s.mortalloom.path));+ }+ didInitialPin = true;+}+// === Core I/O ===async function resolvePath() {const s = await getSettings();- return s?.mortalloom?.path?.trim() || DEFAULT_ICLOUD_PATH;+ return normalizePath(s?.mortalloom?.path);}export async function isMortalLoomEnabled() {@@ -64,14 +236,14 @@ export async function isMortalLoomEnabled() {*/async function readStoreAtPath(path) {if (!existsSync(path)) return null;- const raw = await readFile(path, 'utf-8').catch((err) => {+ const raw = await withTransientRetry(() => readFile(path, 'utf-8')).catch((err) => {// existsSync→readFile race: file disappeared between the two calls.// Treat as "absent" silently — no warning noise.if (err.code === 'ENOENT') return null;console.warn(`⚠️ MortalLoom store unavailable (${err.code || err.errno || 'unknown'}): ${path}`);return null;});- if (raw === null) return null;+ if (raw === null || raw === undefined) return null;const parsed = safeJSONParse(raw, null, { context: path });return isPlainObject(parsed) ? parsed : null;}@@ -81,7 +253,7 @@ export async function readStore() {}async function writeStoreAtPath(path, data) {- await writeFile(path, JSON.stringify(data, null, 2));+ await withTransientRetry(() => writeFile(path, JSON.stringify(data, null, 2)));}/** Atomic read → mutate → write. Ensures all array keys are initialized. */@@ -266,7 +438,7 @@ export async function readDailyLogIfEnabled() {export async function getStatus() {const s = await getSettings();- const path = s?.mortalloom?.path?.trim() || DEFAULT_ICLOUD_PATH;+ const path = normalizePath(s?.mortalloom?.path);const enabled = Boolean(s?.mortalloom?.enabled);const missingResponse = {enabled, path, usingDefault: path === DEFAULT_ICLOUD_PATH, defaultPath: DEFAULT_ICLOUD_PATH,@@ -278,7 +450,7 @@ export async function getStatus() {// disappeared between existsSync and stat/readFile) collapses back to the// "missing" response; only genuinely transient errors keep `exists:true`.let statTransient = false;- const st = await stat(path).catch((err) => {+ const st = await withTransientRetry(() => stat(path)).catch((err) => {if (err.code === 'ENOENT') return null;statTransient = true;console.warn(`⚠️ MortalLoom status stat unavailable (${err.code || err.errno || 'unknown'}): ${path}`);@@ -286,7 +458,7 @@ export async function getStatus() {});if (!st && !statTransient) return missingResponse;let readEnoent = false;- const raw = st ? await readFile(path, 'utf-8').catch((err) => {+ const raw = st ? await withTransientRetry(() => readFile(path, 'utf-8')).catch((err) => {if (err.code === 'ENOENT') { readEnoent = true; return null; }console.warn(`⚠️ MortalLoom status read unavailable (${err.code || err.errno || 'unknown'}): ${path}`);return null;diff --git a/server/services/mortalLoomStore.test.js b/server/services/mortalLoomStore.test.jsindex 804f630062..f80677808b 100644--- a/server/services/mortalLoomStore.test.js+++ b/server/services/mortalLoomStore.test.js@@ -1,4 +1,5 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, vi, beforeAll, afterAll, beforeEach, afterEach } from 'vitest';+import { EventEmitter } from 'events';let existsResult = true;// Queue of return values for sequential existsSync() calls. When empty, falls@@ -8,6 +9,7 @@ const existsQueue = [];const readFileMock = vi.fn();const statMock = vi.fn();const writeFileMock = vi.fn();+const spawnMock = vi.fn();vi.mock('fs', () => ({existsSync: vi.fn(() => (existsQueue.length ? existsQueue.shift() : existsResult)),@@ -19,9 +21,15 @@ vi.mock('fs/promises', () => ({stat: (...args) => statMock(...args),}));+vi.mock('child_process', () => ({+ spawn: (...args) => spawnMock(...args),+}));+let settings = { mortalloom: { enabled: true } };+const settingsEvents = new EventEmitter();vi.mock('./settings.js', () => ({getSettings: vi.fn(async () => settings),+ settingsEvents,}));vi.mock('../lib/fileUtils.js', () => ({@@ -39,6 +47,14 @@ vi.mock('../lib/objects.js', () => ({}));const store = await import('./mortalLoomStore.js');+// Tests must not pay the 50ms+100ms retry backoff on every transient-error+// case. Zero delays keep the suite fast while still exercising the retry path.+// Set up + restore the original through beforeAll/afterAll so the mutation+// can't leak into other test files that import mortalLoomStore.js in the same+// Vitest worker (when isolation is disabled).+const ORIGINAL_RETRY_DELAYS = store.TRANSIENT_RETRY_DELAYS_MS;+beforeAll(() => store._setRetryDelaysForTest([0, 0]));+afterAll(() => store._setRetryDelaysForTest(ORIGINAL_RETRY_DELAYS));beforeEach(() => {existsResult = true;@@ -46,9 +62,11 @@ beforeEach(() => {readFileMock.mockReset();statMock.mockReset();writeFileMock.mockReset();+ spawnMock.mockReset();settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };vi.spyOn(console, 'warn').mockImplementation(() => {});vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.spyOn(console, 'log').mockImplementation(() => {});});afterEach(() => {@@ -302,3 +320,319 @@ describe('getStatus', () => {expect(status.summary.hasProfile).toBe(true);});});++describe('readStore — EAGAIN retry', () => {+ it('retries on transient EAGAIN and succeeds when a later attempt resolves', async () => {+ // First attempt: EAGAIN (iCloud coordination lock). Second attempt: success.+ // Without retry, the dashboard's proactive-alerts poll would surface stale+ // data + a warning every 2 minutes when iCloud is mid-coordination.+ const transient = Object.assign(new Error('EAGAIN'), { code: 'EAGAIN', errno: -11 });+ readFileMock.mockRejectedValueOnce(transient);+ readFileMock.mockResolvedValueOnce(JSON.stringify({ goals: [{ id: 'recovered' }] }));++ const result = await store.readStore();++ expect(result).toEqual({ goals: [{ id: 'recovered' }] });+ expect(readFileMock).toHaveBeenCalledTimes(2);+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('does not retry on ENOENT — file-not-found is not a transient', async () => {+ const enoent = Object.assign(new Error('ENOENT'), { code: 'ENOENT' });+ readFileMock.mockRejectedValueOnce(enoent);++ const result = await store.readStore();++ expect(result).toBeNull();+ expect(readFileMock).toHaveBeenCalledTimes(1);+ expect(console.warn).not.toHaveBeenCalled();+ });++ it('exhausts retries on persistent EAGAIN (3 attempts total) and warns once', async () => {+ const transient = Object.assign(new Error('EAGAIN'), { code: 'EAGAIN', errno: -11 });+ readFileMock.mockRejectedValue(transient);++ const result = await store.readStore();++ expect(result).toBeNull();+ expect(readFileMock).toHaveBeenCalledTimes(3);+ expect(console.warn).toHaveBeenCalledTimes(1);+ });+});++describe('initMortalLoomStore — brctl pinning', () => {+ const makeFakeChild = () => {+ const handlers = {};+ const child = {+ on: vi.fn(function (evt, cb) { handlers[evt] = cb; return child; }),+ unref: vi.fn(),+ _emit: (evt, ...args) => handlers[evt]?.(...args),+ };+ return child;+ };++ // process.platform overrides aren't restored by vi.restoreAllMocks(). Capture+ // the original property descriptor before each test and restore it in+ // afterEach so an assertion failure can't leak the mutated platform into+ // unrelated test files (mirrors the updateExecutor.test.js pattern).+ let originalPlatformDescriptor;+ beforeEach(() => {+ settingsEvents.removeAllListeners('settings:updated');+ store._resetMortalLoomInitForTest();+ originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');+ });+ afterEach(() => {+ if (originalPlatformDescriptor) {+ Object.defineProperty(process, 'platform', originalPlatformDescriptor);+ }+ });++ it('spawns brctl download when sync is enabled (darwin only)', async () => {+ // Force darwin so the platform guard doesn't short-circuit the test.+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };++ await store.initMortalLoomStore();++ // Spawn options must include detached:true so the child doesn't keep the+ // Node process alive on shutdown; unref() is the matching half of the+ // pattern. Without both, a slow brctl download blocks process exit.+ expect(spawnMock).toHaveBeenCalledWith(+ 'brctl',+ ['download', '/icloud/MortalLoom.json'],+ expect.objectContaining({ detached: true, stdio: 'ignore' })+ );+ expect(child.unref).toHaveBeenCalledTimes(1);+ });++ it('re-pins when settings:updated flips enabled on with a new path', async () => {+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ spawnMock.mockReturnValue(makeFakeChild());+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ await store.initMortalLoomStore();+ const initialCalls = spawnMock.mock.calls.length;++ // Same path: deduped, no new spawn.+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ expect(spawnMock.mock.calls.length).toBe(initialCalls);++ // New path: re-pins.+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/other/MortalLoom.json' } });+ expect(spawnMock).toHaveBeenLastCalledWith('brctl', ['download', '/icloud/other/MortalLoom.json'], expect.any(Object));+ });++ it('no-ops on non-darwin platforms (init pin AND settings-change re-pin both guarded)', async () => {+ // Earlier this test only emitted settings:updated without calling+ // initMortalLoomStore(), so the listener was never attached and the+ // assertion passed for the wrong reason. Fix: call init() so the listener+ // IS attached and the platform guard inside pinAgainstEviction is the+ // thing under test on both the immediate-pin and the event-driven path.+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });++ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ await store.initMortalLoomStore();+ expect(spawnMock).not.toHaveBeenCalled();++ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ expect(spawnMock).not.toHaveBeenCalled();+ });++ it('attaches the settings:updated listener even when getSettings throws during init', async () => {+ // Regression: if isMortalLoomEnabled() rejects (transient settings.json+ // read failure at boot), the listener must STILL be attached so a later+ // settings:updated event can re-pin. Earlier code set initialized=true+ // and ran the await BEFORE attaching the listener, so a throw left the+ // listener gone forever.+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ spawnMock.mockReturnValue(makeFakeChild());+ const { getSettings } = await import('./settings.js');+ getSettings.mockRejectedValueOnce(new Error('settings.json read failed'));++ await expect(store.initMortalLoomStore()).rejects.toThrow('settings.json read failed');+ expect(spawnMock).not.toHaveBeenCalled();++ // Listener was attached before the failing await, so a later event still+ // fires pinAgainstEviction.+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));+ });++ it('reads settings exactly once during init (no half-fail window)', async () => {+ // Regression: an earlier shape called isMortalLoomEnabled() and then+ // resolvePath() — each invoking getSettings() — so init read settings+ // twice. A transient failure on the second read could skip the boot+ // pin even though the first read confirmed sync enabled. Reading once+ // and deriving both fields collapses the partial-failure window.+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ spawnMock.mockReturnValue(makeFakeChild());+ const { getSettings } = await import('./settings.js');+ // Other tests in this file accumulate calls on the shared getSettings+ // mock — clear before asserting count to isolate this test's call pattern.+ getSettings.mockClear();+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };++ await store.initMortalLoomStore();++ expect(getSettings).toHaveBeenCalledTimes(1);+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));+ });++ it('retries the initial pin on a subsequent call when the first attempt threw', async () => {+ // Regression for the listenerAttached/didInitialPin split: if+ // isMortalLoomEnabled() rejects, didInitialPin must stay false so a+ // subsequent initMortalLoomStore() call can retry the pin. The listener+ // must NOT be re-attached (otherwise events fire twice).+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ spawnMock.mockReturnValue(makeFakeChild());+ const { getSettings } = await import('./settings.js');+ getSettings.mockRejectedValueOnce(new Error('settings.json read failed'));++ await expect(store.initMortalLoomStore()).rejects.toThrow('settings.json read failed');+ expect(spawnMock).not.toHaveBeenCalled();++ // Second call: getSettings recovers, initial pin proceeds.+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ await store.initMortalLoomStore();+ expect(spawnMock).toHaveBeenCalledTimes(1);+ expect(spawnMock).toHaveBeenCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));++ // Listener was attached on the first call, not the second — emitting once+ // must fire pinAgainstEviction once, not twice.+ spawnMock.mockClear();+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/other/MortalLoom.json' } });+ expect(spawnMock).toHaveBeenCalledTimes(1);+ });++ it('re-pins after a disable → re-enable cycle with the same path', async () => {+ // Without resetting the dedup cache on disable, toggling sync off then+ // back on (without changing the path) silently no-ops. Settings.json+ // listeners must clear `lastPinnedPath` on disable so a subsequent+ // enable with the same path materializes again.+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ spawnMock.mockReturnValue(makeFakeChild());+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ await store.initMortalLoomStore();+ expect(spawnMock).toHaveBeenCalledTimes(1);++ // User disables sync — no spawn, but the dedup cache must clear.+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: false, path: '/icloud/MortalLoom.json' } });+ expect(spawnMock).toHaveBeenCalledTimes(1);++ // Re-enable with the SAME path — should re-spawn brctl, not be deduped.+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ expect(spawnMock).toHaveBeenCalledTimes(2);+ expect(spawnMock).toHaveBeenLastCalledWith('brctl', ['download', '/icloud/MortalLoom.json'], expect.any(Object));+ });++ it('clears lastPinnedPath when brctl is signal-killed so a later event can retry', async () => {+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ const child = makeFakeChild();+ spawnMock.mockReturnValue(child);+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ await store.initMortalLoomStore();+ expect(spawnMock).toHaveBeenCalledTimes(1);++ // Simulate signal-kill: exit handler fires with code=null, signal='SIGTERM'.+ // Earlier code skipped the cache-clear in this branch, so the dedup cache+ // would stay poisoned and a subsequent settings:updated for the same path+ // would no-op forever.+ child._emit('exit', null, 'SIGTERM');+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } });+ expect(spawnMock).toHaveBeenCalledTimes(2);+ });++ it('warns once when brctl is missing, then dedupes on subsequent settings changes', async () => {+ // Regression: the brctl pin comment promised "we just log and rely on the+ // retry path" but the error handler silently swallowed ENOENT entirely.+ // Operators in a sandboxed darwin env had no signal that pinning was a+ // no-op. Now we surface ENOENT once per process, then dedupe via+ // brctlMissingWarned so settings churn doesn't spam the same warning.+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ const child1 = makeFakeChild();+ const child2 = makeFakeChild();+ spawnMock.mockReturnValueOnce(child1).mockReturnValueOnce(child2);+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ await store.initMortalLoomStore();++ // First brctl process fires error with ENOENT.+ child1._emit('error', Object.assign(new Error('not found'), { code: 'ENOENT' }));+ expect(console.warn).toHaveBeenCalledTimes(1);+ expect(console.warn).toHaveBeenLastCalledWith(+ expect.stringContaining('brctl not found on PATH')+ );++ // Re-emit settings:updated with a DIFFERENT path so dedupe doesn't gate.+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/other.json' } });+ child2._emit('error', Object.assign(new Error('not found'), { code: 'ENOENT' }));+ // No second warning — the missing-binary dedupe held.+ expect(console.warn).toHaveBeenCalledTimes(1);+ });++ it('stale-child error does not clear the cache for the current path', async () => {+ // Regression: error/exit handlers previously cleared lastPinnedPath+ // unconditionally. If a newer pinAgainstEviction() had already spawned a+ // second child for a different path, the older child's error would null+ // the cache for the *current* path, defeating dedupe and causing a+ // spurious re-spawn on the next settings:updated for the same current+ // path. Capturing `path` in the closure and comparing before clearing+ // confines each handler's cache invalidation to its own path.+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ const child1 = makeFakeChild();+ const child2 = makeFakeChild();+ spawnMock.mockReturnValueOnce(child1).mockReturnValueOnce(child2);+ settings = { mortalloom: { enabled: true, path: '/icloud/A.json' } };+ await store.initMortalLoomStore();+ expect(spawnMock).toHaveBeenCalledTimes(1);++ // Newer pin for path B kicks off (e.g. user changed path before A's+ // child finished). Cache now points to B, child2 is in flight.+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/B.json' } });+ expect(spawnMock).toHaveBeenCalledTimes(2);++ // Stale child1 finally errors. Must NOT clear the B cache.+ child1._emit('error', Object.assign(new Error('boom'), { code: 'EAGAIN' }));++ // Re-emit settings:updated for B — dedupe should still hold (no spawn).+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: '/icloud/B.json' } });+ expect(spawnMock).toHaveBeenCalledTimes(2);+ });++ it('tolerates non-string path in settings without throwing in the listener', async () => {+ // Regression: settings.json is shallow-merged and not schema-validated, so+ // mortalloom.path can land as a number / array / object. Calling .trim()+ // on a non-string throws — and an unhandled throw inside the EventEmitter+ // listener can crash the process. Listener must normalize via type-check.+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });++ spawnMock.mockReturnValue(makeFakeChild());+ settings = { mortalloom: { enabled: true, path: '/icloud/MortalLoom.json' } };+ await store.initMortalLoomStore();+ spawnMock.mockClear();++ // Each non-string shape must be tolerated and fall back to the default+ // path rather than throwing.+ expect(() => {+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: 42 } });+ }).not.toThrow();+ expect(() => {+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: ['x'] } });+ }).not.toThrow();+ expect(() => {+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: { wrapped: '/x' } } });+ }).not.toThrow();+ expect(() => {+ settingsEvents.emit('settings:updated', { mortalloom: { enabled: true, path: null } });+ }).not.toThrow();+ });+});