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: address review (claude) sync resilience
[._.]/ Adam Eivyfb9f5521df30
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 964460af1f..3e177dfa2c 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -61,7 +61,8 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).-- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No sync cursor, no tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.+- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.+- Spotify brain playlist shelf — `data/spotify/playlists.json`. `file-primary`, intentionally machine-local and never federated: it is a bounded cache of Spotify playlist and track metadata used as local reference material, while listening evidence remains in the federated Brain activity record. No sync cursor or tombstone. Adapter: `server/services/spotifyPlaylists.js`.- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.diff --git a/server/services/spotifyPlaylists.js b/server/services/spotifyPlaylists.jsindex 8774cbc8f9..0503f90057 100644--- a/server/services/spotifyPlaylists.js+++ b/server/services/spotifyPlaylists.js@@ -15,6 +15,7 @@ const REQUEST_TIMEOUT_MS = 15000;const PAGE_LIMIT = 50;const PLAYLIST_BATCH_SIZE = 5;const MAX_RATE_LIMIT_RETRIES = 2;+const MAX_RATE_LIMIT_WAIT_MS = 10000;const PLAYLISTS_FILE = dataPath('spotify', 'playlists.json');const SNAPSHOT_VERSION = 1;@@ -86,7 +87,9 @@ async function fetchJson(url, accessToken) {}, REQUEST_TIMEOUT_MS);if (!response.ok && response.status === 429 && attempt < MAX_RATE_LIMIT_RETRIES) {const retryAfter = Number(response.headers?.get?.('retry-after'));- await sleep(Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter * 1000 : 1000);+ const waitMs = Number.isFinite(retryAfter) && retryAfter >= 0 ? retryAfter * 1000 : 1000;+ if (waitMs > MAX_RATE_LIMIT_WAIT_MS) throw new Error(`Spotify rate limited; retry after ${retryAfter}s`);+ await sleep(waitMs);continue;}const payload = await response.json().catch(() => ({}));@@ -150,6 +153,16 @@ async function doSyncSpotifyPlaylists() {return { ok: false, error: error.message };}const playlistSummaries = playlistResult.value.filter((playlist) => playlist?.id && playlist?.name);+ if (!playlistSummaries.length && previous?.playlists?.length) {+ return {+ ok: false,+ status: 'list-empty',+ error: 'No playlists returned — keeping the previous snapshot.',+ ...playlistSnapshotSummary(previous),+ scanned: 0,+ failed: 0,+ };+ }const results = [];for (let index = 0; index < playlistSummaries.length; index += PLAYLIST_BATCH_SIZE) {diff --git a/server/services/spotifyPlaylists.test.js b/server/services/spotifyPlaylists.test.jsindex 22177b055d..a644503ce2 100644--- a/server/services/spotifyPlaylists.test.js+++ b/server/services/spotifyPlaylists.test.js@@ -117,4 +117,26 @@ describe('syncSpotifyPlaylists', () => {expect(mocks.fetchWithTimeout).toHaveBeenCalledTimes(3);expect(mocks.sleep).toHaveBeenCalledWith(0);});++ it('keeps the prior library when Spotify returns an empty playlist list', async () => {+ mocks.readJSONFile.mockResolvedValue({ playlists: [normalizeSpotifyPlaylist(playlist)] });+ mocks.fetchWithTimeout.mockReset().mockResolvedValueOnce({ ok: true, json: async () => ({ total: 1, items: [] }) });++ const result = await syncSpotifyPlaylists();++ expect(result).toMatchObject({ ok: false, status: 'list-empty', playlistCount: 1, scanned: 0 });+ expect(mocks.atomicWrite).not.toHaveBeenCalled();+ });++ it('stops instead of sleeping past the rate-limit wait bound', async () => {+ mocks.fetchWithTimeout+ .mockReset()+ .mockResolvedValueOnce({ ok: true, json: async () => ({ total: 1, items: [playlist] }) })+ .mockResolvedValueOnce({ ok: false, status: 429, headers: { get: () => '11' }, json: async () => ({}) });++ const result = await syncSpotifyPlaylists();++ expect(result).toMatchObject({ ok: false, playlistCount: 0, failed: 1 });+ expect(mocks.sleep).not.toHaveBeenCalled();+ });});diff --git a/server/services/youtubePlaylists.js b/server/services/youtubePlaylists.jsindex b2aba0a9e4..61433a3ad9 100644--- a/server/services/youtubePlaylists.js+++ b/server/services/youtubePlaylists.js@@ -188,16 +188,26 @@ async function doSyncYoutubePlaylists() {};}const deadline = Date.now() + MAX_SYNC_MS;- for (let index = 0; index < sourcePlaylists.length; index += 1) {- const rawPlaylist = sourcePlaylists[index];+ const cursorIndex = previous?.nextPlaylistId+ ? sourcePlaylists.findIndex((playlist) => playlist.id === previous.nextPlaylistId)+ : -1;+ const orderedPlaylists = cursorIndex > 0+ ? [...sourcePlaylists.slice(cursorIndex), ...sourcePlaylists.slice(0, cursorIndex)]+ : sourcePlaylists;+ let nextPlaylistId = null;+ let scanned = 0;+ for (let index = 0; index < orderedPlaylists.length; index += 1) {+ const rawPlaylist = orderedPlaylists[index];if (Date.now() >= deadline) {+ nextPlaylistId = rawPlaylist.id;warnings.push(`Sync stopped after ${Math.round(MAX_SYNC_MS / 60000)} minutes; remaining playlists were not refreshed`);- sourcePlaylists.slice(index).forEach((remaining) => {+ orderedPlaylists.slice(index).forEach((remaining) => {const stale = previous?.playlists?.find((playlist) => playlist.id === remaining.id);- if (stale) playlists.push(stale);+ playlists.push(stale || normalizeYoutubePlaylist(remaining, []));});break;}+ scanned += 1;// Do not use the evaluate result as the navigation verdict: CDP can report// a context error while the requested navigation is already in progress.await evaluateOnPage(loaded.page, `location.assign(${JSON.stringify(`${PLAYLIST_URL}${encodeURIComponent(rawPlaylist.id)}`)}); true`).catch(() => null);@@ -238,6 +248,7 @@ async function doSyncYoutubePlaylists() {syncedAt: new Date().toISOString(),playlists,warnings,+ ...(nextPlaylistId ? { nextPlaylistId } : {}),};await ensureDir(dataPath('youtube'));await atomicWrite(PLAYLISTS_FILE, snapshot);@@ -246,7 +257,7 @@ async function doSyncYoutubePlaylists() {const result = {ok: warnings.length === 0,...summary,- scanned: sourcePlaylists.length,+ scanned,failed: warnings.length,...(warnings.length ? { warnings } : {}),};diff --git a/server/services/youtubePlaylists.test.js b/server/services/youtubePlaylists.test.jsindex a2b4886bed..eb6351e24a 100644--- a/server/services/youtubePlaylists.test.js+++ b/server/services/youtubePlaylists.test.js@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({findOrOpenPage: vi.fn(), listCdpPages: vi.fn(), isAuthPage: vi.fn(), evaluateOnPage: vi.fn(), readJSONFile: vi.fn(), ensureDir: vi.fn(), atomicWrite: vi.fn(),@@ -29,6 +29,8 @@ describe('YouTube playlist normalization', () => {});describe('syncYoutubePlaylists', () => {+ afterEach(() => vi.restoreAllMocks());+beforeEach(() => {vi.clearAllMocks();mocks.findOrOpenPage.mockResolvedValue({ id: 'page-1', url: 'https://www.youtube.com/feed/playlists' });@@ -126,4 +128,47 @@ describe('syncYoutubePlaylists', () => {expect(result.warnings).toEqual(['Example playlist: only read 1 of 90 video(s)']);expect(mocks.atomicWrite).toHaveBeenCalledWith('/tmp/youtube/playlists.json', expect.objectContaining({ playlists: [stale] }));});++ it('resumes a timed-out sync from the first unrefreshed playlist', async () => {+ const now = vi.spyOn(Date, 'now').mockReturnValueOnce(0).mockReturnValue(120000);+ const playlists = [+ { id: 'PL-first', name: 'First playlist', videoCount: 1 },+ { id: 'PL-second', name: 'Second playlist', videoCount: 2 },+ ];+ mocks.evaluateOnPage+ .mockReset()+ .mockResolvedValueOnce({ signedOut: false, playlists })+ .mockResolvedValueOnce(null);++ const result = await syncYoutubePlaylists();++ expect(result).toMatchObject({ ok: false, scanned: 0, playlistCount: 2, videoCount: 0 });+ expect(result.warnings).toEqual(['Sync stopped after 2 minutes; remaining playlists were not refreshed']);+ expect(mocks.atomicWrite).toHaveBeenCalledWith('/tmp/youtube/playlists.json', expect.objectContaining({+ nextPlaylistId: 'PL-first',+ playlists: [+ expect.objectContaining({ id: 'PL-first', videos: [] }),+ expect.objectContaining({ id: 'PL-second', videos: [] }),+ ],+ }));+ now.mockRestore();+ });++ it('starts the next sync at the persisted playlist cursor', async () => {+ mocks.readJSONFile.mockResolvedValue({ nextPlaylistId: 'PL-second', playlists: [] });+ mocks.evaluateOnPage+ .mockReset()+ .mockResolvedValueOnce({ signedOut: false, playlists: [+ { id: 'PL-first', name: 'First playlist' },+ { id: 'PL-second', name: 'Second playlist' },+ ] })+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce({ signedOut: false, videos: [] })+ .mockResolvedValueOnce(true)+ .mockResolvedValueOnce({ signedOut: false, videos: [] });++ await syncYoutubePlaylists();++ expect(mocks.evaluateOnPage.mock.calls[1][1]).toContain('PL-second');+ });});