diff --git a/scripts/__tests__/cutover.test.ts b/scripts/__tests__/cutover.test.ts index ef360bab..138cd631 100644 --- a/scripts/__tests__/cutover.test.ts +++ b/scripts/__tests__/cutover.test.ts @@ -1,4 +1,6 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +afterEach(() => vi.unstubAllEnvs()); // ─── Mock PrismaClient ────────────────────────────────────────────────────── @@ -112,7 +114,8 @@ describe('validate-quality', () => { id: `msg-${i}`, ticketId: `ticket-${i}`, author: 'outpost-shadow', - content: "I'm not sure about this. I don't know the answer. Unfortunately I cannot help.", + content: + "I'm not sure about this. I don't know the answer. Unfortunately I cannot help.", type: 'NOTE', isAiGenerated: true, attachments: { @@ -179,7 +182,7 @@ describe('execute-cutover', () => { prisma.ticket.count .mockResolvedValueOnce(150) // total .mockResolvedValueOnce(100) // discord - .mockResolvedValueOnce(50); // orca + .mockResolvedValueOnce(50); // orca const result = await verifyTicketData(prisma as never); @@ -222,6 +225,42 @@ describe('execute-cutover', () => { expect(log.steps.length).toBeGreaterThanOrEqual(4); }); + it.each(['true', 'TRUE', '1', 'yes', 'on', ' true ', '', 'flase'])( + 'stops before announcement when shadow mode is unresolved (%j)', + async (value) => { + vi.stubEnv('SHADOW_MODE', value); + const log = await executeCutover(makePrismaMock() as never, { + confirm: true, + skipQualityCheck: true, + announcement: 'Test', + }); + expect(log.outcome).toBe('FAILED'); + expect(log.steps.at(-1)?.message).toContain(`SHADOW_MODE=${value}`); + expect(log.steps.some((step) => step.step === 'Post announcement')).toBe(false); + }, + ); + + it('stops when the shadow-mode variable is absent', async () => { + vi.stubEnv('SHADOW_MODE', undefined); + const log = await executeCutover(makePrismaMock() as never, { + confirm: true, + skipQualityCheck: true, + announcement: 'Test', + }); + expect(log.outcome).toBe('FAILED'); + expect(log.steps.at(-1)?.message).toContain('SHADOW_MODE=unset'); + }); + + it('proceeds when shadow mode is explicitly off', async () => { + vi.stubEnv('SHADOW_MODE', 'false'); + const log = await executeCutover(makePrismaMock() as never, { + confirm: true, + skipQualityCheck: true, + announcement: 'Test', + }); + expect(log.outcome).toBe('SUCCESS'); + }); + it('aborts on health check failure', async () => { const prisma = makePrismaMock(); prisma.$queryRaw.mockRejectedValue(new Error('Connection refused')); @@ -257,6 +296,7 @@ describe('rollback', () => { }); it('completes successfully in confirm mode', async () => { + vi.stubEnv('SHADOW_MODE', 'true'); const prisma = makePrismaMock(); const log = await executeRollback(prisma as never, { @@ -268,6 +308,30 @@ describe('rollback', () => { expect(log.confirm).toBe(true); }); + it.each(['false', '', 'TRUE', 'flase'])( + 'stops before notifying the team when shadow mode is unresolved (%j)', + async (value) => { + vi.stubEnv('SHADOW_MODE', value); + const log = await executeRollback(makePrismaMock() as never, { + confirm: true, + reason: 'Emergency', + }); + expect(log.outcome).toBe('FAILED'); + expect(log.steps.at(-1)?.message).toContain(`SHADOW_MODE=${value}`); + expect(log.steps.some((step) => step.step === 'Notify team')).toBe(false); + }, + ); + + it('fails when the shadow-mode variable is absent', async () => { + vi.stubEnv('SHADOW_MODE', undefined); + const log = await executeRollback(makePrismaMock() as never, { + confirm: true, + reason: 'Emergency', + }); + expect(log.outcome).toBe('FAILED'); + expect(log.steps.at(-1)?.message).toContain('SHADOW_MODE=unset'); + }); + it('fails if database integrity check fails', async () => { const prisma = makePrismaMock(); prisma.$queryRaw.mockRejectedValue(new Error('Connection refused')); @@ -282,6 +346,7 @@ describe('rollback', () => { }); it('preserves ticket data during rollback', async () => { + vi.stubEnv('SHADOW_MODE', 'true'); const prisma = makePrismaMock(); prisma.ticket.count.mockResolvedValue(200); @@ -292,7 +357,7 @@ describe('rollback', () => { expect(log.outcome).toBe('SUCCESS'); // Database integrity step should report ticket count - const dbStep = log.steps.find(s => s.step === 'Verify database integrity'); + const dbStep = log.steps.find((s) => s.step === 'Verify database integrity'); expect(dbStep?.message).toContain('200'); }); }); diff --git a/scripts/cutover/README.md b/scripts/cutover/README.md index 79f46ad8..af341ddf 100644 --- a/scripts/cutover/README.md +++ b/scripts/cutover/README.md @@ -8,10 +8,10 @@ Before starting the parallel run, verify: - [ ] **Database migrated** — `npx tsx scripts/migrate-from-orca.ts` completed successfully - [ ] **Environment variables set** on Railway for all services: - - `DATABASE_URL`, `DISCORD_TOKEN`, `DISCORD_CLIENT_ID`, `GUILD_ID` - - `MONITORED_CHANNEL_IDS` (comma-separated forum channel IDs) - - `ANTHROPIC_API_KEY` (for AI responses) - - `SHADOW_MODE=true` (critical — prevents double-posting) + - `DATABASE_URL`, `DISCORD_TOKEN`, `DISCORD_CLIENT_ID`, `GUILD_ID` + - `MONITORED_CHANNEL_IDS` (comma-separated forum channel IDs) + - `ANTHROPIC_API_KEY` (for AI responses) + - `SHADOW_MODE=true` (critical — prevents double-posting) - [ ] **Railway services deployed** — `outpost-web`, `outpost-discord-bot`, `outpost-github-app` - [ ] **Discord bot connected** — bot is online in the server with correct permissions - [ ] **GitHub app installed** — if using GitHub integration for issue tracking @@ -46,6 +46,7 @@ npx tsx scripts/cutover/validate-quality.ts --since 2024-01-15 # filter by date ``` The script compares: + - **Response time**: Outpost vs Orca response latency - **Content quality**: response length, code blocks, links - **Confidence distribution**: percentage of high/medium/low confidence responses @@ -58,12 +59,12 @@ Target: run for **48-72 hours** with at least 20 shadow responses before proceed The cutover script checks these targets automatically: -| Metric | Target | -|--------|--------| -| Shadow responses collected | >= 20 | -| Average response time | < 10 minutes | -| Response length vs Orca | >= 50% of Orca average | -| Low confidence rate | < 20% | +| Metric | Target | +| -------------------------- | ---------------------- | +| Shadow responses collected | >= 20 | +| Average response time | < 10 minutes | +| Response length vs Orca | >= 50% of Orca average | +| Low confidence rate | < 20% | ### Run Validation @@ -85,14 +86,19 @@ This validates all prerequisites without making changes. ### Execute Cutover +Set `SHADOW_MODE=false` in Railway and redeploy `discord-bot`. The script does not call the Railway API; it checks the invoking shell's `SHADOW_MODE` as the operator's attestation that the deployed value is correct. Run: + ```bash -npx tsx scripts/cutover/execute-cutover.ts --confirm +SHADOW_MODE=false npx tsx scripts/cutover/execute-cutover.ts --confirm ``` +The script fails closed when `SHADOW_MODE` is unset or is not exactly `false` in that shell. + The script: + 1. Verifies all health checks pass 2. Validates shadow mode quality metrics -3. Disables shadow mode (`SHADOW_MODE=false`) +3. Verifies the local `SHADOW_MODE=false` attestation 4. Posts upgrade announcement in support channels ### Post-Cutover @@ -114,13 +120,18 @@ npx tsx scripts/cutover/rollback.ts ### Execute Rollback +Set `SHADOW_MODE=true` in Railway and redeploy `discord-bot`. Then attest the deployed value in the invoking shell: + ```bash -npx tsx scripts/cutover/rollback.ts --confirm --reason "Response quality degradation" +SHADOW_MODE=true npx tsx scripts/cutover/rollback.ts --confirm --reason "Response quality degradation" ``` +The script fails closed when `SHADOW_MODE` is unset or is not exactly `true` in that shell. + The rollback script: + 1. Verifies database integrity (ticket data is preserved) -2. Re-enables shadow mode (`SHADOW_MODE=true`) +2. Verifies the local `SHADOW_MODE=true` attestation 3. Logs the rollback event for audit trail 4. Prints manual steps: re-enable Orca bot, verify it's responding diff --git a/scripts/cutover/execute-cutover.ts b/scripts/cutover/execute-cutover.ts index 4ff2867d..744c80b7 100644 --- a/scripts/cutover/execute-cutover.ts +++ b/scripts/cutover/execute-cutover.ts @@ -40,7 +40,7 @@ function parseArgs(argv: string[]): CliArgs { skipQualityCheck: false, announcement: "We've upgraded our support bot to provide faster, more accurate responses. " + - "If you notice any issues, please let us know!", + 'If you notice any issues, please let us know!', }; for (let i = 2; i < argv.length; i++) { @@ -63,9 +63,7 @@ function parseArgs(argv: string[]): CliArgs { // ─── Step Execution ───────────────────────────────────────────────────────── function logStep(result: StepResult): void { - const icon = result.status === 'PASS' ? '[OK]' - : result.status === 'FAIL' ? '[FAIL]' - : '[SKIP]'; + const icon = result.status === 'PASS' ? '[OK]' : result.status === 'FAIL' ? '[FAIL]' : '[SKIP]'; console.log(` ${icon} ${result.step}: ${result.message}`); } @@ -76,13 +74,8 @@ export async function runHealthChecks(prisma: PrismaClient): Promise await prisma.$queryRaw`SELECT 1`; // Verify required env vars are set - const required = [ - 'DATABASE_URL', - 'DISCORD_TOKEN', - 'DISCORD_CLIENT_ID', - 'GUILD_ID', - ]; - const missing = required.filter(k => !process.env[k]); + const required = ['DATABASE_URL', 'DISCORD_TOKEN', 'DISCORD_CLIENT_ID', 'GUILD_ID']; + const missing = required.filter((k) => !process.env[k]); if (missing.length > 0) { return { step, @@ -161,30 +154,34 @@ export async function disableShadowMode(confirm: boolean): Promise { return { step, status: 'SKIP', - message: 'Dry run — would set SHADOW_MODE=false on Railway', + message: 'Dry run — would verify the SHADOW_MODE=false attestation', timestamp: new Date(), }; } // In a real deployment, this would call the Railway API to update env vars. - // For now, we verify the current state and log the instruction. + // For now, the invoking shell's value is the operator's attestation. const currentValue = process.env.SHADOW_MODE; - if (currentValue !== 'true') { + if (currentValue === 'false') { return { step, status: 'PASS', - message: `Shadow mode already disabled (SHADOW_MODE=${currentValue ?? 'unset'})`, + message: + 'SHADOW_MODE=false is set in this process. Treat that as local attestation only, and verify the deployed services were redeployed with the same value before continuing.', timestamp: new Date(), }; } console.log(' ACTION REQUIRED: Set SHADOW_MODE=false in Railway environment variables'); console.log(' Then redeploy the discord-bot service.'); + console.log( + ' Finally, export SHADOW_MODE=false in the shell running this script before rerunning --confirm.', + ); return { step, - status: 'PASS', - message: 'Shadow mode disable instruction issued', + status: 'FAIL', + message: `Shadow mode is not confirmed off in this process (SHADOW_MODE=${currentValue ?? 'unset'}). Set SHADOW_MODE=false in Railway, redeploy discord-bot, export SHADOW_MODE=false in this shell, and rerun the cutover.`, timestamp: new Date(), }; } @@ -228,10 +225,7 @@ export async function verifyTicketData(prisma: PrismaClient): Promise { +export async function executeCutover(prisma: PrismaClient, args: CliArgs): Promise { const log: CutoverLog = { startedAt: new Date(), completedAt: null, @@ -280,6 +274,11 @@ export async function executeCutover( const shadow = await disableShadowMode(args.confirm); log.steps.push(shadow); logStep(shadow); + if (shadow.status === 'FAIL') { + log.outcome = 'FAILED'; + log.completedAt = new Date(); + return log; + } // Step 5: Log announcement const announceStep: StepResult = { diff --git a/scripts/cutover/rollback.ts b/scripts/cutover/rollback.ts index 626a4790..fc37af3d 100644 --- a/scripts/cutover/rollback.ts +++ b/scripts/cutover/rollback.ts @@ -55,9 +55,7 @@ function parseArgs(argv: string[]): CliArgs { // ─── Rollback Steps ───────────────────────────────────────────────────────── function logStep(result: RollbackStep): void { - const icon = result.status === 'DONE' ? '[OK]' - : result.status === 'FAIL' ? '[FAIL]' - : '[SKIP]'; + const icon = result.status === 'DONE' ? '[OK]' : result.status === 'FAIL' ? '[FAIL]' : '[SKIP]'; console.log(` ${icon} ${result.step}: ${result.message}`); } @@ -68,19 +66,33 @@ async function enableShadowMode(confirm: boolean): Promise { return { step, status: 'SKIP', - message: 'Dry run — would set SHADOW_MODE=true on Railway', + message: 'Dry run — would verify the SHADOW_MODE=true attestation', + timestamp: new Date(), + }; + } + + const currentValue = process.env.SHADOW_MODE; + if (currentValue === 'true') { + return { + step, + status: 'DONE', + message: + 'SHADOW_MODE=true is set in this process. Treat that as local attestation only, and verify the deployed services were redeployed with the same value before continuing.', timestamp: new Date(), }; } console.log(' ACTION REQUIRED: Set SHADOW_MODE=true in Railway environment variables'); console.log(' Then redeploy the discord-bot service.'); + console.log( + ' Finally, export SHADOW_MODE=true in the shell running this script before rerunning --confirm.', + ); console.log(' This prevents Outpost from posting to Discord while Orca resumes.'); return { step, - status: 'DONE', - message: 'Shadow mode re-enable instruction issued', + status: 'FAIL', + message: `Shadow mode is not confirmed on in this process (SHADOW_MODE=${currentValue ?? 'unset'}). Set SHADOW_MODE=true in Railway, redeploy discord-bot, export SHADOW_MODE=true in this shell, and rerun the rollback.`, timestamp: new Date(), }; } @@ -148,10 +160,7 @@ async function logRollbackEvent( // ─── Main ─────────────────────────────────────────────────────────────────── -export async function executeRollback( - prisma: PrismaClient, - args: CliArgs, -): Promise { +export async function executeRollback(prisma: PrismaClient, args: CliArgs): Promise { const log: RollbackLog = { startedAt: new Date(), completedAt: null, @@ -180,6 +189,10 @@ export async function executeRollback( const shadow = await enableShadowMode(args.confirm); log.steps.push(shadow); logStep(shadow); + if (shadow.status === 'FAIL') { + log.completedAt = new Date(); + return log; + } // Step 3: Log the rollback event for audit trail const logEvent = await logRollbackEvent(prisma, args.reason, args.confirm);