Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: extract shared migrationMarker helpers using atomicWrite (#2525)

Adam Eivy17847ffd1e3a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 92139c4c51..3a9e1a2435 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,4 +17,5 @@
## Changed
- **[issue-2521] Validate the remaining ad-hoc route bodies with Zod `validateRequest`.** The ports (`/check`, `/allocate`), database (`switch`/`start`/`stop`/`destroy`/`export`), brain digest/review run, telegram (`method`/`config`/`test`/`forward-types`), and AI-toolkit provider (`POST`/`PUT`/`PUT active`) routes parsed `req.body` with hand-rolled `Array.isArray`/`includes` checks. Each now has a named Zod schema (PortOS schemas in `lib/validation.js`, brain schema in `brainValidation.js`, provider schemas in `aiToolkit/validation.js`) wired through `validateRequest`, so invalid bodies return a consistent `400 VALIDATION_ERROR` with per-field `context.details` instead of ad-hoc messages. Port numbers are range-checked (and `count` coercion no longer silently accepts booleans/arrays), backend/target values are enum-checked, and provider create/update reuse the canonical `providerSchema` (`.partial()` on update). As part of wiring `PUT /api/providers/active`, the toolkit providers map is now null-prototyped on load so a crafted id (`__proto__`, `constructor`, `toString`) can no longer resolve an inherited `Object.prototype` member as an existing provider and be persisted as the active one.
+- **[issue-2525] Extract shared `migrationMarker` helpers using `atomicWrite`.** Eleven boot-time migration/repair/reconcile scripts under `server/scripts/` each hand-rolled `markerExists`/`readMarker`/`writeMarker` on top of `readFile(...).catch(() => null)` and a non-atomic `writeFile(JSON.stringify(...))`, so a crash mid-write could leave a truncated marker a later boot misreads as "not applied." The three helpers now live once in `server/lib/migrationMarker.js` (anchored under `PATHS.data`, built on the existing `tryReadFile`/`atomicWrite`/`safeJSONParse`), are barrel- and README-cataloged, and carry their own unit test. Marker filenames, gate semantics, and payloads are unchanged; the write path is now atomic (temp file + rename).
- **[issue-2522] Deep-link Tribe tabs and fix form label associations.** The Tribe page's active section (Circle / Map / Care Queue / Focus) lived in local `useState`, so a section couldn't be shared, bookmarked, or survive a reload. It now reads from a `?tab=` URL search param (default `circle` omitted for a clean `/tribe`) with a valid-tab fallback for stale/unknown values — matching the PromptManager convention. Separately, the `StylePresetPicker` style-preset `<label>` and the Loops "Interval" `<label>` had no `htmlFor`/`id` pairing; both now associate with their control via a `useId()`-generated id so click-to-focus and screen readers work.
diff --git a/server/lib/README.md b/server/lib/README.md
index bb03a6c7bd..384796fec2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -220,6 +220,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
+| `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. |
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. Mirrored to `client/src/lib/`. |
| `textUtils.js` | Pure server-side prose helpers. `countWords(text)` — canonical whitespace-token count (`\S+`), the single home for what `writersRoom/local.js`, `issueLength.js`, and the client's `formatters.js` used to each re-implement. |
diff --git a/server/lib/index.js b/server/lib/index.js
index e97d27e6cd..17d82c5903 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -194,6 +194,7 @@ export * from './localModelHeuristics.js';
export * from './loraDataset.js';
export * from './issueLength.js';
export * from './mediaItemKey.js';
+export * from './migrationMarker.js';
export * from './modelPricing.js';
export * from './navManifest.js';
export * from './usageRange.js';
diff --git a/server/lib/migrationMarker.js b/server/lib/migrationMarker.js
new file mode 100644
index 0000000000..c1425879af
--- /dev/null
+++ b/server/lib/migrationMarker.js
@@ -0,0 +1,56 @@
+/**
+ * Shared marker-file helpers for one-time migration / repair / reconcile scripts.
+ *
+ * ~11 boot-time scripts under server/scripts/ gate their idempotent walk on a
+ * small JSON "applied" / "migrated" marker under data/. They used to hand-roll
+ * three near-identical helpers each — `markerExists` / `readMarker` /
+ * `writeMarker` — built on `readFile(...).catch(() => null)` and a non-atomic
+ * `writeFile(JSON.stringify(...))`. This module collapses those into the shared
+ * `tryReadFile` / `atomicWrite` primitives from fileUtils, so a crash mid-write
+ * can't leave a truncated marker that a later boot misreads as "not applied".
+ *
+ * All three operate on a marker filename relative to PATHS.data. Pass just the
+ * filename (e.g. 'universes.migrated.json'); the helper anchors it under data/.
+ */
+
+import { join } from 'path';
+import { PATHS, tryReadFile, atomicWrite, safeJSONParse } from './fileUtils.js';
+
+function markerPath(filename) {
+ return join(PATHS.data, filename);
+}
+
+/**
+ * True when the marker file is present (any readable content), else false.
+ * Mirrors the old `raw != null` boolean gate used by the migrate*ToDB scripts.
+ * @param {string} filename - Marker filename relative to data/.
+ * @returns {Promise<boolean>}
+ */
+export async function markerExists(filename) {
+ const raw = await tryReadFile(markerPath(filename));
+ return raw != null;
+}
+
+/**
+ * Parsed marker payload, or null when the file is missing / empty / not valid
+ * JSON. Mirrors the old `readMarker` (read → JSON.parse with a null fallback)
+ * used by the backfill / repair / reconcile scripts.
+ * @param {string} filename - Marker filename relative to data/.
+ * @returns {Promise<any|null>}
+ */
+export async function readMarker(filename) {
+ const raw = await tryReadFile(markerPath(filename));
+ if (raw == null) return null;
+ return safeJSONParse(raw, null);
+}
+
+/**
+ * Atomically write the marker payload as pretty-printed JSON. Uses fileUtils'
+ * `atomicWrite` (temp file + rename) so a crash can't leave a partial marker.
+ * @param {string} filename - Marker filename relative to data/.
+ * @param {object} payload - JSON-serializable marker contents.
+ * @returns {Promise<void>}
+ */
+export async function writeMarker(filename, payload) {
+ await atomicWrite(markerPath(filename), payload);
+}
diff --git a/server/lib/migrationMarker.test.js b/server/lib/migrationMarker.test.js
new file mode 100644
index 0000000000..948863b7f4
--- /dev/null
+++ b/server/lib/migrationMarker.test.js
@@ -0,0 +1,94 @@
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { makePathsProxy } from './mockPathsDataRoot.js';
+
+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'migration-marker-test-'));
+
+// Redirect PATHS.data at the temp dir; keep the real tryReadFile/atomicWrite/
+// safeJSONParse so the helpers do genuine on-disk I/O against the temp root.
+vi.mock('./fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, { dataRoot: TEST_DATA_ROOT });
+});
+
+const { markerExists, readMarker, writeMarker } = await import('./migrationMarker.js');
+
+afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));
+
+const markerFile = (name) => join(TEST_DATA_ROOT, name);
+
+describe('migrationMarker', () => {
+ beforeEach(() => {
+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });
+ mkdirSync(TEST_DATA_ROOT, { recursive: true });
+ });
+
+ describe('markerExists', () => {
+ it('returns false when the marker file is absent', async () => {
+ expect(await markerExists('absent.migrated.json')).toBe(false);
+ });
+
+ it('returns true when the marker file exists (even if empty)', async () => {
+ writeFileSync(markerFile('present.migrated.json'), '');
+ expect(await markerExists('present.migrated.json')).toBe(true);
+ });
+
+ it('returns true for a non-JSON marker (gate is presence, not validity)', async () => {
+ writeFileSync(markerFile('garbage.applied.json'), 'not json at all');
+ expect(await markerExists('garbage.applied.json')).toBe(true);
+ });
+ });
+
+ describe('readMarker', () => {
+ it('returns null when the marker file is absent', async () => {
+ expect(await readMarker('absent.applied.json')).toBeNull();
+ });
+
+ it('returns null for an empty marker file', async () => {
+ writeFileSync(markerFile('empty.applied.json'), '');
+ expect(await readMarker('empty.applied.json')).toBeNull();
+ });
+
+ it('returns null for an invalid-JSON marker instead of throwing', async () => {
+ writeFileSync(markerFile('broken.applied.json'), '{ not: valid');
+ expect(await readMarker('broken.applied.json')).toBeNull();
+ });
+
+ it('returns the parsed payload for a valid JSON marker', async () => {
+ const payload = { version: 2, appliedAt: '2026-01-01T00:00:00.000Z', scanned: 7 };
+ writeFileSync(markerFile('valid.applied.json'), JSON.stringify(payload));
+ expect(await readMarker('valid.applied.json')).toEqual(payload);
+ });
+ });
+
+ describe('writeMarker', () => {
+ it('writes pretty-printed JSON that round-trips through readMarker', async () => {
+ const payload = { migratedAt: '2026-02-02T00:00:00.000Z', imported: 3, skipped: 1, reason: 'imported' };
+ await writeMarker('roundtrip.migrated.json', payload);
+
+ // Persisted as 2-space pretty JSON.
+ const raw = readFileSync(markerFile('roundtrip.migrated.json'), 'utf-8');
+ expect(raw).toBe(JSON.stringify(payload, null, 2));
+
+ expect(await markerExists('roundtrip.migrated.json')).toBe(true);
+ expect(await readMarker('roundtrip.migrated.json')).toEqual(payload);
+ });
+
+ it('overwrites an existing marker with the new payload', async () => {
+ await writeMarker('overwrite.applied.json', { version: 1 });
+ await writeMarker('overwrite.applied.json', { version: 2, extra: true });
+ expect(await readMarker('overwrite.applied.json')).toEqual({ version: 2, extra: true });
+ });
+
+ it('creates the marker atomically (no leftover temp files in data/)', async () => {
+ await writeMarker('atomic.migrated.json', { ok: true });
+ expect(existsSync(markerFile('atomic.migrated.json'))).toBe(true);
+ // atomicWrite renames its temp file into place — none should linger.
+ const { readdirSync } = await import('fs');
+ const leftovers = readdirSync(TEST_DATA_ROOT).filter((f) => f.includes('.tmp'));
+ expect(leftovers).toEqual([]);
+ });
+ });
+});
diff --git a/server/scripts/backfillSeriesCoverImages.js b/server/scripts/backfillSeriesCoverImages.js
index 26b80d0bf9..d2531d4cda 100644
--- a/server/scripts/backfillSeriesCoverImages.js
+++ b/server/scripts/backfillSeriesCoverImages.js
@@ -24,9 +24,7 @@
* the PostgreSQL backend (normal installs) and the file escape hatch (tests).
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
+import { readMarker, writeMarker } from '../lib/migrationMarker.js';
import { listSeries, setSeriesCoverImage } from '../services/pipeline/series.js';
import { listAllIssues } from '../services/pipeline/issues.js';
import { deriveSeriesCoverImage, pickVolumeCoverFilename } from '../services/pipeline/seriesCoverImage.js';
@@ -34,24 +32,12 @@ import { deriveSeriesCoverImage, pickVolumeCoverFilename } from '../services/pip
const MARKER_VERSION = 1;
const MARKER_FILENAME = 'series-cover-backfill.applied.json';
-async function readMarker() {
- const path = join(PATHS.data, MARKER_FILENAME);
- const raw = await readFile(path, 'utf-8').catch(() => null);
- if (!raw) return null;
- try { return JSON.parse(raw); } catch { return null; }
-}
-
-async function writeMarker(payload) {
- const path = join(PATHS.data, MARKER_FILENAME);
- await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');
-}
-
/**
* Public entry point. Runs once, then no-ops on every subsequent boot via the
* marker file. `force` re-runs the walk regardless of the marker.
*/
export async function backfillSeriesCoverImages({ force = false } = {}) {
- const marker = await readMarker();
+ const marker = await readMarker(MARKER_FILENAME);
if (marker?.version === MARKER_VERSION && !force) {
return { skipped: true, marker };
}
@@ -104,7 +90,7 @@ export async function backfillSeriesCoverImages({ force = false } = {}) {
return { skipped: false, scanned, decorated, issueScanFailed: true };
}
- await writeMarker({ version: MARKER_VERSION, appliedAt: new Date().toISOString(), scanned });
+ await writeMarker(MARKER_FILENAME, { version: MARKER_VERSION, appliedAt: new Date().toISOString(), scanned });
console.log(`🖼️ series cover backfill: scanned ${scanned} series, ${decorated} have a cover`);
return { skipped: false, scanned, decorated };
}
diff --git a/server/scripts/backfillSeriesCoverImages.test.js b/server/scripts/backfillSeriesCoverImages.test.js
index f82b6ca0cf..899340d961 100644
--- a/server/scripts/backfillSeriesCoverImages.test.js
+++ b/server/scripts/backfillSeriesCoverImages.test.js
@@ -10,7 +10,13 @@ const listSeries = vi.fn();
const listAllIssues = vi.fn();
const setSeriesCoverImage = vi.fn();
-vi.mock('../lib/fileUtils.js', () => ({ PATHS: { get data() { return DATA_DIR; } } }));
+// Keep the real fileUtils helpers (tryReadFile/atomicWrite/safeJSONParse feed
+// migrationMarker.js) and only point PATHS.data at the disposable temp dir, so
+// the marker is a real on-disk file the existsSync/readFileSync assertions read.
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, get data() { return DATA_DIR; } } };
+});
vi.mock('../services/pipeline/series.js', () => ({
listSeries: (...a) => listSeries(...a),
setSeriesCoverImage: (...a) => setSeriesCoverImage(...a),
diff --git a/server/scripts/migrateBibleToCatalog.js b/server/scripts/migrateBibleToCatalog.js
index 1c82db923d..b16fcbdff7 100644
--- a/server/scripts/migrateBibleToCatalog.js
+++ b/server/scripts/migrateBibleToCatalog.js
@@ -19,10 +19,8 @@
* the marker file so the walk only runs once per install.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
import { createHash } from 'crypto';
-import { PATHS } from '../lib/fileUtils.js';
+import { readMarker, writeMarker } from '../lib/migrationMarker.js';
import { BIBLE_KINDS, BIBLE_FIELD } from '../lib/storyBible.js';
import { listUniverses, updateUniverse } from '../services/universeBuilder.js';
import * as catalogDB from '../services/catalogDB.js';
@@ -63,18 +61,6 @@ function deterministicIngredientId(universeId, kind, entryId) {
return `cat-${prefix}-bible-${hash}`;
}
-async function readMarker() {
- const path = join(PATHS.data, MARKER_FILENAME);
- const raw = await readFile(path, 'utf-8').catch(() => null);
- if (!raw) return null;
- try { return JSON.parse(raw); } catch { return null; }
-}
-
-async function writeMarker(payload) {
- const path = join(PATHS.data, MARKER_FILENAME);
- await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');
-}
-
/**
* Promote a single embedded canon entry to a catalog ingredient.
*
@@ -218,7 +204,7 @@ async function migrateUniverse(universe) {
* subsequent boot. Wired into server/index.js after ensureSchema().
*/
export async function migrateBibleToCatalog({ force = false } = {}) {
- const marker = await readMarker();
+ const marker = await readMarker(MARKER_FILENAME);
if (marker?.version === MARKER_VERSION && !force) {
return { skipped: true, marker };
}
@@ -242,7 +228,7 @@ export async function migrateBibleToCatalog({ force = false } = {}) {
completedAt: new Date().toISOString(),
stats: totals,
};
- await writeMarker(payload);
+ await writeMarker(MARKER_FILENAME, payload);
console.log(
`🪄 bible→catalog migration: ${totals.universesScanned} universes scanned, ` +
diff --git a/server/scripts/migrateBibleToCatalog.test.js b/server/scripts/migrateBibleToCatalog.test.js
index 59bd9cc610..fc48ca55cf 100644
--- a/server/scripts/migrateBibleToCatalog.test.js
+++ b/server/scripts/migrateBibleToCatalog.test.js
@@ -78,17 +78,12 @@ vi.mock('../services/catalogDB.js', () => ({
}));
// --- In-memory marker file -----------------------------------------------
+// Marker I/O is delegated to migrationMarker.js; mock it against `markerBlob`
+// (the marker helper has its own unit test in server/lib/migrationMarker.test.js).
let markerBlob = null; // string | null
-vi.mock('fs/promises', () => ({
- readFile: vi.fn(async () => {
- if (markerBlob === null) {
- const err = new Error('ENOENT');
- err.code = 'ENOENT';
- throw err;
- }
- return markerBlob;
- }),
- writeFile: vi.fn(async (_path, data) => { markerBlob = data; }),
+vi.mock('../lib/migrationMarker.js', () => ({
+ readMarker: vi.fn(async () => (markerBlob === null ? null : JSON.parse(markerBlob))),
+ writeMarker: vi.fn(async (_name, payload) => { markerBlob = JSON.stringify(payload); }),
}));
import { migrateBibleToCatalog } from './migrateBibleToCatalog.js';
diff --git a/server/scripts/migrateCatalogPayload.js b/server/scripts/migrateCatalogPayload.js
index 56134c486a..2c3dcb7823 100644
--- a/server/scripts/migrateCatalogPayload.js
+++ b/server/scripts/migrateCatalogPayload.js
@@ -27,9 +27,7 @@
* ride the pre-DB `scripts/migrations/` file runner.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
+import { readMarker, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
import { CATALOG_TYPES, currentPayloadSchemaVersion, upgradePayload } from '../lib/catalogTypes.js';
@@ -42,18 +40,6 @@ const MARKER_FILENAME = 'catalog-payload.applied.json';
// skip the no-op boot scan on an already-migrated install.)
const targetHighWater = () => Math.max(...CATALOG_TYPES.map((t) => t.payloadSchemaVersion));
-async function readMarker() {
- const path = join(PATHS.data, MARKER_FILENAME);
- const raw = await readFile(path, 'utf-8').catch(() => null);
- if (!raw) return null;
- try { return JSON.parse(raw); } catch { return null; }
-}
-
-async function writeMarker(payload) {
- const path = join(PATHS.data, MARKER_FILENAME);
- await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');
-}
-
/**
* Walk one type's below-current rows and apply the upgrader chain. Returns the
* number of rows upgraded. Rows whose stored `schemaVersion` is absent are
@@ -97,7 +83,7 @@ async function migrateType(type) {
*/
export async function migrateCatalogPayload({ force = false } = {}) {
const highWater = targetHighWater();
- const marker = await readMarker();
+ const marker = await readMarker(MARKER_FILENAME);
if (!force && marker?.highWater >= highWater) {
return { skipped: true, marker };
}
@@ -114,7 +100,7 @@ export async function migrateCatalogPayload({ force = false } = {}) {
}
const payload = { highWater, completedAt: new Date().toISOString(), stats: totals };
- await writeMarker(payload);
+ await writeMarker(MARKER_FILENAME, payload);
console.log(`🧬 catalog payload migration: ${totals.upgraded} row(s) upgraded across ${totals.typesWalked} type(s)`);
return { skipped: false, ...payload };
}
diff --git a/server/scripts/migrateCatalogPayload.test.js b/server/scripts/migrateCatalogPayload.test.js
index ffe214dfeb..ace908ccfd 100644
--- a/server/scripts/migrateCatalogPayload.test.js
+++ b/server/scripts/migrateCatalogPayload.test.js
@@ -22,13 +22,13 @@ vi.mock('../lib/db.js', () => ({
}),
}));
-vi.mock('fs/promises', () => ({
- readFile: vi.fn(async () => (fsState.marker == null ? Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })) : JSON.stringify(fsState.marker))),
- writeFile: vi.fn(async (_p, data) => { fsState.written = JSON.parse(data); }),
+// Marker I/O is delegated to migrationMarker.js; mock it against `fsState`
+// (the marker helper has its own unit test in server/lib/migrationMarker.test.js).
+vi.mock('../lib/migrationMarker.js', () => ({
+ readMarker: vi.fn(async () => fsState.marker),
+ writeMarker: vi.fn(async (_name, payload) => { fsState.written = payload; }),
}));
-vi.mock('../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-data' } }));
-
// Inject a synthetic registry with a v1→v2 upgrader (character) plus an all-v1
// upgrader-less type (idea). Defined inside the factory because vi.mock hoists
// above top-level consts.
diff --git a/server/scripts/migrateCreativeDirectorToDB.js b/server/scripts/migrateCreativeDirectorToDB.js
index 06d451fd09..0d0b06d858 100644
--- a/server/scripts/migrateCreativeDirectorToDB.js
+++ b/server/scripts/migrateCreativeDirectorToDB.js
@@ -29,9 +29,10 @@
* the backend selector instead.
*/
-import { readFile, writeFile, rename } from 'fs/promises';
+import { readFile, rename } from 'fs/promises';
import { join } from 'path';
import { PATHS } from '../lib/fileUtils.js';
+import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
import { mirrorStatus, mirrorTimestamp } from '../services/creativeDirector/projectsLogic.js';
@@ -39,20 +40,9 @@ const LEGACY_FILENAME = 'creative-director-projects.json';
const IMPORTED_SUFFIX = '.imported';
const MARKER_FILENAME = 'creative-director-projects.migrated.json';
-async function markerExists() {
- const path = join(PATHS.data, MARKER_FILENAME);
- const raw = await readFile(path, 'utf-8').catch(() => null);
- return raw != null;
-}
-
-async function writeMarker(payload) {
- const path = join(PATHS.data, MARKER_FILENAME);
- await writeFile(path, JSON.stringify(payload, null, 2) + '\n', 'utf-8');
-}
-
export async function migrateCreativeDirectorToDB() {
// Already imported on a prior boot → no-op.
- if (await markerExists()) return { ok: true, reason: 'already-applied' };
+ if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied' };
const legacyPath = join(PATHS.data, LEGACY_FILENAME);
const raw = await readFile(legacyPath, 'utf-8').catch((err) => {
@@ -63,7 +53,7 @@ export async function migrateCreativeDirectorToDB() {
// Fresh install (no legacy file): stamp the marker so we don't re-probe every
// boot, and return.
if (raw == null) {
- await writeMarker({ migratedAt: new Date().toISOString(), imported: 0, reason: 'fresh-install' });
+ await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), imported: 0, reason: 'fresh-install' });
return { ok: true, reason: 'fresh-install', imported: 0 };
}
@@ -127,7 +117,7 @@ export async function migrateCreativeDirectorToDB() {
});
if (!renamed) return { ok: false, reason: 'rename-failed', imported, skipped };
- await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped });
+ await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), imported, skipped });
console.log(`🎬 CD→DB import: imported ${imported} project(s) into creative_director_projects (${skipped} skipped); legacy file renamed to ${LEGACY_FILENAME}${IMPORTED_SUFFIX}`);
return { ok: true, reason: 'imported', imported, skipped };
}
diff --git a/server/scripts/migrateCreativeDirectorToDB.test.js b/server/scripts/migrateCreativeDirectorToDB.test.js
index 0ea1f79e01..268fe8d853 100644
--- a/server/scripts/migrateCreativeDirectorToDB.test.js
+++ b/server/scripts/migrateCreativeDirectorToDB.test.js
@@ -18,6 +18,13 @@ vi.mock('../lib/fileUtils.js', () => ({
// Rename can be made to fail per-test via `renameShouldFail`.
let renameShouldFail = false;
+// Marker I/O is delegated to migrationMarker.js; mock it against the same
+// in-memory `files` map (the marker helper has its own unit test).
+vi.mock('../lib/migrationMarker.js', () => ({
+ markerExists: vi.fn(async (name) => (`/fake/data/${name}` in files)),
+ writeMarker: vi.fn(async (name, payload) => { files[`/fake/data/${name}`] = JSON.stringify(payload, null, 2); }),
+}));
+
vi.mock('fs/promises', () => ({
readFile: vi.fn(async (path) => {
if (!(path in files)) {
@@ -27,7 +34,6 @@ vi.mock('fs/promises', () => ({
}
return files[path];
}),
- writeFile: vi.fn(async (path, content) => { files[path] = content; }),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES: rename failed');
files[to] = files[from];
diff --git a/server/scripts/migrateIssuesToDB.js b/server/scripts/migrateIssuesToDB.js
index 3f11492555..5f25b5eb75 100644
--- a/server/scripts/migrateIssuesToDB.js
+++ b/server/scripts/migrateIssuesToDB.js
@@ -19,9 +19,10 @@
* the dir → next boot retries (ON CONFLICT DO NOTHING makes the retry safe).
*/
-import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { rename, readdir, stat } from 'fs/promises';
import { join } from 'path';
import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
@@ -30,15 +31,6 @@ const IMPORTED_DIRNAME = 'pipeline-issues.imported';
const MARKER_FILENAME = 'pipeline-issues.migrated.json';
const RECORD_RE = /^iss-[A-Za-z0-9-]+$/;
-async function markerExists() {
- const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
- return raw != null;
-}
-
-async function writeMarker(payload) {
- await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
-}
-
async function importRecord(record) {
if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
if (typeof record.seriesId !== 'string' || !record.seriesId) return false;
@@ -66,7 +58,7 @@ async function importRecord(record) {
}
export async function migrateIssuesToDB() {
- if (await markerExists()) return { ok: true, reason: 'already-applied', imported: 0 };
+ if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
const dirStat = await stat(legacyDir).catch(() => null);
@@ -92,7 +84,7 @@ export async function migrateIssuesToDB() {
console.warn(`⚠️ pipeline-issues→DB import: imported ${imported} issue(s) but renaming ${LEGACY_DIRNAME} aside failed (${err.message}) — leaving dir, will retry marker next boot`);
return { ok: true, reason: 'imported-rename-failed', imported, skipped };
}
- await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
+ await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
console.log(`📚 pipeline-issues→DB import: imported ${imported} issue(s) (${skipped} skipped); data/${LEGACY_DIRNAME} renamed to ${IMPORTED_DIRNAME}`);
return { ok: true, reason: 'imported', imported, skipped };
}
diff --git a/server/scripts/migrateIssuesToDB.test.js b/server/scripts/migrateIssuesToDB.test.js
index 4fea3dcbf3..e8fe011b3e 100644
--- a/server/scripts/migrateIssuesToDB.test.js
+++ b/server/scripts/migrateIssuesToDB.test.js
@@ -18,12 +18,14 @@ vi.mock('../lib/fileUtils.js', () => ({
readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
}));
+// Marker I/O is delegated to migrationMarker.js; mock it against the same
+// in-memory `files` map (the marker helper has its own unit test).
+vi.mock('../lib/migrationMarker.js', () => ({
+ markerExists: vi.fn(async (name) => (`/fake/data/${name}` in files)),
+ writeMarker: vi.fn(async (name, payload) => { files[`/fake/data/${name}`] = JSON.stringify(payload, null, 2); }),
+}));
+
vi.mock('fs/promises', () => ({
- readFile: vi.fn(async (path) => {
- if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
- return files[path];
- }),
- writeFile: vi.fn(async (path, content) => { files[path] = content; }),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
renamed.push([from, to]);
diff --git a/server/scripts/migrateSeriesToDB.js b/server/scripts/migrateSeriesToDB.js
index f96620e9bf..f26599a658 100644
--- a/server/scripts/migrateSeriesToDB.js
+++ b/server/scripts/migrateSeriesToDB.js
@@ -30,9 +30,10 @@
* retry safe; an already-renamed record is simply skipped on re-read).
*/
-import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { rename, readdir, stat } from 'fs/promises';
import { join } from 'path';
import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
@@ -40,15 +41,6 @@ const LEGACY_DIRNAME = 'pipeline-series';
const MARKER_FILENAME = 'pipeline-series.migrated.json';
const RECORD_RE = /^ser-[A-Za-z0-9-]+$/;
-async function markerExists() {
- const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
- return raw != null;
-}
-
-async function writeMarker(payload) {
- await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
-}
-
// One legacy series record → `pipeline_series` row. Verbatim into `data`; the
// typed mirror columns are bind-sanitized so a hand-edited/legacy value can't
// make the INSERT throw and abort the whole import.
@@ -77,7 +69,7 @@ async function importRecord(record) {
}
export async function migrateSeriesToDB() {
- if (await markerExists()) return { ok: true, reason: 'already-applied', imported: 0 };
+ if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
const dirStat = await stat(legacyDir).catch(() => null);
@@ -106,7 +98,7 @@ export async function migrateSeriesToDB() {
await rename(recordPath, `${recordPath}.imported`).catch(() => {});
}
- await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
+ await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
console.log(`🎬 pipeline-series→DB import: imported ${imported} series (${skipped} skipped); index.json renamed aside in place (review siblings kept)`);
return { ok: true, reason: 'imported', imported, skipped };
}
diff --git a/server/scripts/migrateSeriesToDB.test.js b/server/scripts/migrateSeriesToDB.test.js
index 97ad7bbd54..49b7c27ba2 100644
--- a/server/scripts/migrateSeriesToDB.test.js
+++ b/server/scripts/migrateSeriesToDB.test.js
@@ -17,12 +17,14 @@ vi.mock('../lib/fileUtils.js', () => ({
readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
}));
+// Marker I/O is delegated to migrationMarker.js; mock it against the same
+// in-memory `files` map (the marker helper has its own unit test).
+vi.mock('../lib/migrationMarker.js', () => ({
+ markerExists: vi.fn(async (name) => (`/fake/data/${name}` in files)),
+ writeMarker: vi.fn(async (name, payload) => { files[`/fake/data/${name}`] = JSON.stringify(payload, null, 2); }),
+}));
+
vi.mock('fs/promises', () => ({
- readFile: vi.fn(async (path) => {
- if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
- return files[path];
- }),
- writeFile: vi.fn(async (path, content) => { files[path] = content; }),
rename: vi.fn(async (from, to) => { renamed.push([from, to]); }),
readdir: vi.fn(async () => (dirEntries === null ? [] : dirEntries)),
stat: vi.fn(async (path) => {
diff --git a/server/scripts/migrateStoryBuilderToDB.js b/server/scripts/migrateStoryBuilderToDB.js
index ffafb82194..4485beea44 100644
--- a/server/scripts/migrateStoryBuilderToDB.js
+++ b/server/scripts/migrateStoryBuilderToDB.js
@@ -20,9 +20,10 @@
* the dir → next boot retries (ON CONFLICT DO NOTHING makes the retry safe).
*/
-import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { rename, readdir, stat } from 'fs/promises';
import { join } from 'path';
import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
@@ -31,15 +32,6 @@ const IMPORTED_DIRNAME = 'story-builder.imported';
const MARKER_FILENAME = 'story-builder.migrated.json';
const RECORD_RE = /^stb-[A-Za-z0-9-]+$/;
-async function markerExists() {
- const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
- return raw != null;
-}
-
-async function writeMarker(payload) {
- await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
-}
-
// One legacy session record → `story_builder_sessions` row. Verbatim into
// `data`; the typed mirror columns are bind-sanitized so a hand-edited/legacy
// value can't make the INSERT throw and abort the whole import.
@@ -68,7 +60,7 @@ async function importRecord(record) {
}
export async function migrateStoryBuilderToDB() {
- if (await markerExists()) return { ok: true, reason: 'already-applied', imported: 0 };
+ if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
const dirStat = await stat(legacyDir).catch(() => null);
@@ -96,7 +88,7 @@ export async function migrateStoryBuilderToDB() {
console.warn(`⚠️ story-builder→DB import: imported ${imported} session(s) but renaming ${LEGACY_DIRNAME} aside failed (${err.message}) — leaving dir, will retry marker next boot`);
return { ok: true, reason: 'imported-rename-failed', imported, skipped };
}
- await writeMarker({ migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
+ await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
console.log(`📖 story-builder→DB import: imported ${imported} session(s) (${skipped} skipped); data/${LEGACY_DIRNAME} renamed to ${IMPORTED_DIRNAME}`);
return { ok: true, reason: 'imported', imported, skipped };
}
diff --git a/server/scripts/migrateStoryBuilderToDB.test.js b/server/scripts/migrateStoryBuilderToDB.test.js
index f1a6274359..e6a2c0d885 100644
--- a/server/scripts/migrateStoryBuilderToDB.test.js
+++ b/server/scripts/migrateStoryBuilderToDB.test.js
@@ -18,12 +18,14 @@ vi.mock('../lib/fileUtils.js', () => ({
readJSONFile: vi.fn(async (path) => recordsByDir[path] ?? null),
}));
+// Marker I/O is delegated to migrationMarker.js; mock it against the same
+// in-memory `files` map (the marker helper has its own unit test).
+vi.mock('../lib/migrationMarker.js', () => ({
+ markerExists: vi.fn(async (name) => (`/fake/data/${name}` in files)),
+ writeMarker: vi.fn(async (name, payload) => { files[`/fake/data/${name}`] = JSON.stringify(payload, null, 2); }),
+}));
+
vi.mock('fs/promises', () => ({
- readFile: vi.fn(async (path) => {
- if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
- return files[path];
- }),
- writeFile: vi.fn(async (path, content) => { files[path] = content; }),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
renamed.push([from, to]);
diff --git a/server/scripts/migrateUniversesToDB.js b/server/scripts/migrateUniversesToDB.js
index 8f11dc0e5a..56ce0a50d4 100644
--- a/server/scripts/migrateUniversesToDB.js
+++ b/server/scripts/migrateUniversesToDB.js
@@ -28,9 +28,10 @@
* it's gated on its own marker and invoked from the backend selector.
*/
-import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { rename, readdir, stat } from 'fs/promises';
import { join } from 'path';
import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
@@ -38,15 +39,6 @@ const LEGACY_DIRNAME = 'universes';
const IMPORTED_DIRNAME = 'universes.imported';
const MARKER_FILENAME = 'universes.migrated.json';
-async function markerExists() {
- const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
- return raw != null;
-}
-
-async function writeMarker(payload) {
- await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
-}
-
// One legacy universe record → `universes` row. Verbatim into `data`; the typed
// mirror columns are bind-sanitized so a hand-edited/legacy timestamp or missing
// field can't make the INSERT throw and abort the whole import.
@@ -92,7 +84,7 @@ async function importRun(run) {
}
export async function migrateUniversesToDB() {
- if (await markerExists()) return { ok: true, reason: 'already-applied', imported: 0 };
+ if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
const dirStat = await stat(legacyDir).catch(() => null);
@@ -135,7 +127,7 @@ export async function migrateUniversesToDB() {
console.warn(`⚠️ universes→DB import: imported ${imported} record(s)/${runs} run(s) but renaming ${LEGACY_DIRNAME} aside failed (${err.message}) — leaving dir, will retry marker next boot`);
return { ok: true, reason: 'imported-rename-failed', imported, runs };
}
- await writeMarker({ migratedAt: new Date().toISOString(), imported, runs, skipped, reason: 'imported' });
+ await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), imported, runs, skipped, reason: 'imported' });
console.log(`🌍 universes→DB import: imported ${imported} universe(s) + ${runs} run(s) (${skipped} skipped); data/${LEGACY_DIRNAME} renamed to ${IMPORTED_DIRNAME}`);
return { ok: true, reason: 'imported', imported, runs, skipped };
}
diff --git a/server/scripts/migrateUniversesToDB.test.js b/server/scripts/migrateUniversesToDB.test.js
index 8610dfec52..ec037fd4e1 100644
--- a/server/scripts/migrateUniversesToDB.test.js
+++ b/server/scripts/migrateUniversesToDB.test.js
@@ -24,12 +24,15 @@ vi.mock('../lib/fileUtils.js', () => ({
}),
}));
+// Marker I/O is delegated to migrationMarker.js; mock it against the same
+// in-memory `files` map so the walk's gate/stamp behavior is exercised without
+// the marker helper's real fs (the helper has its own unit test).
+vi.mock('../lib/migrationMarker.js', () => ({
+ markerExists: vi.fn(async (name) => (`/fake/data/${name}` in files)),
+ writeMarker: vi.fn(async (name, payload) => { files[`/fake/data/${name}`] = JSON.stringify(payload, null, 2); }),
+}));
+
vi.mock('fs/promises', () => ({
- readFile: vi.fn(async (path) => {
- if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
- return files[path];
- }),
- writeFile: vi.fn(async (path, content) => { files[path] = content; }),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
renamed.push([from, to]);
diff --git a/server/scripts/migrateWritersRoomToDB.js b/server/scripts/migrateWritersRoomToDB.js
index 8be663d7d9..9f2068b290 100644
--- a/server/scripts/migrateWritersRoomToDB.js
+++ b/server/scripts/migrateWritersRoomToDB.js
@@ -28,9 +28,10 @@
* retries (ON CONFLICT DO NOTHING makes the retry safe).
*/
-import { readFile, writeFile, rename, readdir, stat } from 'fs/promises';
+import { readFile, rename, readdir, stat } from 'fs/promises';
import { join } from 'path';
import { PATHS, readJSONFile, safeJSONParse } from '../lib/fileUtils.js';
+import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
@@ -38,15 +39,6 @@ const ROOT_DIRNAME = 'writers-room';
const MARKER_FILENAME = 'writers-room.migrated.json';
const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;
-async function markerExists() {
- const raw = await readFile(join(PATHS.data, MARKER_FILENAME), 'utf-8').catch(() => null);
- return raw != null;
-}
-
-async function writeMarker(payload) {
- await writeFile(join(PATHS.data, MARKER_FILENAME), JSON.stringify(payload, null, 2) + '\n', 'utf-8');
-}
-
// Rename a file aside (path → path.replace('.json','.imported.json')) if it
// exists; a missing file is a no-op. Never overwrites an existing recovery copy.
async function parkFileAside(path) {
@@ -156,7 +148,7 @@ async function importWork(manifest) {
}
export async function migrateWritersRoomToDB() {
- if (await markerExists()) return { ok: true, reason: 'already-applied' };
+ if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied' };
const root = join(PATHS.data, ROOT_DIRNAME);
const rootStat = await stat(root).catch(() => null);
@@ -208,7 +200,7 @@ export async function migrateWritersRoomToDB() {
await parkFileAside(exercisesFile);
for (const p of importedManifestPaths) await parkFileAside(p);
- await writeMarker({
+ await writeMarker(MARKER_FILENAME, {
migratedAt: new Date().toISOString(),
folders: folderCount, works: workCount, exercises: exerciseCount, reason: 'imported',
});
diff --git a/server/scripts/migrateWritersRoomToDB.test.js b/server/scripts/migrateWritersRoomToDB.test.js
index e11fad8dca..a3fe0e5628 100644
--- a/server/scripts/migrateWritersRoomToDB.test.js
+++ b/server/scripts/migrateWritersRoomToDB.test.js
@@ -26,12 +26,18 @@ vi.mock('../lib/fileUtils.js', () => ({
safeJSONParse: vi.fn((content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } }),
}));
+// Marker I/O is delegated to migrationMarker.js; mock it against the same
+// in-memory `files` map (the marker helper has its own unit test).
+vi.mock('../lib/migrationMarker.js', () => ({
+ markerExists: vi.fn(async (name) => (`${DATA}/${name}` in files)),
+ writeMarker: vi.fn(async (name, payload) => { files[`${DATA}/${name}`] = JSON.stringify(payload, null, 2); }),
+}));
+
vi.mock('fs/promises', () => ({
readFile: vi.fn(async (path) => {
if (!(path in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
return files[path];
}),
- writeFile: vi.fn(async (path, content) => { files[path] = content; }),
rename: vi.fn(async (from, to) => { renamed.push([from, to]); files[to] = files[from]; delete files[from]; }),
readdir: vi.fn(async (path) => {
if (path === WORKS) return workDirs;
diff --git a/server/scripts/reconcileCanonCatalog.js b/server/scripts/reconcileCanonCatalog.js
index 826f6f34e2..1f33b6dc0f 100644
--- a/server/scripts/reconcileCanonCatalog.js
+++ b/server/scripts/reconcileCanonCatalog.js
@@ -33,9 +33,7 @@
* is at its current payload-shape version before this reconciles content.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
+import { readMarker, writeMarker } from '../lib/migrationMarker.js';
import { BIBLE_FIELD } from '../lib/storyBible.js';
import { listUniverses, updateUniverse } from '../services/universeBuilder.js';
import * as catalogDB from '../services/catalogDB.js';
@@ -49,25 +47,13 @@ const MARKER_FILENAME = 'catalog-canon-reconcile.applied.json';
const CANON_ARRAY_KEYS = Object.values(BIBLE_FIELD); // ['characters','places','objects']
-async function readMarker() {
- const path = join(PATHS.data, MARKER_FILENAME);
- const raw = await readFile(path, 'utf-8').catch(() => null);
- if (!raw) return null;
- try { return JSON.parse(raw); } catch { return null; }
-}
-
-async function writeMarker(payload) {
- const path = join(PATHS.data, MARKER_FILENAME);
- await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');
-}
-
/**
* Public entry point. Walk every universe canon entry with an `ingredientId`,
* LWW-merge embedded vs catalog payload, write the winner to both sides.
* `force` re-runs past the marker (tests / admin re-trigger).
*/
export async function reconcileCanonCatalog({ force = false } = {}) {
- const marker = await readMarker();
+ const marker = await readMarker(MARKER_FILENAME);
if (marker?.version === MARKER_VERSION && !force) {
return { skipped: true, marker };
}
@@ -172,7 +158,7 @@ export async function reconcileCanonCatalog({ force = false } = {}) {
// Only stamp the completion marker on a clean pass — a row-level failure
// withholds it so the (idempotent) reconcile retries next boot.
const wroteMarker = totals.errors === 0;
- if (wroteMarker) await writeMarker(payload);
+ if (wroteMarker) await writeMarker(MARKER_FILENAME, payload);
console.log(
`🔁 canon↔catalog reconcile: ${totals.universesScanned} universes, ${totals.scanned} entries scanned, ` +
diff --git a/server/scripts/reconcileCanonCatalog.test.js b/server/scripts/reconcileCanonCatalog.test.js
index ac6cc1a451..d8795c72a0 100644
--- a/server/scripts/reconcileCanonCatalog.test.js
+++ b/server/scripts/reconcileCanonCatalog.test.js
@@ -16,15 +16,13 @@ const fsState = { marker: null, written: null };
const dbState = { rows: {}, updates: [] };
const uniState = { universes: [], canonStamps: [] };
-vi.mock('fs/promises', () => ({
- readFile: vi.fn(async () => (fsState.marker == null
- ? Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
- : JSON.stringify(fsState.marker))),
- writeFile: vi.fn(async (_p, data) => { fsState.written = JSON.parse(data); }),
+// Marker I/O is delegated to migrationMarker.js; mock it against `fsState`
+// (the marker helper has its own unit test in server/lib/migrationMarker.test.js).
+vi.mock('../lib/migrationMarker.js', () => ({
+ readMarker: vi.fn(async () => fsState.marker),
+ writeMarker: vi.fn(async (_name, payload) => { fsState.written = payload; }),
}));
-vi.mock('../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-data' } }));
-
vi.mock('../services/universeBuilder.js', () => ({
listUniverses: vi.fn(async () => uniState.universes),
updateUniverse: vi.fn(async (id, mutator) => {
diff --git a/server/scripts/repairUniverseTags.js b/server/scripts/repairUniverseTags.js
index 9b9dc3a2a9..63eccac4f3 100644
--- a/server/scripts/repairUniverseTags.js
+++ b/server/scripts/repairUniverseTags.js
@@ -25,9 +25,7 @@
* DB pool is up, the same reason migrations 048–052 are boot-time + stubbed.
*/
-import { readFile, writeFile } from 'fs/promises';
-import { join } from 'path';
-import { PATHS } from '../lib/fileUtils.js';
+import { readMarker, writeMarker } from '../lib/migrationMarker.js';
import { friendlifyUniverseTags } from '../lib/catalogUniverseTags.js';
import { canonicalTagKey } from '../lib/catalogTypes.js';
import { listUniverses } from '../services/universeBuilder.js';
@@ -40,18 +38,6 @@ import * as catalogDB from '../services/catalogDB.js';
const MARKER_VERSION = 2;
const MARKER_FILENAME = 'catalog-universe-tags.applied.json';
-async function readMarker() {
- const path = join(PATHS.data, MARKER_FILENAME);
- const raw = await readFile(path, 'utf-8').catch(() => null);
- if (!raw) return null;
- try { return JSON.parse(raw); } catch { return null; }
-}
-
-async function writeMarker(payload) {
- const path = join(PATHS.data, MARKER_FILENAME);
- await writeFile(path, JSON.stringify(payload, null, 2), 'utf-8');
-}
-
/**
* Build a universeId → name lookup from every universe (including deleted, so a
* row tagged with a soft-deleted universe still resolves to a readable name
@@ -73,7 +59,7 @@ async function buildUniverseNameMap() {
* marker file. `force` re-runs the walk (used by tests / an admin re-trigger).
*/
export async function repairUniverseTags({ force = false } = {}) {
- const marker = await readMarker();
+ const marker = await readMarker(MARKER_FILENAME);
if (marker?.version === MARKER_VERSION && !force) {
return { skipped: true, marker };
}
@@ -127,7 +113,7 @@ export async function repairUniverseTags({ force = false } = {}) {
// repair next boot — already-friendlified rows are no-ops, so only the failed
// / not-yet-resolvable rows retry.
const wroteMarker = totals.errors === 0 && totals.unresolved === 0;
- if (wroteMarker) await writeMarker(payload);
+ if (wroteMarker) await writeMarker(MARKER_FILENAME, payload);
console.log(
`🏷️ universe-tag repair: ${totals.scanned} scanned, ` +
diff --git a/server/scripts/repairUniverseTags.test.js b/server/scripts/repairUniverseTags.test.js
index 35dfceeb15..afb551b4a9 100644
--- a/server/scripts/repairUniverseTags.test.js
+++ b/server/scripts/repairUniverseTags.test.js
@@ -15,15 +15,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const fsState = { marker: null, written: null };
const dbState = { ingredients: [], updates: [] };
-vi.mock('fs/promises', () => ({
- readFile: vi.fn(async () => (fsState.marker == null
- ? Promise.reject(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
- : JSON.stringify(fsState.marker))),
- writeFile: vi.fn(async (_p, data) => { fsState.written = JSON.parse(data); }),
+// Marker I/O is delegated to migrationMarker.js; mock it against `fsState`
+// (the marker helper has its own unit test in server/lib/migrationMarker.test.js).
+vi.mock('../lib/migrationMarker.js', () => ({
+ readMarker: vi.fn(async () => fsState.marker),
+ writeMarker: vi.fn(async (_name, payload) => { fsState.written = payload; }),
}));
-vi.mock('../lib/fileUtils.js', () => ({ PATHS: { data: '/tmp/portos-data' } }));
-
vi.mock('../services/universeBuilder.js', () => ({
listUniverses: vi.fn(async () => [
{ id: 'u-1', name: 'My Cool Universe' },