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: harden migration 224's rename pass against DST, unreadable targets, and a partial run (#3465)
[._.]/ Adam Eivye5a7997a4251
diff --git a/scripts/migrations/224-iso-week-numbering-year-ids.js b/scripts/migrations/224-iso-week-numbering-year-ids.jsindex 9f13cde1d3..96f5c00391 100644--- a/scripts/migrations/224-iso-week-numbering-year-ids.js+++ b/scripts/migrations/224-iso-week-numbering-year-ids.js@@ -48,8 +48,6 @@ import { join } from 'path';import { atomicWrite } from '../../server/lib/fileUtils.js';import { getIsoWeekNumber, getWeekId, parseWeekId } from '../../server/lib/isoWeek.js';-const WEEK_MS = 7 * 24 * 60 * 60 * 1000;-/** The pre-#3465 id shape: ISO week number stamped with the CALENDAR year. */export function legacyWeekId(date) {return `${date.getFullYear()}-W${String(getIsoWeekNumber(date)).padStart(2, '0')}`;@@ -95,30 +93,55 @@ const readJsonOrNull = async (path) => {try { return JSON.parse(raw); } catch { return null; }};+/**+ * Everything about a digest EXCEPT the two id fields this migration rewrites.+ * Two records with the same body are the same digest, one of them a leftover+ * pre-rename copy — which is exactly what a run interrupted between its write+ * and its unlink leaves behind.+ */+const bodyKey = (digest) => {+ const { weekId, previousWeekId, ...body } = digest ?? {};+ return JSON.stringify(body);+};++/** The Monday one calendar week earlier — NOT `-7 * 24h`, which lands at 23:00 across a spring DST shift. */+const previousWeekStart = (weekStart) => {+ const prev = new Date(weekStart);+ prev.setDate(prev.getDate() - 7);+ return prev;+};+/*** Plan the digest rename set. Pure over already-read records — exported so the* test can assert the conflict rules without touching a filesystem.*- * @param {Array<{ file: string, digest: object }>} records+ * @param {Array<{ file: string, digest: object }>} records readable digests+ * @param {string[]} [occupied] filenames present in the directory that are NOT+ * in `records` (unparseable JSON, non-object bodies). They can't take part in+ * conflict resolution, so nothing may be renamed on top of them.* @returns {{ writes: Array<{ file: string, digest: object }>, deletes: string[], skipped: string[] }}*/-export function planDigestRewrite(records) {+export function planDigestRewrite(records, occupied = []) {+ const reserved = new Set(occupied);const claims = new Map(); // newFile -> candidate[]const skipped = [];+ const deletes = [];for (const { file, digest } of records) {const oldId = file.replace(/\.json$/, '');const newId = resolveNewWeekId(oldId, digest?.weekStart);if (!newId) { skipped.push(file); continue; }- const candidate = { file, digest, oldId, newId, newFile: `${newId}.json` };- if (!claims.has(candidate.newFile)) claims.set(candidate.newFile, []);- claims.get(candidate.newFile).push(candidate);+ const newFile = `${newId}.json`;+ // A name held by a file we could not read is not ours to overwrite.+ if (newFile !== file && reserved.has(newFile)) { skipped.push(file); continue; }+ if (!claims.has(newFile)) claims.set(newFile, []);+ claims.get(newFile).push({ file, digest, oldId, newId, newFile });}- // Two digests resolving to one name would clobber each other. Distinct weeks- // cannot collide under the new scheme, so this only fires on hand-edited or- // duplicated records — keep the most recently generated one and leave the- // others under their original names rather than deleting a real digest.+ // Two records resolving to one name would clobber each other. Distinct weeks+ // cannot collide under the new scheme, so this only fires on a duplicated or+ // hand-edited record — or on a re-run after a run that was interrupted+ // between its write and its unlink.const winners = [];for (const [, candidates] of claims) {if (candidates.length === 1) { winners.push(candidates[0]); continue; }@@ -132,8 +155,15 @@ export function planDigestRewrite(records) {if (at !== bt) return at < bt ? 1 : -1; // newest generatedAt firstreturn a.file < b.file ? -1 : 1;});- winners.push(sorted[0]);- for (const loser of sorted.slice(1)) skipped.push(loser.file);+ const [winner, ...losers] = sorted;+ winners.push(winner);+ for (const loser of losers) {+ // Same body as the winner ⇒ the winner IS this record, already renamed;+ // finish the interrupted rename. A different body is a real second+ // digest — leave its file alone rather than deleting user data.+ if (bodyKey(loser.digest) === bodyKey(winner.digest)) deletes.push(loser.file);+ else skipped.push(loser.file);+ }}const writes = [];@@ -141,9 +171,9 @@ export function planDigestRewrite(records) {const { digest, oldId, newId, newFile } = candidate;const next = { ...digest, weekId: newId };if (typeof digest?.previousWeekId === 'string') {- const prevStart = toDateHint(digest.weekStart);- const resolvedPrev = prevStart- ? getWeekId(new Date(prevStart.getTime() - WEEK_MS))+ const weekStart = toDateHint(digest.weekStart);+ const resolvedPrev = weekStart+ ? getWeekId(previousWeekStart(weekStart)): resolveNewWeekId(digest.previousWeekId, null);if (resolvedPrev) next.previousWeekId = resolvedPrev;}@@ -156,7 +186,9 @@ export function planDigestRewrite(records) {// Every name that survives the pass — winners' new names plus whatever we// left alone. Anything else was a rename source and is now redundant.const kept = new Set([...winners.map(w => w.newFile), ...skipped]);- const deletes = records.map(r => r.file).filter(f => !kept.has(f));+ for (const { file } of records) {+ if (!kept.has(file) && !deletes.includes(file)) deletes.push(file);+ }return { writes, deletes, skipped };}@@ -176,18 +208,26 @@ async function migrateDigests(rootDir) {// digest's current name, and reading up front means no pass ever reads a file// an earlier write already replaced.const records = [];+ const unreadable = [];for (const file of entries.filter(f => f.endsWith('.json')).sort()) {const digest = await readJsonOrNull(join(dir, file));if (digest && typeof digest === 'object' && !Array.isArray(digest)) records.push({ file, digest });+ else unreadable.push(file);}if (records.length === 0) {console.log('📊 migration 224: no readable digests — nothing to rename');return { renamed: 0, skipped: 0 };}- const { writes, deletes, skipped } = planDigestRewrite(records);+ const { writes, deletes, skipped } = planDigestRewrite(records, unreadable);for (const { file, digest } of writes) await atomicWrite(join(dir, file), digest);- for (const file of deletes) await unlink(join(dir, file)).catch(() => {});+ // 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+ // half-finished rename.+ for (const file of deletes) {+ await unlink(join(dir, 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 4c48c83f21..e5c0b02e11 100644--- a/scripts/migrations/224-iso-week-numbering-year-ids.test.js+++ b/scripts/migrations/224-iso-week-numbering-year-ids.test.js@@ -6,12 +6,19 @@ import { join } from 'path';import migration, { legacyWeekId, planDigestRewrite, resolveNewWeekId, toDateHint } from './224-iso-week-numbering-year-ids.js';const on = (year, month, day) => new Date(year, month - 1, day);+// Local midnight, serialized the way the service stores it. Built from LOCAL+// components (as the service does) so every expectation holds in any timezone —+// a bare `${ymd}T00:00:00.000Z` reads as the PREVIOUS day west of Greenwich.+const localMidnightIso = (ymd) => {+ const [year, month, day] = ymd.split('-').map(Number);+ return new Date(year, month - 1, day).toISOString();+};// A digest record with only the fields the migration reads. Values are// obviously-synthetic, not lifted from any real install.const digestFixture = (weekId, weekStart, extra = {}) => ({weekId,- generatedAt: `${weekStart}T18:00:00.000Z`,- weekStart: `${weekStart}T00:00:00.000Z`,+ generatedAt: localMidnightIso(weekStart),+ weekStart: localMidnightIso(weekStart),summary: { totalTasks: 1 },...extra,});@@ -118,6 +125,47 @@ describe('planDigestRewrite', () => {expect(skipped).toEqual(['2025-W52.json']);});+ it('steps previousWeekId back by a CALENDAR week, not 168 hours', () => {+ // Spring-forward week (Mon 2025-03-10 in a DST-observing zone): subtracting+ // 7 * 24h from a local-midnight weekStart lands on Sun 23:00, i.e. 2025-W09+ // — one week too far back.+ const dstWeek = { previousWeekId: '2025-W10' };++ // A correct record must not be rewritten at all.+ expect(planDigestRewrite([+ { file: '2025-W11.json', digest: digestFixture('2025-W11', '2025-03-10', dstWeek) },+ ]).writes).toEqual([]);++ // And when something else does force a rewrite, the value stays put.+ const { writes } = planDigestRewrite([+ { file: '2025-W11.json', digest: digestFixture('2025-W99', '2025-03-10', dstWeek) },+ ]);+ expect(writes[0].digest).toMatchObject({ weekId: '2025-W11', previousWeekId: '2025-W10' });+ });++ it('refuses to rename onto a name held by a digest it could not read', () => {+ const { writes, deletes, skipped } = planDigestRewrite(+ [{ file: '2025-W01.json', digest: digestFixture('2025-W01', '2025-12-29') }],+ ['2026-W01.json'],+ );+ expect(writes).toEqual([]);+ expect(deletes).toEqual([]);+ expect(skipped).toEqual(['2025-W01.json']);+ });++ 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.+ const body = digestFixture('2025-W01', '2025-12-29');+ const { writes, deletes, skipped } = planDigestRewrite([+ { file: '2025-W01.json', digest: body },+ { file: '2026-W01.json', digest: { ...body, weekId: '2026-W01' } },+ ]);+ expect(writes).toEqual([]);+ expect(deletes).toEqual(['2025-W01.json']);+ expect(skipped).toEqual([]);+ });+it('keeps one winner when two records claim the same new name, dropping neither file', () => {const stays = digestFixture('2026-W01', '2025-12-29');const moves = digestFixture('2025-W01', '2025-12-30');@@ -184,6 +232,17 @@ describe('migration 224 up()', () => {expect(await readFile(path, 'utf-8')).toBe(before);});+ it('does not rename over an unreadable file already sitting at the target name', async () => {+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2025-W01.json'), JSON.stringify(digestFixture('2025-W01', '2025-12-29')));+ await writeFile(join(digestsDir(), '2026-W01.json'), 'not json');++ await migration.up({ rootDir });++ expect(await readFile(join(digestsDir(), '2026-W01.json'), 'utf-8')).toBe('not json');+ expect(existsSync(join(digestsDir(), '2025-W01.json'))).toBe(true);+ });+it('skips an unreadable digest instead of throwing the boot migration run', async () => {await mkdir(digestsDir(), { recursive: true });await writeFile(join(digestsDir(), '2026-W25.json'), 'not json');