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
address review (codex): fail migration 001 on an unreadable accounts file instead of skipping
[._.]/ Adam Eivy35afe4edd97a
diff --git a/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.js b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.jsindex ac25f42cc3..70fc94e21b 100644--- a/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.js+++ b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.js@@ -18,16 +18,44 @@* Idempotent by construction (the `EXISTS` gate means a second run matches nothing),* and recorded in `schema_migrations` so it only runs once anyway.*/+import { readFile } from 'fs/promises';import { join } from 'path';-import { PATHS, safeJSONParse, tryReadFile } from '../../lib/fileUtils.js';+import { PATHS } from '../../lib/fileUtils.js';import { isPlainObject } from '../../lib/objects.js';import { stripParticipantsForAccount } from '../../services/humanActivity.js';+// Repo-relative label for error messages — never interpolate the absolute path,+// which embeds the OS username.+const ACCOUNTS_LABEL = 'data/messages/accounts.json';+export async function up(client) {- const content = await tryReadFile(join(PATHS.messages, 'accounts.json'));- if (!content) return; // no message accounts on this install — nothing to repair- const parsed = safeJSONParse(content, {}, { context: 'migration-001-send-as-aliases' });- if (!isPlainObject(parsed)) return;+ // Read WITHOUT the usual `tryReadFile`/`safeJSONParse` swallowing: those collapse+ // "file absent" and "read/parse FAILED" into the same empty result, and here the+ // difference is permanent. This migration is recorded in `schema_migrations` the+ // moment `up()` returns normally, so a transient unreadable/corrupt accounts file+ // would mark the one-shot backfill done and it would never run — and the sync-time+ // delta can't cover for it either (those aliases are already stored, so the delta+ // is empty forever). Only a genuinely absent file means "no work"; any other+ // failure throws, which rolls the migration back UNAPPLIED so the next boot+ // retries it. (try/catch is sanctioned here — this runs at boot, outside the+ // Express request lifecycle.)+ let content;+ try {+ content = await readFile(join(PATHS.messages, 'accounts.json'), 'utf8');+ } catch (err) {+ if (err?.code === 'ENOENT') return; // no message accounts on this install — nothing to repair+ throw new Error(`migration 001: cannot read ${ACCOUNTS_LABEL} (${err?.code || 'read error'}) — refusing to mark the send-as-alias backfill applied: ${err.message}`);+ }++ let parsed;+ try {+ parsed = JSON.parse(content);+ } catch (err) {+ throw new Error(`migration 001: ${ACCOUNTS_LABEL} is not valid JSON — refusing to mark the send-as-alias backfill applied: ${err.message}`);+ }+ if (!isPlainObject(parsed)) {+ throw new Error(`migration 001: ${ACCOUNTS_LABEL} did not contain an account map — refusing to mark the send-as-alias backfill applied.`);+ }let repaired = 0;for (const account of Object.values(parsed)) {diff --git a/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.test.js b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.test.jsindex 77a2838e21..3d31659344 100644--- a/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.test.js+++ b/server/scripts/db-migrations/001-strip-send-as-aliases-from-activity-participants.test.js@@ -1,19 +1,31 @@/*** Tests for migration 001 (#2855) — no live DB: the pg transaction client is a* stub that records the statements the migration issues, and the accounts file- * is mocked. Asserts the migration reads each account's ALREADY-stored send-as- * aliases and issues the scoped repair on the supplied transaction client (the- * gap the sync-path delta trigger can't close, since the set never changes again- * on an install that learned it under an earlier build).+ * read is mocked. Asserts the migration reads each account's ALREADY-stored+ * send-as aliases and issues the scoped repair on the supplied transaction client+ * (the gap the sync-path delta trigger can't close, since the set never changes+ * again on an install that learned it under an earlier build).+ *+ * Also pins the absent-vs-failed distinction: the runner records this migration+ * as applied the moment `up()` returns, so a swallowed read failure would mark+ * the one-shot backfill done and it could never run again. Only ENOENT is "no+ * work"; every other failure must throw so the migration rolls back unapplied.** `*.test.js` files in this directory are ignored by the migration runner.*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi } from 'vitest';++// Each test sets its own readFile implementation, and the client stub is rebuilt+// per test, so no beforeEach reset is needed — and adding one is actively harmful:+// under vitest 4, clearing this factory-created mock makes the errors its+// implementation throws surface as unhandled test failures even though up()+// catches them.+const readFile = vi.fn();+vi.mock('fs/promises', () => ({ readFile }));-const tryReadFile = vi.fn();vi.mock('../../lib/fileUtils.js', () => ({- tryReadFile,PATHS: { messages: '/mock/data/messages', data: '/mock/data' },+ tryReadFile: vi.fn(),safeJSONParse: (content, fallback) => { try { return JSON.parse(content); } catch { return fallback; } },ensureDir: vi.fn(),atomicWrite: vi.fn(),@@ -26,13 +38,12 @@ const makeClient = () => {return { calls, query: (sql, params) => { calls.push({ sql, params }); return Promise.resolve({ rowCount: 1 }); } };};-const accountsFile = (accounts) => JSON.stringify(accounts);+const enoent = () => Object.assign(new Error('no such file'), { code: 'ENOENT' });+const ioError = () => Object.assign(new Error('permission denied'), { code: 'EACCES' });describe('migration 001 — strip send-as aliases from activity participants (#2855)', () => {- beforeEach(() => tryReadFile.mockReset());-it('repairs each account that already has stored aliases, scoped by id + type', async () => {- tryReadFile.mockResolvedValue(accountsFile({+ readFile.mockResolvedValue(JSON.stringify({a: { id: 'acct-a', type: 'gmail', sendAsAliases: ['[email protected]'] },b: { id: 'acct-b', type: 'outlook', sendAsAliases: ['[email protected]', '[email protected]'] },}));@@ -45,8 +56,8 @@ describe('migration 001 — strip send-as aliases from activity participants (#2expect(client.calls[0].sql).toContain('UPDATE human_activity_events');});- it('skips accounts with no aliases, no id, or a non-Gmail account that never learned any', async () => {- tryReadFile.mockResolvedValue(accountsFile({+ it('skips accounts with no aliases, no id, or one that never learned any', async () => {+ readFile.mockResolvedValue(JSON.stringify({a: { id: 'acct-a', type: 'gmail', sendAsAliases: [] },b: { id: 'acct-b', type: 'outlook' },c: { type: 'gmail', sendAsAliases: ['[email protected]'] }, // no id — unscopeable@@ -56,19 +67,36 @@ describe('migration 001 — strip send-as aliases from activity participants (#2expect(client.calls).toHaveLength(0);});- it('is a no-op on an install with no message accounts file', async () => {- tryReadFile.mockResolvedValue(null);+ it('is a no-op on an install with no message accounts file (ENOENT is genuine "no work")', async () => {+ readFile.mockImplementation(() => { throw enoent(); });const client = makeClient();- await up(client);+ await expect(up(client)).resolves.toBeUndefined();expect(client.calls).toHaveLength(0);});- it('is a no-op when the accounts file is corrupt or not an object', async () => {- const client = makeClient();- tryReadFile.mockResolvedValue('{ not json');- await up(client);- tryReadFile.mockResolvedValue('[]');- await up(client);- expect(client.calls).toHaveLength(0);+ // The three cases below MUST throw. Returning normally would let the runner+ // record the migration as applied, permanently skipping the one-shot backfill —+ // and the sync-time delta can't recover it, because those aliases are already+ // stored so the delta is empty forever.+ it('throws when the accounts file exists but cannot be read, so the migration retries next boot', async () => {+ readFile.mockImplementation(() => { throw ioError(); });+ await expect(up(makeClient())).rejects.toThrow(/cannot read data\/messages\/accounts\.json/);+ });++ it('throws when the accounts file is malformed JSON', async () => {+ readFile.mockResolvedValue('{ not json');+ await expect(up(makeClient())).rejects.toThrow(/not valid JSON/);+ });++ it('throws when the accounts file parses to a non-object', async () => {+ readFile.mockResolvedValue('[]');+ await expect(up(makeClient())).rejects.toThrow(/did not contain an account map/);+ });++ it('never leaks the absolute accounts path (which embeds the OS username) into an error', async () => {+ readFile.mockImplementation(() => { throw ioError(); });+ const err = await up(makeClient()).catch((e) => e);+ expect(err.message).not.toContain('/mock/data/messages');+ expect(err.message).toContain('data/messages/accounts.json');});});