import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import { join } from 'node:path'; import { newFixture, type Fixture } from '../helpers/fixture.js'; let fixture: Fixture; beforeEach(async () => { vi.resetModules(); fixture = await newFixture(['t5_zombie_theater_1']); delete process.env.KOMODO_ADDRESS; delete process.env.RCON_PASSWORD; // Ensure the three per-kind destinations exist under the fixture tree. await mkdir(join(fixture.t5, 't5_zombie_theater_1', 'runtime/plutonium/storage/t5/raw/scripts/sp'), { recursive: true }); await mkdir(join(fixture.t5, 't5_zombie_theater_1', 'configs'), { recursive: true }); await mkdir(join(fixture.t5, 't5_zombie_theater_1', 'runtime/plutonium/plugins'), { recursive: true }); }); afterEach(async () => { await fixture.cleanup(); }); describe('drift scanning', () => { it('replaces a seeded config once instead of planning both removal and installation', async () => { const { seedServerRegistry } = await import('../../src/lib/server/fleet/servers.js'); const { createScript } = await import('../../src/lib/server/fleet/scripts.js'); const { scanServerDrift, runDriftDeployment } = await import('../../src/lib/server/fleet/drift.js'); const { db } = await import('../../src/lib/server/db/index.js'); const { getPromotedServerConfig } = await import('../../src/lib/server/fleet/server-config.js'); await seedServerRegistry(); const server = 't5_zombie_theater_1'; const { script, version } = createScript({ name: 'baseline', kind: 'baseline', scopeType: 'game', scopeValue: 't5', content: Buffer.from('set sv_voice "1"\n') }); db().prepare('UPDATE scripts SET current_version_id = ? WHERE id = ?').run(version.id, script.id); const path = join(fixture.t5, server, 'configs', 'dedicated_sp.cfg'); await writeFile(path, 'seeded config'); expect(await scanServerDrift(server)).toEqual([expect.objectContaining({ kind: 'config', driftKind: 'replace' })]); expect(await runDriftDeployment({ servers: [server] })).toMatchObject({ totalRemoved: 0, totalRestored: 1 }); expect(await readFile(path)).toEqual(getPromotedServerConfig('t5', 'zombie_theater')); expect(await scanServerDrift(server)).toEqual([]); }); it.each(['identical', 'different'])('reconciles an existing %s scoped file in one pass with an update audit', async (mode) => { const { seedServerRegistry } = await import('../../src/lib/server/fleet/servers.js'); const { createScript } = await import('../../src/lib/server/fleet/scripts.js'); const { scanServerDrift, runDriftDeployment } = await import('../../src/lib/server/fleet/drift.js'); const { getServerScript } = await import('../../src/lib/server/fleet/inventory.js'); const { db } = await import('../../src/lib/server/db/index.js'); const { destOfKind } = await import('../../src/lib/server/config.js'); await seedServerRegistry(); const server = 't5_zombie_theater_1'; const content = Buffer.from('main(){}\n'); const before = mode === 'identical' ? content : Buffer.from('old bytes'); const { script, version } = createScript({ name: 'spawn fix', kind: 'script', scopeType: 'game', scopeValue: 't5', targetRelPath: 'zm_spawn_fix.gsc', content }); db().prepare('UPDATE scripts SET current_version_id = ? WHERE id = ?').run(version.id, script.id); const target = join(destOfKind(server, 'script'), 'zm_spawn_fix.gsc'); await writeFile(target, before); expect(await scanServerDrift(server)).toEqual([expect.objectContaining({ relPath: 'zm_spawn_fix.gsc', driftKind: 'replace' })]); expect(await runDriftDeployment({ servers: [server], dryRun: true })).toMatchObject({ totalRemoved: 0, totalRestored: 1, deploymentId: null }); expect(await readFile(target)).toEqual(before); expect(getServerScript(server, 'zm_spawn_fix.gsc')).toBeUndefined(); const result = await runDriftDeployment({ servers: [server] }); expect(result).toMatchObject({ totalRemoved: 0, totalRestored: 1 }); expect(await readFile(target)).toEqual(content); expect(getServerScript(server, 'zm_spawn_fix.gsc')?.script_version_id).toBe(version.id); expect(db().prepare('SELECT verb, content_before, content_after FROM deployment_files WHERE deployment_id = ?').all(result.deploymentId)) .toEqual([{ verb: 'updated', content_before: before, content_after: content }]); expect(await scanServerDrift(server)).toEqual([]); expect((await runDriftDeployment({ servers: [server] })).deploymentId).toBeNull(); }); it('detects untracked files across script, config, and plugin destinations', async () => { const { seedServerRegistry } = await import('../../src/lib/server/fleet/servers.js'); const { scanServerDrift } = await import('../../src/lib/server/fleet/drift.js'); await seedServerRegistry(); // Drop one stray file in each managed destination. const server = 't5_zombie_theater_1'; await writeFile( join(fixture.t5, server, 'runtime/plutonium/storage/t5/raw/scripts/sp', 'stray.gsc'), 'main(){}\n' ); await writeFile( join(fixture.t5, server, 'configs', 'stray.cfg'), 'set foo "bar"\n' ); await writeFile( join(fixture.t5, server, 'runtime/plutonium/plugins', 'stray.dll'), Buffer.from([0xde, 0xad]) ); const drift = await scanServerDrift(server); const untracked = drift.filter((d) => d.driftKind === 'untracked'); const byKind = Object.fromEntries(untracked.map((d) => [d.kind, d.relPath])); expect(byKind.script).toBe('stray.gsc'); expect(byKind.config).toBe('stray.cfg'); expect(byKind.plugin).toBe('stray.dll'); expect(untracked.length).toBe(3); }); }); // Deploys a promoted artifact to a scope-matching server, then deletes it // off disk so drift's "missing" pass has something to find. async function promoteAndOrphan( createScript: (i: { name: string; kind: 'script' | 'plugin' | 'baseline' | 'config'; scopeType?: 'game' | 'map'; scopeValue?: string; targetRelPath?: string; content: Buffer; }) => { script: { id: number }; version: { id: number } }, getLatestVersion: (id: number) => { id: number } | undefined, openBeta: (i: { scripts: Array<{ scriptId: number; scriptVersionId: number }>; servers: string[]; waitForHealth: boolean; waitForMatch: boolean; }) => Promise<{ betaId: number }>, promoteBeta: (id: number) => Promise, db: () => { prepare: (q: string) => { run: (...args: unknown[]) => unknown } } ): Promise<{ scriptId: number }> { const created = createScript({ name: 't5 hud', kind: 'script', scopeType: 'game', scopeValue: 't5', targetRelPath: 'hud.gsc', content: Buffer.from('main(){}\n') }); const ver = getLatestVersion(created.script.id)!; const { betaId } = await openBeta({ scripts: [{ scriptId: created.script.id, scriptVersionId: ver.id }], servers: ['t5_zombie_theater_1'], waitForHealth: false, waitForMatch: false }); db().prepare( `UPDATE beta_servers SET stage = 'ready', restarted_at = ? WHERE beta_id = ?` ).run(new Date().toISOString(), betaId); db().prepare(`UPDATE betas SET state = 'ready-promote' WHERE id = ?`).run(betaId); await promoteBeta(betaId); return { scriptId: created.script.id }; } describe('missing artifact detection', () => { it('flags a promoted script that is absent on a scope-matching server as missing, then restores it on reconcile', async () => { const { seedServerRegistry } = await import('../../src/lib/server/fleet/servers.js'); const { createScript, getLatestVersion } = await import( '../../src/lib/server/fleet/scripts.js' ); const { openBeta, promoteBeta } = await import( '../../src/lib/server/fleet/beta.js' ); const { scanServerDrift, runDriftDeployment } = await import( '../../src/lib/server/fleet/drift.js' ); const { db } = await import('../../src/lib/server/db/index.js'); await seedServerRegistry(); await promoteAndOrphan( createScript as never, getLatestVersion as never, openBeta as never, promoteBeta as never, db as never ); const targetPath = join( fixture.t5, 't5_zombie_theater_1', 'runtime/plutonium/storage/t5/raw/scripts/sp', 'hud.gsc' ); // Sanity check: promoted script lands on disk. expect(existsSync(targetPath)).toBe(true); // Simulate someone deleting the file out-of-band. await rm(targetPath, { force: true }); const drift = await scanServerDrift('t5_zombie_theater_1'); const missing = drift.filter((d) => d.driftKind === 'missing' && d.kind === 'script'); expect(missing.length).toBe(1); expect(missing[0].relPath).toBe('hud.gsc'); const result = await runDriftDeployment({ servers: ['t5_zombie_theater_1'], dryRun: false, triggeredBy: 'ui' }); expect(result.totalRestored).toBeGreaterThanOrEqual(1); expect(existsSync(targetPath)).toBe(true); const restored = await readFile(targetPath); expect(restored.toString()).toBe('main(){}\n'); }); it('flags a scope-matching server whose composed dedicated_sp.cfg is missing', async () => { const { seedServerRegistry } = await import('../../src/lib/server/fleet/servers.js'); const { createScript, getLatestVersion } = await import( '../../src/lib/server/fleet/scripts.js' ); const { openBeta, promoteBeta } = await import( '../../src/lib/server/fleet/beta.js' ); const { scanServerDrift } = await import('../../src/lib/server/fleet/drift.js'); const { db } = await import('../../src/lib/server/db/index.js'); await seedServerRegistry(); const baseline = createScript({ name: 't5 baseline', kind: 'baseline', scopeType: 'game', scopeValue: 't5', content: Buffer.from('set g_inactivity "190"\n') }); const bVer = getLatestVersion(baseline.script.id)!; const { betaId } = await openBeta({ scripts: [{ scriptId: baseline.script.id, scriptVersionId: bVer.id }], servers: ['t5_zombie_theater_1'], waitForHealth: false, waitForMatch: false }); db().prepare( `UPDATE beta_servers SET stage = 'ready', restarted_at = ? WHERE beta_id = ?` ).run(new Date().toISOString(), betaId); db().prepare(`UPDATE betas SET state = 'ready-promote' WHERE id = ?`).run(betaId); await promoteBeta(betaId); const cfgPath = join(fixture.t5, 't5_zombie_theater_1', 'configs', 'dedicated_sp.cfg'); expect(existsSync(cfgPath)).toBe(true); await rm(cfgPath, { force: true }); const drift = await scanServerDrift('t5_zombie_theater_1'); const missingCfg = drift.filter((d) => d.driftKind === 'missing' && d.kind === 'config'); expect(missingCfg.length).toBe(1); expect(missingCfg[0].relPath).toBe('dedicated_sp.cfg'); }); });