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: stage migration 224's rewrites before promoting them, so a rename chain survives a crash (#3465)
[._.]/ Adam Eivycd149390e22c
diff --git a/scripts/migrations/224-iso-week-numbering-year-ids.js b/scripts/migrations/224-iso-week-numbering-year-ids.jsindex 96f5c00391..ac9e478846 100644--- a/scripts/migrations/224-iso-week-numbering-year-ids.js+++ b/scripts/migrations/224-iso-week-numbering-year-ids.js@@ -41,9 +41,13 @@* so a second pass writes nothing. Safe on an install with no digests dir and* no productivity file at all — both are runtime-generated (neither ships a* `data.reference/` seed), so a fresh install simply has nothing to do.+ *+ * Crash-safe: rewrites are staged beside their targets and promoted only once+ * all of them are durable (see STAGING_SUFFIX / PLAN_FILE), because a rename+ * target is frequently another digest's current filename.*/-import { readdir, readFile, unlink } from 'fs/promises';+import { readdir, readFile, rename, unlink } from 'fs/promises';import { join } from 'path';import { atomicWrite } from '../../server/lib/fileUtils.js';import { getIsoWeekNumber, getWeekId, parseWeekId } from '../../server/lib/isoWeek.js';@@ -193,16 +197,56 @@ export function planDigestRewrite(records, occupied = []) {return { writes, deletes, skipped };}+// A rename target is often another digest's CURRENT name (2018-W01 → 2019-W01+// while 2019-W01 itself moves to 2020-W01), so writing straight to the target+// destroys a source whose migrated copy exists only in memory — one crash and+// that digest is gone for good. Rewrites are therefore staged beside their+// target first, and only promoted once EVERY rewrite is durable. The suffix+// deliberately does not end in `.json`, so neither this migration's own scan+// nor `listDigests()` ever mistakes a staged file for a digest.+const STAGING_SUFFIX = '.staging-224';+// Written once staging is complete; its presence is what makes promoting a+// staged file safe. No `.json` suffix, for the same reason.+const PLAN_FILE = '.migration-224-plan';++/**+ * Finish (or discard) a previous run that died mid-write.+ *+ * Plan file present ⇒ every rewrite was durable, so promote whatever staging+ * files are left; that is precisely the set whose targets may have been+ * clobbered. Plan file absent ⇒ staging was incomplete and promoting would+ * overwrite live digests with a partial plan, so drop the leftovers.+ */+async function recoverInterruptedRun(dir, entries) {+ const staged = entries.filter(f => f.endsWith(STAGING_SUFFIX));+ const plan = await readJsonOrNull(join(dir, PLAN_FILE));+ if (staged.length === 0 && !plan) return false;++ if (plan) {+ for (const file of staged) {+ await rename(join(dir, file), join(dir, file.slice(0, -STAGING_SUFFIX.length)));+ }+ console.warn(`⚠️ migration 224: completed ${staged.length} staged rewrite(s) left by an interrupted run`);+ } else {+ for (const file of staged) await unlink(join(dir, file)).catch(() => {});+ console.warn(`⚠️ migration 224: discarded ${staged.length} incomplete staged rewrite(s) from an interrupted run`);+ }+ await unlink(join(dir, PLAN_FILE)).catch((err) => { if (err.code !== 'ENOENT') throw err; });+ return true;+}+async function migrateDigests(rootDir) {const dir = join(rootDir, 'data', 'cos', 'digests');- const entries = await readdir(dir).catch((err) => {+ const readEntries = () => readdir(dir).catch((err) => {if (err.code === 'ENOENT') return null;throw err;});+ let entries = await readEntries();if (entries == null) {console.log('📊 migration 224: no CoS digests directory — nothing to rename');return { renamed: 0, skipped: 0 };}+ if (await recoverInterruptedRun(dir, entries)) entries = await readEntries() ?? [];// Read EVERY digest before writing anything: a rename target can be another// digest's current name, and reading up front means no pass ever reads a file@@ -220,7 +264,15 @@ async function migrateDigests(rootDir) {}const { writes, deletes, skipped } = planDigestRewrite(records, unreadable);- for (const { file, digest } of writes) await atomicWrite(join(dir, file), digest);+ if (writes.length > 0) {+ // Stage → commit → promote. Nothing live is touched until every rewrite is+ // on disk under its staging name.+ for (const { file, digest } of writes) await atomicWrite(join(dir, `${file}${STAGING_SUFFIX}`), digest);+ await atomicWrite(join(dir, PLAN_FILE), { migration: 224, files: writes.map(w => w.file) });+ for (const { file } of writes) {+ await rename(join(dir, `${file}${STAGING_SUFFIX}`), join(dir, file));+ }+ }// Only ENOENT is benign (an already-removed source on a re-run). Anything else// means a stale old-form file survives, so let it throw: the runner leaves the// migration unrecorded and the next boot retries instead of banking a@@ -228,6 +280,9 @@ async function migrateDigests(rootDir) {for (const file of deletes) {await unlink(join(dir, file)).catch((err) => { if (err.code !== 'ENOENT') throw err; });}+ if (writes.length > 0) {+ await unlink(join(dir, PLAN_FILE)).catch((err) => { if (err.code !== 'ENOENT') throw err; });+ }if (writes.length === 0) {console.log(`📊 migration 224: all ${records.length} digest(s) already use ISO week-numbering ids`);diff --git a/scripts/migrations/224-iso-week-numbering-year-ids.test.js b/scripts/migrations/224-iso-week-numbering-year-ids.test.jsindex e5c0b02e11..e8f52eab3f 100644--- a/scripts/migrations/224-iso-week-numbering-year-ids.test.js+++ b/scripts/migrations/224-iso-week-numbering-year-ids.test.js@@ -153,6 +153,17 @@ describe('planDigestRewrite', () => {expect(skipped).toEqual(['2025-W01.json']);});+ it("plans a chain where one digest renames onto another digest's current name", () => {+ const { writes, deletes, skipped } = planDigestRewrite([+ { file: '2018-W01.json', digest: digestFixture('2018-W01', '2018-12-31') },+ { file: '2019-W01.json', digest: digestFixture('2019-W01', '2019-12-30') },+ ]);+ expect(writes.map(w => w.file).sort()).toEqual(['2019-W01.json', '2020-W01.json']);+ // 2019-W01.json survives as a rename TARGET, so only the head of the chain goes.+ expect(deletes).toEqual(['2018-W01.json']);+ expect(skipped).toEqual([]);+ });+it('finishes an interrupted rename by deleting the leftover source copy', () => {// A run that wrote the target but died before unlinking the source leaves// both files with identical bodies. The re-run must converge, not stall.@@ -271,6 +282,55 @@ describe('migration 224 up()', () => {expect((await readJson(productivityFile())).streaks.lastActiveWeek).toBe('2025-W52');});+ it('carries a whole rename chain without losing the digest in the middle', async () => {+ // 2018-W01 renames ONTO 2019-W01's current filename, while 2019-W01 itself+ // moves on to 2020-W01. Writing the first straight to its target would+ // destroy the second before its own copy was durable.+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2018-W01.json'), JSON.stringify(digestFixture('2018-W01', '2018-12-31', { summary: { totalTasks: 18 } })));+ await writeFile(join(digestsDir(), '2019-W01.json'), JSON.stringify(digestFixture('2019-W01', '2019-12-30', { summary: { totalTasks: 19 } })));++ await migration.up({ rootDir });++ expect((await readdir(digestsDir())).sort()).toEqual(['2019-W01.json', '2020-W01.json']);+ expect(await readJson(join(digestsDir(), '2019-W01.json'))).toMatchObject({ weekId: '2019-W01', summary: { totalTasks: 18 } });+ expect(await readJson(join(digestsDir(), '2020-W01.json'))).toMatchObject({ weekId: '2020-W01', summary: { totalTasks: 19 } });+ });++ it('promotes staged rewrites left by a run that died after staging completed', async () => {+ // Plan file present ⇒ every rewrite was durable, so the leftovers finish.+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2026-W01.json.staging-224'), JSON.stringify(digestFixture('2026-W01', '2025-12-29', { summary: { totalTasks: 42 } })));+ await writeFile(join(digestsDir(), '.migration-224-plan'), JSON.stringify({ migration: 224, files: ['2026-W01.json'] }));++ await migration.up({ rootDir });++ expect(await readJson(join(digestsDir(), '2026-W01.json'))).toMatchObject({ summary: { totalTasks: 42 } });+ expect((await readdir(digestsDir())).sort()).toEqual(['2026-W01.json']);+ });++ it('discards staged rewrites from a run that died BEFORE staging completed', async () => {+ // No plan file ⇒ the staged set is partial, so promoting it could overwrite+ // a live digest with half a plan. Drop it and leave the real files alone.+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2026-W01.json'), JSON.stringify(digestFixture('2026-W01', '2025-12-29', { summary: { totalTasks: 7 } })));+ await writeFile(join(digestsDir(), '2026-W01.json.staging-224'), JSON.stringify(digestFixture('2026-W01', '2025-12-29', { summary: { totalTasks: 999 } })));++ await migration.up({ rootDir });++ expect(await readJson(join(digestsDir(), '2026-W01.json'))).toMatchObject({ summary: { totalTasks: 7 } });+ expect((await readdir(digestsDir())).sort()).toEqual(['2026-W01.json']);+ });++ it('leaves no staging or plan files behind on a successful run', async () => {+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2025-W01.json'), JSON.stringify(digestFixture('2025-W01', '2025-12-29')));++ await migration.up({ rootDir });++ expect((await readdir(digestsDir())).sort()).toEqual(['2026-W01.json']);+ });+it('is idempotent — a second run changes nothing on disk', async () => {await mkdir(digestsDir(), { recursive: true });await writeFile(join(digestsDir(), '2025-W01.json'), JSON.stringify(digestFixture('2025-W01', '2025-12-29', { previousWeekId: '2025-W52' })));