Files
elizaos--eliza/packages/scripts/cloud/admin/audit-migrations.ts
T
wehub-resource-sync 426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

206 lines
6.0 KiB
TypeScript

/**
* Migration Audit Script
*
* WHY THIS EXISTS:
* Drizzle ORM tracks migrations via a journal file (_journal.json) and the
* __drizzle_migrations table in the database. When migrations are created
* manually (outside of db:generate) or the journal gets out of sync, it becomes
* unclear which migrations have actually been applied to production.
*
* This script provides visibility into:
* 1. Migration files on disk vs what's tracked in the journal
* 2. Duplicate migration numbers (common when mixing manual + auto-generated)
* 3. Missing migration numbers (gaps in sequence)
* 4. What's actually applied in the database (when connected)
*
* Use this script before and after migration consolidation to verify state.
*
* Usage: DATABASE_URL=... bun run packages/scripts/audit-migrations.ts
*/
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { enforceTlsForRemote } from "@elizaos/cloud-shared/db/client";
import pg from "pg";
const { Client } = pg;
interface JournalEntry {
idx: number;
version: string;
when: number;
tag: string;
breakpoints: boolean;
}
interface Journal {
version: string;
dialect: string;
entries: JournalEntry[];
}
interface DrizzleMigration {
id: number;
hash: string;
created_at: string;
}
async function getJournalEntries(): Promise<Journal> {
const journalPath = path.join(
process.cwd(),
"packages/cloud/shared/src/db/migrations/meta/_journal.json",
);
const content = await readFile(journalPath, "utf-8");
return JSON.parse(content) as Journal;
}
async function getMigrationFiles(): Promise<string[]> {
const migrationsDir = path.join(
process.cwd(),
"packages/cloud/shared/src/db/migrations",
);
const files = await readdir(migrationsDir);
return files
.filter((f) => f.endsWith(".sql"))
.sort((a, b) => {
const numA = parseInt(a.split("_")[0] ?? "0", 10);
const numB = parseInt(b.split("_")[0] ?? "0", 10);
return numA - numB;
});
}
async function getAppliedMigrations(
client: pg.Client,
): Promise<DrizzleMigration[]> {
const result = await client.query<DrizzleMigration>(
'SELECT * FROM "__drizzle_migrations" ORDER BY id',
);
return result.rows;
}
async function main() {
console.log("\n=== Migration Audit Report ===\n");
const journal = await getJournalEntries();
const migrationFiles = await getMigrationFiles();
console.log("📁 MIGRATION FILES:");
console.log(` Total SQL files: ${migrationFiles.length}`);
const filesByNumber = new Map<string, string[]>();
for (const file of migrationFiles) {
const num = file.split("_")[0] ?? "";
const existing = filesByNumber.get(num) ?? [];
existing.push(file);
filesByNumber.set(num, existing);
}
const duplicates = Array.from(filesByNumber.entries()).filter(
([, files]) => files.length > 1,
);
if (duplicates.length > 0) {
console.log("\n ⚠️ DUPLICATE MIGRATION NUMBERS:");
for (const [num, files] of duplicates) {
console.log(` ${num}:`);
for (const file of files) {
console.log(` - ${file}`);
}
}
}
const allNumbers = Array.from(filesByNumber.keys())
.map((n) => parseInt(n, 10))
.sort((a, b) => a - b);
const gaps: number[] = [];
for (let i = 0; i < allNumbers.length - 1; i++) {
const current = allNumbers[i]!;
const next = allNumbers[i + 1]!;
for (let j = current + 1; j < next; j++) {
gaps.push(j);
}
}
if (gaps.length > 0) {
console.log(`\n ⚠️ MISSING MIGRATION NUMBERS: ${gaps.join(", ")}`);
}
console.log("\n📋 JOURNAL STATE:");
console.log(` Tracked migrations: ${journal.entries.length}`);
console.log(" Entries:");
for (const entry of journal.entries) {
console.log(` ${entry.idx}: ${entry.tag}`);
}
const trackedFiles = new Set(journal.entries.map((e) => `${e.tag}.sql`));
const untrackedFiles = migrationFiles.filter((f) => !trackedFiles.has(f));
if (untrackedFiles.length > 0) {
console.log(`\n ⚠️ UNTRACKED FILES (${untrackedFiles.length}):`);
for (const file of untrackedFiles) {
console.log(` - ${file}`);
}
}
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl) {
console.log("\n📊 DATABASE STATE:");
console.log(" ⚠️ DATABASE_URL not set - skipping database check");
console.log(" Set DATABASE_URL to check applied migrations");
return;
}
console.log("\n📊 DATABASE STATE:");
const { url: clientUrl, ssl: clientSsl } = enforceTlsForRemote(databaseUrl);
const client = new Client({
connectionString: clientUrl,
...(clientSsl ? { ssl: clientSsl } : {}),
});
try {
await client.connect();
const tableCheck = await client.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = '__drizzle_migrations'
)
`);
if (!tableCheck.rows[0]?.exists) {
console.log(" ⚠️ __drizzle_migrations table does not exist");
console.log(
" This database has never had migrations applied via Drizzle",
);
return;
}
const appliedMigrations = await getAppliedMigrations(client);
console.log(` Applied migrations: ${appliedMigrations.length}`);
console.log(" Entries:");
for (const migration of appliedMigrations) {
console.log(
` ${migration.id}: ${migration.hash} (${migration.created_at})`,
);
}
console.log("\n📈 COMPARISON:");
console.log(` Journal entries: ${journal.entries.length}`);
console.log(` Applied in DB: ${appliedMigrations.length}`);
console.log(` SQL files on disk: ${migrationFiles.length}`);
if (journal.entries.length !== appliedMigrations.length) {
console.log(
"\n ⚠️ MISMATCH between journal entries and applied migrations!",
);
}
} catch (error) {
console.log(` ❌ Error connecting to database: ${error}`);
} finally {
await client.end();
}
console.log("\n=== Audit Complete ===\n");
}
main();