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: retain legacy recovery files on directory errors (#7166)
[._.]/ Adam Eivy1d59d49c5bcb
diff --git a/server/scripts/pruneImportedLegacyFiles.js b/server/scripts/pruneImportedLegacyFiles.jsindex bc95a3c3b2..21f820a6d5 100644--- a/server/scripts/pruneImportedLegacyFiles.js+++ b/server/scripts/pruneImportedLegacyFiles.js@@ -90,6 +90,28 @@ const MARKER_FILENAME = 'legacy-prune.applied.json';// absent file, which legitimately yields no ids.)class ParkedArtifactUnreadable extends Error {}+// Directory and stat probes participate in the same fail-closed contract as+// parked JSON reads. ENOENT is the only result that proves an artifact is+// absent; every other filesystem error leaves its domain unverifiable.+async function readParkedDir(base, dir) {+ try {+ return await readdir(join(base, dir), { withFileTypes: true });+ } catch (err) {+ if (err.code === 'ENOENT') return [];+ throw new ParkedArtifactUnreadable(`${dir}: ${err.message}`);+ }+}++async function parkedPathExists(base, rel) {+ try {+ await stat(join(base, rel));+ return true;+ } catch (err) {+ if (err.code === 'ENOENT') return false;+ throw new ParkedArtifactUnreadable(`${rel}: ${err.message}`);+ }+}+// Read a parked JSON artifact. Returns null when ABSENT; throws// ParkedArtifactUnreadable when present-but-unreadable/unparseable — so a// corrupt recovery file blocks its domain instead of being mistaken for empty.@@ -118,12 +140,12 @@ async function readParkedJson(base, file) {// `leaf` defaults to the live record file; pass `index.json.imported` for the// in-place rename layout (pipeline-series) and a missing leaf is skipped there.async function idsFromRecordDirs(base, dir, { leaf = 'index.json', requireLeaf = false } = {}) {- const entries = await readdir(join(base, dir), { withFileTypes: true }).catch(() => []);+ const entries = await readParkedDir(base, dir);const ids = [];for (const entry of entries) {if (!entry.isDirectory() || entry.name === 'index.json' || entry.name.startsWith('.')) continue;const rel = join(dir, entry.name, leaf);- if (requireLeaf && !await pathExists(join(base, rel))) continue; // unrelated sibling dir+ if (requireLeaf && !await parkedPathExists(base, rel)) continue; // unrelated sibling dirconst record = await readParkedJson(base, rel);if (record === null) {if (requireLeaf) continue; // leaf vanished between listing and read — skip@@ -175,7 +197,7 @@ async function universeRunIds(base) {// A present-but-corrupt manifest, or one with an id-less work / draft, throws.async function writersRoomManifestIds(base) {const worksDir = 'writers-room/works';- const subdirs = await readdir(join(base, worksDir), { withFileTypes: true }).catch(() => []);+ const subdirs = await readParkedDir(base, worksDir);const workIds = [];const draftIds = [];for (const entry of subdirs) {@@ -206,21 +228,20 @@ async function writersRoomManifestIds(base) {// (pipeline-series/writers-room) keep their dir, so we look for the specific// un-renamed legacy file.async function pipelineSeriesPending(base) {- const entries = await readdir(join(base, 'pipeline-series'), { withFileTypes: true }).catch(() => []);+ const entries = await readParkedDir(base, 'pipeline-series');for (const e of entries) {if (!e.isDirectory()) continue;- const live = join(base, 'pipeline-series', e.name, 'index.json');- const parked = join(base, 'pipeline-series', e.name, 'index.json.imported');- if (await pathExists(live) && !await pathExists(parked)) return true;+ if (await parkedPathExists(base, join('pipeline-series', e.name, 'index.json')) &&+ !await parkedPathExists(base, join('pipeline-series', e.name, 'index.json.imported'))) return true;}return false;}async function writersRoomPending(base) {- if (await pathExists(join(base, 'writers-room/folders.json'))) return true;- if (await pathExists(join(base, 'writers-room/exercises.json'))) return true;- const works = await readdir(join(base, 'writers-room/works'), { withFileTypes: true }).catch(() => []);+ if (await parkedPathExists(base, 'writers-room/folders.json')) return true;+ if (await parkedPathExists(base, 'writers-room/exercises.json')) return true;+ const works = await readParkedDir(base, 'writers-room/works');for (const e of works) {- if (e.isDirectory() && await pathExists(join(base, 'writers-room/works', e.name, 'manifest.json'))) return true;+ if (e.isDirectory() && await parkedPathExists(base, join('writers-room/works', e.name, 'manifest.json'))) return true;}return false;}@@ -241,7 +262,7 @@ const DB_DOMAINS = [{ table: 'universes', ids: await idsFromRecordDirs(base, 'universes.imported') },{ table: 'universe_runs', ids: await universeRunIds(base) },],- pending: (base) => pathExists(join(base, 'universes')),+ pending: (base) => parkedPathExists(base, 'universes'),artifacts: ['universes.imported'],},{@@ -250,7 +271,7 @@ const DB_DOMAINS = [verify: async (base) => [{ table: 'pipeline_issues', ids: await idsFromRecordDirs(base, 'pipeline-issues.imported') },],- pending: (base) => pathExists(join(base, 'pipeline-issues')),+ pending: (base) => parkedPathExists(base, 'pipeline-issues'),artifacts: ['pipeline-issues.imported'],},{@@ -272,7 +293,7 @@ const DB_DOMAINS = [verify: async (base) => [{ table: 'story_builder_sessions', ids: await idsFromRecordDirs(base, 'story-builder.imported') },],- pending: (base) => pathExists(join(base, 'story-builder')),+ pending: (base) => parkedPathExists(base, 'story-builder'),artifacts: ['story-builder.imported'],},{@@ -299,15 +320,11 @@ const DB_DOMAINS = [verify: async (base) => [{ table: 'creative_director_projects', ids: await idsFromJsonArray(base, 'creative-director-projects.json.imported') },],- pending: (base) => pathExists(join(base, 'creative-director-projects.json')),+ pending: (base) => parkedPathExists(base, 'creative-director-projects.json'),artifacts: ['creative-director-projects.json.imported'],},];-async function pathExists(p) {- return stat(p).then(() => true, () => false);-}-async function readJson(base, file) {const raw = await tryReadFile(join(base, file));if (!raw) return null;@@ -323,24 +340,30 @@ async function missingIds(query, table, ids) {return ids.filter((id) => !present.has(id));}-// Remove a path (file or dir) under `base`. force:true → no throw if absent.-// Returns true if the path existed before removal (so we can report a count).-async function removeUnder(base, rel) {- const abs = join(base, rel);- const existed = await pathExists(abs);- if (existed) await rm(abs, { recursive: true, force: true });- return existed;+// Resolve every artifact a domain will remove before deleting any of them. This+// makes a nested-directory enumeration failure block the whole domain without+// partially pruning its top-level recovery files first.+async function collectDomainArtifacts(base, domain) {+ const artifacts = [];+ for (const rel of domain.artifacts) {+ if (await parkedPathExists(base, rel)) artifacts.push(rel);+ }+ for (const { baseDir, leaf } of (domain.nestedGlobs ?? [])) {+ const entries = await readParkedDir(base, baseDir);+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const rel = join(baseDir, entry.name, leaf);+ if (await parkedPathExists(base, rel)) artifacts.push(rel);+ }+ }+ return artifacts;}-// Remove `<baseDir>/<sub>/<leaf>` for every immediate subdir of baseDir.-async function removeNestedGlob(base, baseDir, leaf) {- const entries = await readdir(join(base, baseDir), { withFileTypes: true }).catch(() => []);- let removed = 0;- for (const entry of entries) {- if (!entry.isDirectory()) continue;- if (await removeUnder(base, join(baseDir, entry.name, leaf))) removed++;+async function removeDomainArtifacts(base, artifacts) {+ for (const entry of artifacts) {+ await rm(join(base, entry), { recursive: true, force: true });}- return removed;+ return artifacts.length;}/**@@ -369,7 +392,16 @@ export async function pruneImportedLegacyFiles({ force = false, db, dataDir } =// blocked so the global completion marker is withheld; otherwise a later// boot (after the source is repaired and finally parked) would skip the// prune forever via the applied marker.- if (await domain.pending(base)) {+ let pending;+ try {+ pending = await domain.pending(base);+ } catch (err) {+ if (!(err instanceof ParkedArtifactUnreadable)) throw err;+ console.warn(`🧹 legacy-prune: ${domain.label} pending state unreadable (${err.message}); withholding completion so a later boot retries`);+ totals.blocked++;+ continue;+ }+ if (pending) {console.warn(`🧹 legacy-prune: ${domain.label} pending — no migration marker but legacy source still on disk; withholding completion so a later boot prunes it`);totals.blocked++;}@@ -405,13 +437,16 @@ export async function pruneImportedLegacyFiles({ force = false, db, dataDir } =continue;}- let domainRemoved = 0;- for (const rel of domain.artifacts) {- if (await removeUnder(base, rel)) domainRemoved++;- }- for (const glob of (domain.nestedGlobs ?? [])) {- domainRemoved += await removeNestedGlob(base, glob.baseDir, glob.leaf);+ let artifacts;+ try {+ artifacts = await collectDomainArtifacts(base, domain);+ } catch (err) {+ if (!(err instanceof ParkedArtifactUnreadable)) throw err;+ console.warn(`🧹 legacy-prune: ${domain.label} cleanup blocked — recovery artifact enumeration failed (${err.message}); keeping recovery files`);+ totals.blocked++;+ continue;}+ const domainRemoved = await removeDomainArtifacts(base, artifacts);if (domainRemoved > 0) {totals.removed += domainRemoved;totals.pruned.push(`${domain.label}(${domainRemoved})`);diff --git a/server/scripts/pruneImportedLegacyFiles.test.js b/server/scripts/pruneImportedLegacyFiles.test.jsindex db8a485c62..5132ca3d40 100644--- a/server/scripts/pruneImportedLegacyFiles.test.js+++ b/server/scripts/pruneImportedLegacyFiles.test.js@@ -14,16 +14,46 @@* blocked pass withholds the marker; a force-blocked run drops a stale one.*/-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import { mkdtemp, rm, mkdir, writeFile, stat } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';import { pruneImportedLegacyFiles } from './pruneImportedLegacyFiles.js';+const fsFaults = vi.hoisted(() => ({ readdir: new Map(), stat: new Map() }));++vi.mock('fs/promises', async (importOriginal) => {+ const actual = await importOriginal();+ const failIfScheduled = (operation, file) => {+ const fault = fsFaults[operation].get(String(file));+ if (!fault) return;+ if (fault.after > 0) {+ fault.after--;+ return;+ }+ fsFaults[operation].delete(String(file));+ throw Object.assign(new Error(`${operation} fault for test`), { code: fault.code });+ };+ return {+ ...actual,+ readdir: async (...args) => {+ failIfScheduled('readdir', args[0]);+ return actual.readdir(...args);+ },+ stat: async (...args) => {+ failIfScheduled('stat', args[0]);+ return actual.stat(...args);+ },+ };+});+let dataDir;const exists = (p) => stat(p).then(() => true, () => false);const writeJSON = (p, obj) => writeFile(p, JSON.stringify(obj), 'utf-8');+const failOnce = (operation, file, code, { after = 0 } = {}) => {+ fsFaults[operation].set(file, { code, after });+};// A db stub backed by a per-table set of present ids. Answers the prune's only// query shape: `SELECT id FROM <table> WHERE id = ANY($1)`.@@ -39,9 +69,13 @@ function stubDb(tables) {}beforeEach(async () => {+ fsFaults.readdir.clear();+ fsFaults.stat.clear();dataDir = await mkdtemp(join(tmpdir(), 'legacy-prune-'));});afterEach(async () => {+ fsFaults.readdir.clear();+ fsFaults.stat.clear();await rm(dataDir, { recursive: true, force: true });});@@ -176,6 +210,101 @@ describe('pruneImportedLegacyFiles', () => {expect(await exists(join(dataDir, 'story-builder.imported'))).toBe(false);});+ it('WITHHOLDS a parked domain when directory enumeration fails, then retries safely', async () => {+ await writeJSON(join(dataDir, 'story-builder.migrated.json'), { imported: 1 });+ const parked = join(dataDir, 'story-builder.imported');+ await mkdir(join(parked, 'session-1'), { recursive: true });+ await writeJSON(join(parked, 'session-1', 'index.json'), { id: 'session-1' });+ let queries = 0;+ const missingDb = stubDb({ story_builder_sessions: [] });+ const countingDb = { async query(...args) { queries++; return missingDb.query(...args); } };+ failOnce('readdir', parked, 'EIO');++ const unavailable = await pruneImportedLegacyFiles({ dataDir, db: countingDb });+ expect(unavailable.blocked).toBe(1);+ expect(unavailable.markerWritten).toBe(false);+ expect(queries).toBe(0);+ expect(await exists(parked)).toBe(true);++ const stillMissing = await pruneImportedLegacyFiles({ dataDir, db: missingDb });+ expect(stillMissing.blocked).toBe(1);+ expect(stillMissing.markerWritten).toBe(false);+ expect(await exists(parked)).toBe(true);++ const restored = await pruneImportedLegacyFiles({+ dataDir,+ db: stubDb({ story_builder_sessions: ['session-1'] }),+ });+ expect(restored.blocked).toBe(0);+ expect(restored.markerWritten).toBe(true);+ expect(await exists(parked)).toBe(false);+ });++ it('WITHHOLDS completion when pending-source directory discovery fails', async () => {+ const seriesDir = join(dataDir, 'pipeline-series');+ await mkdir(join(seriesDir, 'series-1'), { recursive: true });+ await writeJSON(join(seriesDir, 'series-1', 'index.json'), { id: 'series-1' });+ failOnce('readdir', seriesDir, 'EACCES');++ const result = await pruneImportedLegacyFiles({ dataDir, db: stubDb({}) });++ expect(result.blocked).toBe(1);+ expect(result.markerWritten).toBe(false);+ expect(await exists(join(dataDir, 'legacy-prune.applied.json'))).toBe(false);+ expect(await exists(join(seriesDir, 'series-1', 'index.json'))).toBe(true);+ });++ it('WITHHOLDS nested cleanup when its directory enumeration fails before deletion', async () => {+ await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 1, works: 1, exercises: 1 });+ const writersRoom = join(dataDir, 'writers-room');+ const worksDir = join(writersRoom, 'works');+ const workDir = join(worksDir, 'work-1');+ const artifacts = [+ join(writersRoom, 'folders.imported.json'),+ join(writersRoom, 'exercises.imported.json'),+ join(workDir, 'manifest.imported.json'),+ ];+ await mkdir(workDir, { recursive: true });+ await writeJSON(artifacts[0], [{ id: 'folder-1' }]);+ await writeJSON(artifacts[1], [{ id: 'exercise-1' }]);+ await writeJSON(artifacts[2], { id: 'work-1', drafts: [] });+ failOnce('readdir', worksDir, 'EIO', { after: 1 });++ const db = stubDb({+ writers_room_folders: ['folder-1'],+ writers_room_exercises: ['exercise-1'],+ writers_room_works: ['work-1'],+ writers_room_draft_versions: [],+ });++ const unavailable = await pruneImportedLegacyFiles({ dataDir, db });+ expect(unavailable.blocked).toBe(1);+ expect(unavailable.markerWritten).toBe(false);+ for (const artifact of artifacts) expect(await exists(artifact)).toBe(true);++ const recovered = await pruneImportedLegacyFiles({ dataDir, db });+ expect(recovered.markerWritten).toBe(true);+ for (const artifact of artifacts) expect(await exists(artifact)).toBe(false);+ });++ it('WITHHOLDS verification when a parked-artifact stat fails', async () => {+ await writeJSON(join(dataDir, 'pipeline-series.migrated.json'), { imported: 1 });+ const seriesDir = join(dataDir, 'pipeline-series');+ const parked = join(seriesDir, 'series-1', 'index.json.imported');+ await mkdir(join(seriesDir, 'series-1'), { recursive: true });+ await writeJSON(parked, { id: 'series-1' });+ failOnce('stat', parked, 'EACCES');++ const result = await pruneImportedLegacyFiles({+ dataDir,+ db: stubDb({ pipeline_series: ['series-1'] }),+ });++ expect(result.blocked).toBe(1);+ expect(result.markerWritten).toBe(false);+ expect(await exists(parked)).toBe(true);+ });+it('skips a domain with no migration marker (never parked anything)', async () => {const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({}) });expect(res.blocked).toBe(0);