From 0fc3c9f5259c6f3a506a03b05e1f2aa19ae622da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nathan=20=F0=9F=94=B6=20Tarbert?= <66887028+NathanTarbert@users.noreply.github.com> Date: Wed, 2 Dec 2026 18:40:28 -0500 Subject: [PATCH 1/2] chore(scripts): remove the one-off migration and cutover tooling --- .claude/skills/deep-read-issue/SKILL.md | 2 +- apps/discord-bot/src/lib/shadow-mode.ts | 13 +- scripts/__tests__/cutover.test.ts | 299 ------------- scripts/__tests__/orca-migration.test.ts | 531 ----------------------- scripts/cutover/README.md | 132 ------ scripts/cutover/execute-cutover.ts | 335 -------------- scripts/cutover/rollback.ts | 248 ----------- scripts/cutover/validate-quality.ts | 331 -------------- scripts/lib/migration-report.ts | 81 ---- scripts/lib/orca-transformer.ts | 142 ------ scripts/lib/orca-types.ts | 156 ------- scripts/migrate-from-orca.ts | 417 ------------------ 12 files changed, 6 insertions(+), 2681 deletions(-) delete mode 100644 scripts/__tests__/cutover.test.ts delete mode 100644 scripts/__tests__/orca-migration.test.ts delete mode 100644 scripts/cutover/README.md delete mode 100644 scripts/cutover/execute-cutover.ts delete mode 100644 scripts/cutover/rollback.ts delete mode 100644 scripts/cutover/validate-quality.ts delete mode 100644 scripts/lib/migration-report.ts delete mode 100644 scripts/lib/orca-transformer.ts delete mode 100644 scripts/lib/orca-types.ts delete mode 100644 scripts/migrate-from-orca.ts diff --git a/.claude/skills/deep-read-issue/SKILL.md b/.claude/skills/deep-read-issue/SKILL.md index 40b535f8..3c82bc61 100644 --- a/.claude/skills/deep-read-issue/SKILL.md +++ b/.claude/skills/deep-read-issue/SKILL.md @@ -54,7 +54,7 @@ Capture per issue: - **Surface package MATURITY explicitly** (`stable` / `deprecated` / `experimental` / `pre-release 0.x` / `beta`). If the reporter is on anything that isn't a stable current release, say so loudly — the orchestrator must put this in the card's FIRST SENTENCE (What line), not bury it, so Nathan can tell at a glance it may be a "just migrate/upgrade" case and NOT tag engineering. Output e.g. `MATURITY: deprecated (@copilotkitnext)` or `MATURITY: pre-release 0.x (@ag-ui/*)`. - **`@copilotkitnext/*` = DEPRECATED (the useAgent-era experimental v2 line).** As of 2026-06-18 the `@copilotkitnext/*` packages are deprecated on npm and merged into `@copilotkit` v2 — `@copilotkitnext/core` → `@copilotkit/core`, `@copilotkitnext/react` → `@copilotkit/react-core/v2`, `@copilotkitnext/runtime` → `@copilotkit/runtime/v2` (last publish 1.54.1; current `@copilotkit` is on the 1.6x line). **Two things follow:** (1) a reporter on `@copilotkitnext/*` is on a dead package → the version line should note `(deprecated — migrate to @copilotkit/*/v2)` and the fix plan should first check whether the bug is already gone in current `@copilotkit` v2 (often it's a "just migrate" case, not a code fix); (2) **cite the exact subpackage the reporter used, never the bare scope `@copilotkitnext`** (which isn't a valid package). Also note: coding agents frequently *invent* `@copilotkitnext` from training data because it was real during useAgent development — so only report it when the REPORTER'S OWN text uses it; don't let an agent's guess put it on the card. - **Maintainer status, quoted.** Any comment from a MEMBER / OWNER / COLLABORATOR (check authorAssociation) that states status — "fixed in 1.60.1", "closing, reopen if not", "this is a real bug", a Linear/ENT-#### ref, "PR up". Quote it with author + date. -- **Ignore the support bot for status.** `copilotkit-support-bot` / getorca "Recommended Solutions" are auto-generated guesses, NOT maintainer status or confirmation. Note bot advice only if a human endorsed it. +- **Ignore the support bot for status.** `copilotkit-support-bot` "Recommended Solutions" are auto-generated guesses, NOT maintainer status or confirmation. Note bot advice only if a human endorsed it. - Whether the *reporter* confirmed the fix (vs a maintainer closing speculatively). - Cross-references (Discord threads, related issues, sibling-repo dup). - **TRUE COMMUNITY (by subject, not repo).** Decide whether the issue is really a CopilotKit or an AG-UI problem from *what is actually broken*, not which repo it was filed in. **Trigger:** an `ag-ui` issue whose subject/repro is a **CopilotKit** bug (it says CopilotKit chat/runtime/component breaks, or the fix shipped in a CopilotKit release) is **MIS-FILED → attribute to CopilotKit** (and the reverse). Output `COMMUNITY: CK | AG-UI` + `MIS-FILED: yes/no (filed in , true owner , because )`. **Caveat:** ownership of the broken *tool* wins over mere mentions — `create-ag-ui-app` failing is AG-UI's even though it scaffolds CopilotKit. Flag every mis-filed issue so the orchestrator lists it on the right page only. (Precedent the agent previously MISSED: `ag-ui#1891` "Illegal invocation" — an `HttpAgent` bug that breaks CopilotKit chat, fixed in CopilotKit 1.60.1 → it's CopilotKit's, not AG-UI's.) diff --git a/apps/discord-bot/src/lib/shadow-mode.ts b/apps/discord-bot/src/lib/shadow-mode.ts index 06495249..ddcfca41 100644 --- a/apps/discord-bot/src/lib/shadow-mode.ts +++ b/apps/discord-bot/src/lib/shadow-mode.ts @@ -4,14 +4,14 @@ import { TicketSource, buildTicketSourceId, truncate } from '@copilotkit/outpost import type { ThreadChannel, Message } from 'discord.js'; /** - * Shadow mode allows Outpost to run alongside Orca without double-posting. + * Shadow mode lets Outpost run against a live server without posting replies. * * When SHADOW_MODE=true: * - Tickets are created in the Outpost DB as normal * - AI responses are generated but NOT posted to Discord - * - Shadow responses are logged for quality comparison against Orca + * - Shadow responses are logged so their quality can be reviewed * - * This enables a parallel-run validation period before full cutover. + * Use it to validate responses on a server before Outpost answers there. */ export function isShadowMode(): boolean { return process.env.SHADOW_MODE === 'true'; @@ -48,7 +48,7 @@ export async function logShadowResponse(response: ShadowResponse): Promise console.log( `[Shadow Mode] Logged response for ticket ${response.ticketId} ` + - `(${response.responseTimeMs}ms)`, + `(${response.responseTimeMs}ms)`, ); } @@ -115,10 +115,7 @@ export async function handleShadowThreadCreate( return ticket.id; } catch (error) { - console.error( - `[Shadow Mode] Failed to create ticket for thread ${thread.id}:`, - error, - ); + console.error(`[Shadow Mode] Failed to create ticket for thread ${thread.id}:`, error); return null; } } diff --git a/scripts/__tests__/cutover.test.ts b/scripts/__tests__/cutover.test.ts deleted file mode 100644 index ef360bab..00000000 --- a/scripts/__tests__/cutover.test.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; - -// ─── Mock PrismaClient ────────────────────────────────────────────────────── - -function makePrismaMock() { - return { - $queryRaw: vi.fn().mockResolvedValue([{ '?column?': 1 }]), - $disconnect: vi.fn().mockResolvedValue(undefined), - ticket: { - count: vi.fn().mockResolvedValue(100), - findMany: vi.fn().mockResolvedValue([]), - }, - message: { - findMany: vi.fn().mockResolvedValue([]), - }, - }; -} - -// ─── Mock modules ─────────────────────────────────────────────────────────── - -vi.mock('@prisma/client', () => ({ - PrismaClient: vi.fn().mockImplementation(() => makePrismaMock()), -})); - -// We need to import after mocking -import { validateQuality } from '../cutover/validate-quality.js'; -import { - runHealthChecks, - runQualityValidation, - verifyTicketData, - executeCutover, -} from '../cutover/execute-cutover.js'; -import { executeRollback } from '../cutover/rollback.js'; - -describe('validate-quality', () => { - it('returns NEEDS_MORE_DATA when shadow responses are below minimum', async () => { - const prisma = makePrismaMock(); - prisma.message.findMany.mockResolvedValue([]); - prisma.ticket.findMany.mockResolvedValue([]); - - const metrics = await validateQuality(prisma as never, { - since: null, - minSample: 20, - }); - - expect(metrics.recommendation).toBe('NEEDS_MORE_DATA'); - expect(metrics.reasons[0]).toContain('Only 0 shadow responses'); - }); - - it('returns READY when sufficient high-quality shadow responses exist', async () => { - const shadowMessages = Array.from({ length: 25 }, (_, i) => ({ - id: `msg-${i}`, - ticketId: `ticket-${i}`, - author: 'outpost-shadow', - content: `Here's how to fix it:\n\`\`\`js\nconsole.log("hello")\n\`\`\`\nSee https://docs.example.com for more.`, - type: 'NOTE', - isAiGenerated: true, - attachments: { - shadowMode: true, - threadId: `thread-${i}`, - responseTimeMs: 3000, - generatedAt: new Date().toISOString(), - }, - ticket: { id: `ticket-${i}` }, - })); - - const prisma = makePrismaMock(); - prisma.message.findMany.mockResolvedValue(shadowMessages); - prisma.ticket.findMany.mockResolvedValue([]); - - const metrics = await validateQuality(prisma as never, { - since: null, - minSample: 20, - }); - - expect(metrics.recommendation).toBe('READY'); - expect(metrics.ticketsWithShadowResponses).toBe(25); - }); - - it('returns NOT_READY when response time exceeds target', async () => { - const shadowMessages = Array.from({ length: 25 }, (_, i) => ({ - id: `msg-${i}`, - ticketId: `ticket-${i}`, - author: 'outpost-shadow', - content: 'A response.', - type: 'NOTE', - isAiGenerated: true, - attachments: { - shadowMode: true, - threadId: `thread-${i}`, - responseTimeMs: 700000, // > 10 minutes - generatedAt: new Date().toISOString(), - }, - ticket: { id: `ticket-${i}` }, - })); - - const prisma = makePrismaMock(); - prisma.message.findMany.mockResolvedValue(shadowMessages); - prisma.ticket.findMany.mockResolvedValue([]); - - const metrics = await validateQuality(prisma as never, { - since: null, - minSample: 20, - }); - - expect(metrics.recommendation).toBe('NOT_READY'); - expect(metrics.reasons.some((r: string) => r.includes('response time'))).toBe(true); - }); - - it('returns NOT_READY when low confidence rate is too high', async () => { - const shadowMessages = Array.from({ length: 25 }, (_, i) => ({ - 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.", - type: 'NOTE', - isAiGenerated: true, - attachments: { - shadowMode: true, - threadId: `thread-${i}`, - responseTimeMs: 3000, - generatedAt: new Date().toISOString(), - }, - ticket: { id: `ticket-${i}` }, - })); - - const prisma = makePrismaMock(); - prisma.message.findMany.mockResolvedValue(shadowMessages); - prisma.ticket.findMany.mockResolvedValue([]); - - const metrics = await validateQuality(prisma as never, { - since: null, - minSample: 20, - }); - - expect(metrics.recommendation).toBe('NOT_READY'); - expect(metrics.reasons.some((r: string) => r.includes('low confidence'))).toBe(true); - }); -}); - -describe('execute-cutover', () => { - describe('runHealthChecks', () => { - it('passes when database is connected and env vars are set', async () => { - const prisma = makePrismaMock(); - process.env.DATABASE_URL = 'postgres://test'; - process.env.DISCORD_TOKEN = 'test-token'; - process.env.DISCORD_CLIENT_ID = 'test-client-id'; - process.env.GUILD_ID = 'test-guild-id'; - - const result = await runHealthChecks(prisma as never); - - expect(result.status).toBe('PASS'); - }); - - it('fails when database connection fails', async () => { - const prisma = makePrismaMock(); - prisma.$queryRaw.mockRejectedValue(new Error('Connection refused')); - - const result = await runHealthChecks(prisma as never); - - expect(result.status).toBe('FAIL'); - expect(result.message).toContain('Connection refused'); - }); - - it('fails when required env vars are missing', async () => { - const prisma = makePrismaMock(); - delete process.env.DISCORD_TOKEN; - - const result = await runHealthChecks(prisma as never); - - expect(result.status).toBe('FAIL'); - expect(result.message).toContain('DISCORD_TOKEN'); - }); - }); - - describe('verifyTicketData', () => { - it('passes when tickets exist', async () => { - const prisma = makePrismaMock(); - prisma.ticket.count - .mockResolvedValueOnce(150) // total - .mockResolvedValueOnce(100) // discord - .mockResolvedValueOnce(50); // orca - - const result = await verifyTicketData(prisma as never); - - expect(result.status).toBe('PASS'); - expect(result.message).toContain('150'); - }); - - it('fails when no tickets exist', async () => { - const prisma = makePrismaMock(); - prisma.ticket.count.mockResolvedValue(0); - - const result = await verifyTicketData(prisma as never); - - expect(result.status).toBe('FAIL'); - }); - }); - - describe('executeCutover', () => { - beforeEach(() => { - process.env.DATABASE_URL = 'postgres://test'; - process.env.DISCORD_TOKEN = 'test-token'; - process.env.DISCORD_CLIENT_ID = 'test-client-id'; - process.env.GUILD_ID = 'test-guild-id'; - }); - - it('validates prerequisites before proceeding', async () => { - const prisma = makePrismaMock(); - prisma.ticket.count - .mockResolvedValueOnce(100) - .mockResolvedValueOnce(80) - .mockResolvedValueOnce(20); - - const log = await executeCutover(prisma as never, { - confirm: false, - skipQualityCheck: true, - announcement: 'Test', - }); - - expect(log.outcome).toBe('SUCCESS'); - expect(log.steps.length).toBeGreaterThanOrEqual(4); - }); - - it('aborts on health check failure', async () => { - const prisma = makePrismaMock(); - prisma.$queryRaw.mockRejectedValue(new Error('Connection refused')); - - const log = await executeCutover(prisma as never, { - confirm: false, - skipQualityCheck: true, - announcement: 'Test', - }); - - expect(log.outcome).toBe('FAILED'); - expect(log.steps[0].status).toBe('FAIL'); - }); - }); -}); - -describe('rollback', () => { - describe('executeRollback', () => { - it('completes successfully in dry-run mode', async () => { - const prisma = makePrismaMock(); - - const log = await executeRollback(prisma as never, { - confirm: false, - reason: 'Test rollback', - }); - - expect(log.outcome).toBe('SUCCESS'); - expect(log.confirm).toBe(false); - // All steps should be SKIP or DONE - for (const step of log.steps) { - expect(['DONE', 'SKIP']).toContain(step.status); - } - }); - - it('completes successfully in confirm mode', async () => { - const prisma = makePrismaMock(); - - const log = await executeRollback(prisma as never, { - confirm: true, - reason: 'Response quality issue', - }); - - expect(log.outcome).toBe('SUCCESS'); - expect(log.confirm).toBe(true); - }); - - it('fails if database integrity check fails', async () => { - const prisma = makePrismaMock(); - prisma.$queryRaw.mockRejectedValue(new Error('Connection refused')); - - const log = await executeRollback(prisma as never, { - confirm: true, - reason: 'Emergency', - }); - - expect(log.outcome).toBe('FAILED'); - expect(log.steps[0].status).toBe('FAIL'); - }); - - it('preserves ticket data during rollback', async () => { - const prisma = makePrismaMock(); - prisma.ticket.count.mockResolvedValue(200); - - const log = await executeRollback(prisma as never, { - confirm: true, - reason: 'Test', - }); - - expect(log.outcome).toBe('SUCCESS'); - // Database integrity step should report ticket count - const dbStep = log.steps.find(s => s.step === 'Verify database integrity'); - expect(dbStep?.message).toContain('200'); - }); - }); -}); diff --git a/scripts/__tests__/orca-migration.test.ts b/scripts/__tests__/orca-migration.test.ts deleted file mode 100644 index 3975d5f7..00000000 --- a/scripts/__tests__/orca-migration.test.ts +++ /dev/null @@ -1,531 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { validateOrcaExport, type OrcaExport } from '../lib/orca-types.js'; -import { - transformAccount, - transformUser, - transformTicket, - transformMessage, -} from '../lib/orca-transformer.js'; -import { - createReport, - finalizeReport, - formatReport, -} from '../lib/migration-report.js'; - -// ─── Test Fixtures ────────────────────────────────────────────────────────── - -function makeValidExport(overrides: Partial = {}): OrcaExport { - return { - accounts: [ - { id: 'acct-1', name: 'Acme Corp', domain: 'acme.com', owner: 'Jane' }, - ], - users: [ - { id: 'user-1', name: 'John Doe', email: 'john@acme.com', domain: 'acme.com' }, - ], - tickets: [ - { - id: 'tkt-1', - title: 'Widget broken', - description: 'The widget does not load', - status: 'open', - priority: 'high', - type: 'bug', - account_id: 'acct-1', - user_id: 'user-1', - messages: [ - { - id: 'msg-1', - ticket_id: 'tkt-1', - author: 'John Doe', - content: 'Help, my widget is broken', - type: 'user', - created_at: '2024-06-01T12:00:00Z', - }, - ], - created_at: '2024-06-01T10:00:00Z', - updated_at: '2024-06-02T14:00:00Z', - }, - ], - ...overrides, - }; -} - -// ─── Validation Tests ─────────────────────────────────────────────────────── - -describe('validateOrcaExport', () => { - it('accepts a valid export', () => { - const result = validateOrcaExport(makeValidExport()); - expect(result.valid).toBe(true); - expect(result.errors).toHaveLength(0); - }); - - it('rejects non-object input', () => { - const result = validateOrcaExport('not an object'); - expect(result.valid).toBe(false); - expect(result.errors[0].message).toContain('must be an object'); - }); - - it('rejects null input', () => { - const result = validateOrcaExport(null); - expect(result.valid).toBe(false); - }); - - it('rejects missing accounts array', () => { - const result = validateOrcaExport({ users: [], tickets: [] }); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.field === 'accounts')).toBe(true); - }); - - it('rejects missing users array', () => { - const result = validateOrcaExport({ accounts: [], tickets: [] }); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.field === 'users')).toBe(true); - }); - - it('rejects missing tickets array', () => { - const result = validateOrcaExport({ accounts: [], users: [] }); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.field === 'tickets')).toBe(true); - }); - - it('catches account missing required id', () => { - const data = makeValidExport({ accounts: [{ id: '', name: 'Test' } as never] }); - const result = validateOrcaExport(data); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.entity === 'account' && e.field === 'id')).toBe(true); - }); - - it('catches account missing required name', () => { - const data = makeValidExport({ accounts: [{ id: 'a1', name: '' } as never] }); - const result = validateOrcaExport(data); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.entity === 'account' && e.field === 'name')).toBe(true); - }); - - it('catches user missing required email', () => { - const data = makeValidExport({ users: [{ id: 'u1', name: 'Test', email: '' } as never] }); - const result = validateOrcaExport(data); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.entity === 'user' && e.field === 'email')).toBe(true); - }); - - it('catches ticket missing required title', () => { - const data = makeValidExport({ - tickets: [{ id: 't1', title: '', description: 'x' } as never], - }); - const result = validateOrcaExport(data); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.entity === 'ticket' && e.field === 'title')).toBe(true); - }); - - it('catches ticket missing description', () => { - const data = makeValidExport({ - tickets: [{ id: 't1', title: 'Test' } as never], - }); - const result = validateOrcaExport(data); - expect(result.valid).toBe(false); - expect(result.errors.some(e => e.entity === 'ticket' && e.field === 'description')).toBe(true); - }); -}); - -// ─── Transformer Tests ────────────────────────────────────────────────────── - -describe('transformAccount', () => { - it('maps all fields correctly', () => { - const result = transformAccount({ id: '1', name: 'Acme', domain: 'acme.com', owner: 'Jane' }); - expect(result).toEqual({ - name: 'Acme', - domain: 'acme.com', - owner: 'Jane', - }); - }); - - it('handles null/undefined optional fields', () => { - const result = transformAccount({ id: '1', name: 'Acme' }); - expect(result.domain).toBeNull(); - expect(result.owner).toBeNull(); - }); -}); - -describe('transformUser', () => { - it('maps all fields correctly', () => { - const result = transformUser({ - id: 'u1', name: 'John', email: 'john@test.com', - domain: 'test.com', external_id: 'ext-123', - }); - expect(result).toEqual({ - name: 'John', - email: 'john@test.com', - domain: 'test.com', - externalId: 'ext-123', - source: 'ORCA', - }); - }); - - it('handles missing optional fields', () => { - const result = transformUser({ id: 'u1', name: 'John', email: 'john@test.com' }); - expect(result.domain).toBeNull(); - expect(result.externalId).toBeNull(); - expect(result.source).toBe('ORCA'); - }); -}); - -describe('transformTicket', () => { - it('maps status correctly', () => { - const cases: Array<[string, string]> = [ - ['open', 'OPEN'], - ['new', 'OPEN'], - ['in_progress', 'IN_PROGRESS'], - ['in progress', 'IN_PROGRESS'], - ['pending', 'IN_PROGRESS'], - ['waiting', 'WAITING_ON_CUSTOMER'], - ['waiting_on_customer', 'WAITING_ON_CUSTOMER'], - ['waiting_on_team', 'WAITING_ON_TEAM'], - ['resolved', 'RESOLVED'], - ['closed', 'CLOSED'], - ]; - - for (const [input, expected] of cases) { - const result = transformTicket( - { id: '1', title: 'T', description: 'D', status: input }, - 'TKT-0001', - ); - expect(result.status).toBe(expected); - } - }); - - it('maps priority correctly', () => { - const cases: Array<[string, string]> = [ - ['critical', 'CRITICAL'], - ['urgent', 'CRITICAL'], - ['high', 'HIGH'], - ['medium', 'MEDIUM'], - ['normal', 'MEDIUM'], - ['low', 'LOW'], - ]; - - for (const [input, expected] of cases) { - const result = transformTicket( - { id: '1', title: 'T', description: 'D', priority: input }, - 'TKT-0001', - ); - expect(result.priority).toBe(expected); - } - }); - - it('maps type correctly', () => { - const cases: Array<[string, string]> = [ - ['bug', 'BUG'], - ['feature_request', 'FEATURE_REQUEST'], - ['feature', 'FEATURE_REQUEST'], - ['question', 'QUESTION'], - ['integration_help', 'INTEGRATION_HELP'], - ['integration', 'INTEGRATION_HELP'], - ['account_issue', 'ACCOUNT_ISSUE'], - ['account', 'ACCOUNT_ISSUE'], - ['other', 'OTHER'], - ]; - - for (const [input, expected] of cases) { - const result = transformTicket( - { id: '1', title: 'T', description: 'D', type: input }, - 'TKT-0001', - ); - expect(result.type).toBe(expected); - } - }); - - it('defaults to sensible values for missing fields', () => { - const result = transformTicket( - { id: '1', title: 'T', description: 'D' }, - 'TKT-0001', - ); - expect(result.status).toBe('OPEN'); - expect(result.priority).toBe('MEDIUM'); - expect(result.type).toBe('QUESTION'); - expect(result.source).toBe('ORCA'); - expect(result.sourceId).toBe('1'); - }); - - it('falls back to defaults for unknown enum values', () => { - const result = transformTicket( - { id: '1', title: 'T', description: 'D', status: 'unknown_status', priority: 'xxx', type: 'yyy' }, - 'TKT-0001', - ); - expect(result.status).toBe('OPEN'); - expect(result.priority).toBe('MEDIUM'); - expect(result.type).toBe('OTHER'); - }); - - it('preserves displayId and sourceId', () => { - const result = transformTicket( - { id: 'orca-42', title: 'T', description: 'D' }, - 'TKT-0099', - ); - expect(result.displayId).toBe('TKT-0099'); - expect(result.sourceId).toBe('orca-42'); - }); - - it('parses dates correctly', () => { - const result = transformTicket( - { id: '1', title: 'T', description: 'D', created_at: '2024-01-15T10:30:00Z', updated_at: '2024-02-20T16:00:00Z' }, - 'TKT-0001', - ); - expect(result.createdAt).toEqual(new Date('2024-01-15T10:30:00Z')); - expect(result.updatedAt).toEqual(new Date('2024-02-20T16:00:00Z')); - }); - - it('uses current date when dates are missing', () => { - const before = new Date(); - const result = transformTicket( - { id: '1', title: 'T', description: 'D' }, - 'TKT-0001', - ); - const after = new Date(); - expect(result.createdAt.getTime()).toBeGreaterThanOrEqual(before.getTime()); - expect(result.createdAt.getTime()).toBeLessThanOrEqual(after.getTime()); - }); -}); - -describe('transformMessage', () => { - it('maps all fields correctly', () => { - const result = transformMessage({ - id: 'm1', ticket_id: 't1', author: 'John', - content: 'Hello', type: 'user', - is_ai_generated: false, attachments: [{ url: 'file.png' }], - created_at: '2024-06-01T12:00:00Z', - }); - expect(result).toEqual({ - author: 'John', - content: 'Hello', - type: 'USER', - isAiGenerated: false, - attachments: [{ url: 'file.png' }], - createdAt: new Date('2024-06-01T12:00:00Z'), - }); - }); - - it('maps message types correctly', () => { - const cases: Array<[string, string]> = [ - ['user', 'USER'], - ['customer', 'USER'], - ['bot', 'BOT'], - ['ai', 'BOT'], - ['system', 'SYSTEM'], - ['auto', 'SYSTEM'], - ]; - - for (const [input, expected] of cases) { - const result = transformMessage({ - id: 'm1', ticket_id: 't1', author: 'x', content: 'x', type: input, - }); - expect(result.type).toBe(expected); - } - }); - - it('defaults to USER type when type is missing', () => { - const result = transformMessage({ - id: 'm1', ticket_id: 't1', author: 'x', content: 'x', - }); - expect(result.type).toBe('USER'); - }); - - it('defaults isAiGenerated to false', () => { - const result = transformMessage({ - id: 'm1', ticket_id: 't1', author: 'x', content: 'x', - }); - expect(result.isAiGenerated).toBe(false); - }); - - it('handles null attachments', () => { - const result = transformMessage({ - id: 'm1', ticket_id: 't1', author: 'x', content: 'x', attachments: null, - }); - expect(result.attachments).toBeNull(); - }); -}); - -// ─── Migration Report Tests ───────────────────────────────────────────────── - -describe('migration report', () => { - it('creates a blank report', () => { - const report = createReport(false); - expect(report.accounts.created).toBe(0); - expect(report.tickets.created).toBe(0); - expect(report.users.created).toBe(0); - expect(report.messages.total).toBe(0); - expect(report.dryRun).toBe(false); - expect(report.completedAt).toBeNull(); - }); - - it('creates a dry run report', () => { - const report = createReport(true); - expect(report.dryRun).toBe(true); - }); - - it('finalizes with duration', () => { - const report = createReport(false); - // Simulate some time passing - report.startedAt = new Date(Date.now() - 1500); - finalizeReport(report); - expect(report.completedAt).toBeInstanceOf(Date); - expect(report.durationMs).toBeGreaterThanOrEqual(1400); - }); - - it('formats report with all stats', () => { - const report = createReport(false); - report.accounts.created = 10; - report.accounts.skipped = 2; - report.accounts.failed = 1; - report.users.created = 50; - report.tickets.created = 100; - report.tickets.failed = 3; - report.tickets.errors.push({ id: 'tkt-5', message: 'Duplicate key' }); - report.messages.total = 500; - finalizeReport(report); - - const output = formatReport(report); - expect(output).toContain('MIGRATION REPORT'); - expect(output).toContain('10 created'); - expect(output).toContain('2 skipped'); - expect(output).toContain('100 created'); - expect(output).toContain('500 imported'); - expect(output).toContain('tkt-5'); - expect(output).toContain('Duplicate key'); - expect(output).not.toContain('DRY RUN'); - }); - - it('formats dry run report correctly', () => { - const report = createReport(true); - finalizeReport(report); - const output = formatReport(report); - expect(output).toContain('DRY RUN'); - }); -}); - -// ─── Progress Reporting Tests ─────────────────────────────────────────────── - -describe('progress reporting', () => { - it('logProgress format matches expected pattern', () => { - // logProgress is not exported, so we verify the expected format by - // spying on stdout.write and calling the module indirectly. - // The progress format is: "\r Migrating {label}... {current}/{total}" - const writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); - - // Simulate what logProgress does internally - process.stdout.write('\r Migrating accounts... 3/10'); - - expect(writeSpy).toHaveBeenCalledWith('\r Migrating accounts... 3/10'); - writeSpy.mockRestore(); - }); -}); - -// ─── Dry Run Integration Test (mocked Prisma) ────────────────────────────── - -describe('dry run mode', () => { - it('does not call prisma create methods', async () => { - // The dry run logic is in the migration script. We test the core - // behavior: when dryRun=true, the report counts are incremented - // but no DB operations occur. - const report = createReport(true); - const data = makeValidExport(); - - // Simulate dry run account migration - for (const account of data.accounts) { - const _transformed = transformAccount(account); - // In dry run, we skip DB operations and just count - report.accounts.created++; - } - - // Simulate dry run ticket migration - for (const ticket of data.tickets) { - const _transformed = transformTicket(ticket, 'TKT-0001'); - report.tickets.created++; - report.messages.total += (ticket.messages ?? []).length; - } - - finalizeReport(report); - - expect(report.accounts.created).toBe(1); - expect(report.tickets.created).toBe(1); - expect(report.messages.total).toBe(1); - expect(report.dryRun).toBe(true); - }); -}); - -// ─── Rollback Test ────────────────────────────────────────────────────────── - -describe('rollback', () => { - it('deletes only ORCA-sourced records', () => { - // The rollback logic uses Prisma deleteMany with { source: 'ORCA' }. - // We verify the query shape matches what we expect. - const expectedTicketFilter = { source: 'ORCA' }; - const expectedUserFilter = { source: 'ORCA' }; - - // These filters should only match ORCA data, not manual/discord/etc - expect(expectedTicketFilter.source).toBe('ORCA'); - expect(expectedUserFilter.source).toBe('ORCA'); - expect(expectedTicketFilter.source).not.toBe('DISCORD'); - expect(expectedTicketFilter.source).not.toBe('MANUAL'); - }); - - it('rollback with mocked prisma deletes in correct order', async () => { - const deletedMessages: string[] = []; - - const mockPrisma = { - ticket: { - findMany: vi.fn().mockResolvedValue([ - { id: 'outpost-1' }, - { id: 'outpost-2' }, - ]), - deleteMany: vi.fn().mockResolvedValue({ count: 2 }), - }, - message: { - deleteMany: vi.fn().mockResolvedValue({ count: 5 }), - }, - user: { - deleteMany: vi.fn().mockResolvedValue({ count: 3 }), - }, - }; - - // Simulate rollback sequence - const orcaTickets = await mockPrisma.ticket.findMany({ - where: { source: 'ORCA' }, - select: { id: true }, - }); - const ticketIds = orcaTickets.map((t: { id: string }) => t.id); - - const messagesResult = await mockPrisma.message.deleteMany({ - where: { ticketId: { in: ticketIds } }, - }); - deletedMessages.push(`messages:${messagesResult.count}`); - - const ticketsResult = await mockPrisma.ticket.deleteMany({ - where: { source: 'ORCA' }, - }); - deletedMessages.push(`tickets:${ticketsResult.count}`); - - const usersResult = await mockPrisma.user.deleteMany({ - where: { source: 'ORCA' }, - }); - deletedMessages.push(`users:${usersResult.count}`); - - // Verify order: messages first, then tickets, then users - expect(deletedMessages).toEqual(['messages:5', 'tickets:2', 'users:3']); - - // Verify the correct filters were used - expect(mockPrisma.ticket.findMany).toHaveBeenCalledWith({ - where: { source: 'ORCA' }, - select: { id: true }, - }); - expect(mockPrisma.message.deleteMany).toHaveBeenCalledWith({ - where: { ticketId: { in: ['outpost-1', 'outpost-2'] } }, - }); - expect(mockPrisma.ticket.deleteMany).toHaveBeenCalledWith({ - where: { source: 'ORCA' }, - }); - expect(mockPrisma.user.deleteMany).toHaveBeenCalledWith({ - where: { source: 'ORCA' }, - }); - }); -}); diff --git a/scripts/cutover/README.md b/scripts/cutover/README.md deleted file mode 100644 index 79f46ad8..00000000 --- a/scripts/cutover/README.md +++ /dev/null @@ -1,132 +0,0 @@ -# Orca → Outpost Cutover - -Step-by-step procedure for switching from Orca (app.getorca.ai) to Outpost as the primary support bot. - -## Pre-Cutover Checklist - -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) -- [ ] **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 -- [ ] **Pathfinder indexed** — knowledge base is populated and responding -- [ ] **HubSpot synced** — customer account data is flowing (if applicable) - -## Phase 1: Parallel Run (Shadow Mode) - -Shadow mode lets Outpost monitor the same channels as Orca without posting responses. - -### Enable Shadow Mode - -1. Set `SHADOW_MODE=true` in the discord-bot's environment variables on Railway -2. Deploy the discord-bot service -3. Verify the bot is online: check the `/health` endpoint and Discord presence - -### What Happens in Shadow Mode - -- Outpost monitors threads in configured channels -- Creates tickets in the Outpost database -- Generates AI responses but does **NOT** post them to Discord -- Logs shadow responses for quality comparison with Orca's actual responses -- Orca continues to operate normally — users see no change - -### Monitor the Parallel Run - -Run the quality validation script periodically: - -```bash -npx tsx scripts/cutover/validate-quality.ts -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 - -Target: run for **48-72 hours** with at least 20 shadow responses before proceeding. - -## Phase 2: Validation - -### Quality Criteria - -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% | - -### Run Validation - -```bash -npx tsx scripts/cutover/validate-quality.ts --min-sample 20 -``` - -Produces a report with a recommendation: `READY`, `NOT_READY`, or `NEEDS_MORE_DATA`. - -## Phase 3: Cutover - -### Dry Run First - -```bash -npx tsx scripts/cutover/execute-cutover.ts -``` - -This validates all prerequisites without making changes. - -### Execute Cutover - -```bash -npx tsx scripts/cutover/execute-cutover.ts --confirm -``` - -The script: -1. Verifies all health checks pass -2. Validates shadow mode quality metrics -3. Disables shadow mode (`SHADOW_MODE=false`) -4. Posts upgrade announcement in support channels - -### Post-Cutover - -- [ ] Verify Outpost is responding to new threads within 5 minutes -- [ ] Disable Orca bot in Discord server settings -- [ ] Monitor for 2 hours — check response quality and timing -- [ ] Verify no threads are being missed (compare channel activity vs ticket count) - -## Phase 4: Rollback (if needed) - -If issues arise after cutover, roll back immediately: - -### Dry Run - -```bash -npx tsx scripts/cutover/rollback.ts -``` - -### Execute Rollback - -```bash -npx tsx scripts/cutover/rollback.ts --confirm --reason "Response quality degradation" -``` - -The rollback script: -1. Verifies database integrity (ticket data is preserved) -2. Re-enables shadow mode (`SHADOW_MODE=true`) -3. Logs the rollback event for audit trail -4. Prints manual steps: re-enable Orca bot, verify it's responding - -### Manual Steps After Rollback - -1. Re-enable Orca bot in Discord server settings -2. Verify Orca is responding to new threads -3. Monitor for 30 minutes to confirm stability -4. Investigate the root cause before attempting cutover again diff --git a/scripts/cutover/execute-cutover.ts b/scripts/cutover/execute-cutover.ts deleted file mode 100644 index 4ff2867d..00000000 --- a/scripts/cutover/execute-cutover.ts +++ /dev/null @@ -1,335 +0,0 @@ -#!/usr/bin/env npx tsx -// ─── Orca → Outpost Cutover Execution ─────────────────────────────────────── -// Automated step-by-step cutover from Orca to Outpost as the primary bot. -// -// Usage: -// npx tsx scripts/cutover/execute-cutover.ts # dry run -// npx tsx scripts/cutover/execute-cutover.ts --confirm # execute for real - -import { PrismaClient } from '@prisma/client'; -import { validateQuality } from './validate-quality.js'; - -// ─── Types ────────────────────────────────────────────────────────────────── - -interface StepResult { - step: string; - status: 'PASS' | 'FAIL' | 'SKIP'; - message: string; - timestamp: Date; -} - -interface CutoverLog { - startedAt: Date; - completedAt: Date | null; - confirm: boolean; - steps: StepResult[]; - outcome: 'SUCCESS' | 'FAILED' | 'ABORTED'; -} - -interface CliArgs { - confirm: boolean; - skipQualityCheck: boolean; - announcement: string; -} - -// ─── CLI Parsing ──────────────────────────────────────────────────────────── - -function parseArgs(argv: string[]): CliArgs { - const args: CliArgs = { - confirm: false, - skipQualityCheck: false, - announcement: - "We've upgraded our support bot to provide faster, more accurate responses. " + - "If you notice any issues, please let us know!", - }; - - for (let i = 2; i < argv.length; i++) { - switch (argv[i]) { - case '--confirm': - args.confirm = true; - break; - case '--skip-quality-check': - args.skipQualityCheck = true; - break; - case '--announcement': - args.announcement = argv[++i] ?? args.announcement; - break; - } - } - - return args; -} - -// ─── Step Execution ───────────────────────────────────────────────────────── - -function logStep(result: StepResult): void { - const icon = result.status === 'PASS' ? '[OK]' - : result.status === 'FAIL' ? '[FAIL]' - : '[SKIP]'; - console.log(` ${icon} ${result.step}: ${result.message}`); -} - -export async function runHealthChecks(prisma: PrismaClient): Promise { - const step = 'Health checks'; - try { - // Verify database connectivity - 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]); - if (missing.length > 0) { - return { - step, - status: 'FAIL', - message: `Missing env vars: ${missing.join(', ')}`, - timestamp: new Date(), - }; - } - - return { - step, - status: 'PASS', - message: 'Database connected, all required env vars present', - timestamp: new Date(), - }; - } catch (err) { - return { - step, - status: 'FAIL', - message: `Database connection failed: ${err instanceof Error ? err.message : String(err)}`, - timestamp: new Date(), - }; - } -} - -export async function runQualityValidation( - prisma: PrismaClient, - skip: boolean, -): Promise { - const step = 'Quality validation'; - - if (skip) { - return { - step, - status: 'SKIP', - message: 'Skipped via --skip-quality-check', - timestamp: new Date(), - }; - } - - try { - const metrics = await validateQuality(prisma, { - since: null, - minSample: 20, - }); - - if (metrics.recommendation === 'READY') { - return { - step, - status: 'PASS', - message: `${metrics.ticketsWithShadowResponses} shadow responses analyzed, all metrics pass`, - timestamp: new Date(), - }; - } - - return { - step, - status: 'FAIL', - message: `Recommendation: ${metrics.recommendation} — ${metrics.reasons.join('; ')}`, - timestamp: new Date(), - }; - } catch (err) { - return { - step, - status: 'FAIL', - message: `Validation error: ${err instanceof Error ? err.message : String(err)}`, - timestamp: new Date(), - }; - } -} - -export async function disableShadowMode(confirm: boolean): Promise { - const step = 'Disable shadow mode'; - - if (!confirm) { - return { - step, - status: 'SKIP', - message: 'Dry run — would set SHADOW_MODE=false on Railway', - 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. - const currentValue = process.env.SHADOW_MODE; - if (currentValue !== 'true') { - return { - step, - status: 'PASS', - message: `Shadow mode already disabled (SHADOW_MODE=${currentValue ?? 'unset'})`, - timestamp: new Date(), - }; - } - - console.log(' ACTION REQUIRED: Set SHADOW_MODE=false in Railway environment variables'); - console.log(' Then redeploy the discord-bot service.'); - - return { - step, - status: 'PASS', - message: 'Shadow mode disable instruction issued', - timestamp: new Date(), - }; -} - -export async function verifyTicketData(prisma: PrismaClient): Promise { - const step = 'Verify ticket data'; - - try { - const ticketCount = await prisma.ticket.count(); - const discordTickets = await prisma.ticket.count({ - where: { source: 'DISCORD' }, - }); - const orcaTickets = await prisma.ticket.count({ - where: { source: 'ORCA' }, - }); - - if (ticketCount === 0) { - return { - step, - status: 'FAIL', - message: 'No tickets found in database', - timestamp: new Date(), - }; - } - - return { - step, - status: 'PASS', - message: `${ticketCount} total tickets (${discordTickets} Discord, ${orcaTickets} Orca)`, - timestamp: new Date(), - }; - } catch (err) { - return { - step, - status: 'FAIL', - message: `Query failed: ${err instanceof Error ? err.message : String(err)}`, - timestamp: new Date(), - }; - } -} - -// ─── Main ─────────────────────────────────────────────────────────────────── - -export async function executeCutover( - prisma: PrismaClient, - args: CliArgs, -): Promise { - const log: CutoverLog = { - startedAt: new Date(), - completedAt: null, - confirm: args.confirm, - steps: [], - outcome: 'ABORTED', - }; - - console.log(''); - console.log('═══ Orca → Outpost Cutover ═══'); - console.log(` Mode: ${args.confirm ? 'EXECUTE' : 'DRY RUN'}`); - console.log(` Started: ${log.startedAt.toISOString()}`); - console.log(''); - - // Step 1: Health checks - const health = await runHealthChecks(prisma); - log.steps.push(health); - logStep(health); - if (health.status === 'FAIL') { - log.outcome = 'FAILED'; - log.completedAt = new Date(); - return log; - } - - // Step 2: Verify ticket data exists - const dataCheck = await verifyTicketData(prisma); - log.steps.push(dataCheck); - logStep(dataCheck); - if (dataCheck.status === 'FAIL') { - log.outcome = 'FAILED'; - log.completedAt = new Date(); - return log; - } - - // Step 3: Quality validation - const quality = await runQualityValidation(prisma, args.skipQualityCheck); - log.steps.push(quality); - logStep(quality); - if (quality.status === 'FAIL') { - log.outcome = 'FAILED'; - log.completedAt = new Date(); - return log; - } - - // Step 4: Disable shadow mode - const shadow = await disableShadowMode(args.confirm); - log.steps.push(shadow); - logStep(shadow); - - // Step 5: Log announcement - const announceStep: StepResult = { - step: 'Post announcement', - status: args.confirm ? 'PASS' : 'SKIP', - message: args.confirm - ? `Announcement: "${args.announcement}"` - : `Dry run — would post: "${args.announcement}"`, - timestamp: new Date(), - }; - log.steps.push(announceStep); - logStep(announceStep); - - log.outcome = 'SUCCESS'; - log.completedAt = new Date(); - - console.log(''); - console.log(` Cutover ${args.confirm ? 'COMPLETED' : 'DRY RUN COMPLETED'}`); - console.log(` Duration: ${log.completedAt.getTime() - log.startedAt.getTime()}ms`); - console.log(''); - - return log; -} - -async function main(): Promise { - const args = parseArgs(process.argv); - - if (!args.confirm) { - console.log('\n This is a DRY RUN. Pass --confirm to execute the cutover.\n'); - } - - const prisma = new PrismaClient(); - - try { - const log = await executeCutover(prisma, args); - - if (log.outcome === 'FAILED') { - console.error('\n Cutover FAILED. Review the steps above.\n'); - process.exit(1); - } - } finally { - await prisma.$disconnect(); - } -} - -// Only run when executed directly (not when imported for testing) -const isDirectExecution = process.argv[1]?.endsWith('execute-cutover.ts') ?? false; -if (isDirectExecution) { - main().catch((err) => { - console.error('Cutover failed:', err); - process.exit(1); - }); -} diff --git a/scripts/cutover/rollback.ts b/scripts/cutover/rollback.ts deleted file mode 100644 index 626a4790..00000000 --- a/scripts/cutover/rollback.ts +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env npx tsx -// ─── Outpost Emergency Rollback ───────────────────────────────────────────── -// Reverts from Outpost back to Orca as the primary bot. -// -// Usage: -// npx tsx scripts/cutover/rollback.ts # dry run -// npx tsx scripts/cutover/rollback.ts --confirm # execute rollback - -import { PrismaClient } from '@prisma/client'; - -// ─── Types ────────────────────────────────────────────────────────────────── - -interface RollbackStep { - step: string; - status: 'DONE' | 'SKIP' | 'FAIL'; - message: string; - timestamp: Date; -} - -interface RollbackLog { - startedAt: Date; - completedAt: Date | null; - confirm: boolean; - steps: RollbackStep[]; - outcome: 'SUCCESS' | 'FAILED'; -} - -interface CliArgs { - confirm: boolean; - reason: string; -} - -// ─── CLI Parsing ──────────────────────────────────────────────────────────── - -function parseArgs(argv: string[]): CliArgs { - const args: CliArgs = { - confirm: false, - reason: 'Emergency rollback — no specific reason provided', - }; - - for (let i = 2; i < argv.length; i++) { - switch (argv[i]) { - case '--confirm': - args.confirm = true; - break; - case '--reason': - args.reason = argv[++i] ?? args.reason; - break; - } - } - - return args; -} - -// ─── Rollback Steps ───────────────────────────────────────────────────────── - -function logStep(result: RollbackStep): void { - const icon = result.status === 'DONE' ? '[OK]' - : result.status === 'FAIL' ? '[FAIL]' - : '[SKIP]'; - console.log(` ${icon} ${result.step}: ${result.message}`); -} - -async function enableShadowMode(confirm: boolean): Promise { - const step = 'Re-enable shadow mode'; - - if (!confirm) { - return { - step, - status: 'SKIP', - message: 'Dry run — would set SHADOW_MODE=true on Railway', - 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(' This prevents Outpost from posting to Discord while Orca resumes.'); - - return { - step, - status: 'DONE', - message: 'Shadow mode re-enable instruction issued', - timestamp: new Date(), - }; -} - -async function verifyDatabaseIntegrity(prisma: PrismaClient): Promise { - const step = 'Verify database integrity'; - - try { - await prisma.$queryRaw`SELECT 1`; - const ticketCount = await prisma.ticket.count(); - - return { - step, - status: 'DONE', - message: `Database OK, ${ticketCount} tickets preserved`, - timestamp: new Date(), - }; - } catch (err) { - return { - step, - status: 'FAIL', - message: `Database check failed: ${err instanceof Error ? err.message : String(err)}`, - timestamp: new Date(), - }; - } -} - -async function logRollbackEvent( - prisma: PrismaClient, - reason: string, - confirm: boolean, -): Promise { - const step = 'Log rollback event'; - - if (!confirm) { - return { - step, - status: 'SKIP', - message: `Dry run — would log: "${reason}"`, - timestamp: new Date(), - }; - } - - try { - // Store rollback event as a system note on a sentinel record - // This creates a breadcrumb in the database for audit purposes - console.log(` Rollback reason: ${reason}`); - console.log(` Rollback timestamp: ${new Date().toISOString()}`); - - return { - step, - status: 'DONE', - message: 'Rollback event recorded', - timestamp: new Date(), - }; - } catch (err) { - return { - step, - status: 'FAIL', - message: `Failed to log event: ${err instanceof Error ? err.message : String(err)}`, - timestamp: new Date(), - }; - } -} - -// ─── Main ─────────────────────────────────────────────────────────────────── - -export async function executeRollback( - prisma: PrismaClient, - args: CliArgs, -): Promise { - const log: RollbackLog = { - startedAt: new Date(), - completedAt: null, - confirm: args.confirm, - steps: [], - outcome: 'FAILED', - }; - - console.log(''); - console.log('═══ Outpost → Orca Rollback ═══'); - console.log(` Mode: ${args.confirm ? 'EXECUTE' : 'DRY RUN'}`); - console.log(` Reason: ${args.reason}`); - console.log(` Started: ${log.startedAt.toISOString()}`); - console.log(''); - - // Step 1: Verify database is healthy (we don't want to lose data) - const dbCheck = await verifyDatabaseIntegrity(prisma); - log.steps.push(dbCheck); - logStep(dbCheck); - if (dbCheck.status === 'FAIL') { - log.completedAt = new Date(); - return log; - } - - // Step 2: Re-enable shadow mode (prevents Outpost from posting) - const shadow = await enableShadowMode(args.confirm); - log.steps.push(shadow); - logStep(shadow); - - // Step 3: Log the rollback event for audit trail - const logEvent = await logRollbackEvent(prisma, args.reason, args.confirm); - log.steps.push(logEvent); - logStep(logEvent); - - // Step 4: Notify team - const notifyStep: RollbackStep = { - step: 'Notify team', - status: args.confirm ? 'DONE' : 'SKIP', - message: args.confirm - ? 'ACTION REQUIRED: Re-enable Orca bot in Discord server settings' - : 'Dry run — would notify team to re-enable Orca', - timestamp: new Date(), - }; - log.steps.push(notifyStep); - logStep(notifyStep); - - if (args.confirm) { - console.log(''); - console.log(' MANUAL STEPS REQUIRED:'); - console.log(' 1. Re-enable Orca bot in Discord server settings'); - console.log(' 2. Verify Orca is responding to new threads'); - console.log(' 3. Monitor for 30 minutes to confirm stability'); - } - - log.outcome = 'SUCCESS'; - log.completedAt = new Date(); - - console.log(''); - console.log(` Rollback ${args.confirm ? 'COMPLETED' : 'DRY RUN COMPLETED'}`); - console.log(` Duration: ${log.completedAt.getTime() - log.startedAt.getTime()}ms`); - console.log(''); - - return log; -} - -async function main(): Promise { - const args = parseArgs(process.argv); - - if (!args.confirm) { - console.log('\n This is a DRY RUN. Pass --confirm to execute the rollback.\n'); - } - - const prisma = new PrismaClient(); - - try { - const log = await executeRollback(prisma, args); - - if (log.outcome === 'FAILED') { - console.error('\n Rollback FAILED. Review the steps above.\n'); - process.exit(1); - } - } finally { - await prisma.$disconnect(); - } -} - -// Only run when executed directly (not when imported for testing) -const isDirectExecution = process.argv[1]?.endsWith('rollback.ts') ?? false; -if (isDirectExecution) { - main().catch((err) => { - console.error('Rollback failed:', err); - process.exit(1); - }); -} diff --git a/scripts/cutover/validate-quality.ts b/scripts/cutover/validate-quality.ts deleted file mode 100644 index 42835bc0..00000000 --- a/scripts/cutover/validate-quality.ts +++ /dev/null @@ -1,331 +0,0 @@ -#!/usr/bin/env npx tsx -// ─── Shadow Mode Quality Validation ───────────────────────────────────────── -// Compares Outpost's shadow responses against Orca's actual posted responses. -// -// Usage: -// npx tsx scripts/cutover/validate-quality.ts -// npx tsx scripts/cutover/validate-quality.ts --since 2024-01-01 -// npx tsx scripts/cutover/validate-quality.ts --min-sample 50 - -import { PrismaClient } from '@prisma/client'; - -// ─── Types ────────────────────────────────────────────────────────────────── - -interface QualityMetrics { - totalTickets: number; - ticketsWithShadowResponses: number; - ticketsWithOrcaResponses: number; - ticketsWithBoth: number; - averageShadowResponseTimeMs: number; - averageOrcaResponseTimeMs: number; - contentQuality: { - averageShadowLength: number; - averageOrcaLength: number; - shadowCodeBlockCount: number; - orcaCodeBlockCount: number; - shadowLinkCount: number; - orcaLinkCount: number; - }; - confidenceDistribution: { - high: number; - medium: number; - low: number; - }; - recommendation: 'READY' | 'NOT_READY' | 'NEEDS_MORE_DATA'; - reasons: string[]; -} - -interface CliArgs { - since: Date | null; - minSample: number; -} - -// ─── CLI Parsing ──────────────────────────────────────────────────────────── - -function parseArgs(argv: string[]): CliArgs { - const args: CliArgs = { - since: null, - minSample: 20, - }; - - for (let i = 2; i < argv.length; i++) { - switch (argv[i]) { - case '--since': - args.since = new Date(argv[++i] ?? ''); - break; - case '--min-sample': - args.minSample = parseInt(argv[++i] ?? '20', 10); - break; - } - } - - return args; -} - -// ─── Content Analysis ─────────────────────────────────────────────────────── - -function countCodeBlocks(content: string): number { - const matches = content.match(/```[\s\S]*?```/g); - return matches?.length ?? 0; -} - -function countLinks(content: string): number { - const matches = content.match(/https?:\/\/[^\s)>\]]+/g); - return matches?.length ?? 0; -} - -function classifyConfidence(content: string): 'high' | 'medium' | 'low' { - const lowConfidenceSignals = [ - /i'm not sure/i, - /i don't know/i, - /i cannot/i, - /unfortunately/i, - /i don't have enough/i, - ]; - - const highConfidenceSignals = [ - /```/, // Code blocks suggest concrete answers - /https?:\/\//, // Links suggest specific references - /step \d/i, // Step-by-step instructions - /here's how/i, - ]; - - const lowScore = lowConfidenceSignals.filter(r => r.test(content)).length; - const highScore = highConfidenceSignals.filter(r => r.test(content)).length; - - if (highScore >= 2 && lowScore === 0) return 'high'; - if (lowScore >= 2) return 'low'; - return 'medium'; -} - -// ─── Validation Logic ─────────────────────────────────────────────────────── - -export async function validateQuality( - prisma: PrismaClient, - args: CliArgs, -): Promise { - const whereClause = args.since - ? { createdAt: { gte: args.since } } - : {}; - - // Fetch all shadow responses (SYSTEM messages from outpost-shadow) - const shadowMessages = await prisma.message.findMany({ - where: { - author: 'outpost-shadow', - type: 'SYSTEM', - isAiGenerated: true, - ...whereClause, - }, - include: { - ticket: true, - }, - }); - - // Fetch Orca AI responses (AI messages from the orca bot) - // Orca responses are identified by source=ORCA on the ticket - const orcaTickets = await prisma.ticket.findMany({ - where: { - source: 'ORCA', - ...whereClause, - }, - include: { - messages: { - where: { isAiGenerated: true }, - }, - }, - }); - - // Also fetch Discord-source tickets that have shadow responses - const shadowTicketIds = [...new Set(shadowMessages.map(m => m.ticketId))]; - const discordTickets = await prisma.ticket.findMany({ - where: { - source: 'DISCORD', - id: { in: shadowTicketIds }, - }, - include: { - messages: { - where: { isAiGenerated: true }, - }, - }, - }); - - // Build metrics - const allTicketIds = new Set([ - ...shadowTicketIds, - ...orcaTickets.map(t => t.id), - ]); - - const shadowResponseTimes: number[] = []; - const orcaResponseTimes: number[] = []; - const shadowLengths: number[] = []; - const orcaLengths: number[] = []; - let shadowCodeBlocks = 0; - let orcaCodeBlocks = 0; - let shadowLinks = 0; - let orcaLinks = 0; - const confidenceDist = { high: 0, medium: 0, low: 0 }; - - for (const msg of shadowMessages) { - shadowLengths.push(msg.content.length); - shadowCodeBlocks += countCodeBlocks(msg.content); - shadowLinks += countLinks(msg.content); - confidenceDist[classifyConfidence(msg.content)]++; - - // Extract response time from attachments metadata - const attachments = msg.attachments as Record | null; - if (attachments?.responseTimeMs) { - shadowResponseTimes.push(Number(attachments.responseTimeMs)); - } - } - - for (const ticket of orcaTickets) { - for (const msg of ticket.messages) { - orcaLengths.push(msg.content.length); - orcaCodeBlocks += countCodeBlocks(msg.content); - orcaLinks += countLinks(msg.content); - } - } - - const avg = (arr: number[]) => arr.length > 0 - ? arr.reduce((a, b) => a + b, 0) / arr.length - : 0; - - const ticketsWithBoth = discordTickets.filter(t => - shadowMessages.some(m => m.ticketId === t.id), - ).length; - - // Determine recommendation - const reasons: string[] = []; - let recommendation: QualityMetrics['recommendation'] = 'READY'; - - if (shadowMessages.length < args.minSample) { - recommendation = 'NEEDS_MORE_DATA'; - reasons.push( - `Only ${shadowMessages.length} shadow responses collected ` + - `(minimum: ${args.minSample})`, - ); - } - - const avgResponseTime = avg(shadowResponseTimes); - if (avgResponseTime > 600000) { // 10 minutes in ms - recommendation = 'NOT_READY'; - reasons.push( - `Average response time ${Math.round(avgResponseTime / 1000)}s exceeds 10 minute target`, - ); - } - - const avgShadowLen = avg(shadowLengths); - const avgOrcaLen = avg(orcaLengths); - if (avgOrcaLen > 0 && avgShadowLen < avgOrcaLen * 0.5) { - recommendation = 'NOT_READY'; - reasons.push( - `Shadow responses are significantly shorter than Orca ` + - `(${Math.round(avgShadowLen)} vs ${Math.round(avgOrcaLen)} chars)`, - ); - } - - const lowConfidenceRate = shadowMessages.length > 0 - ? confidenceDist.low / shadowMessages.length - : 0; - if (lowConfidenceRate > 0.2) { - if (recommendation !== 'NOT_READY') recommendation = 'NOT_READY'; - reasons.push( - `${Math.round(lowConfidenceRate * 100)}% of responses have low confidence ` + - `(target: <20%)`, - ); - } - - if (reasons.length === 0) { - reasons.push('All quality metrics meet targets'); - } - - return { - totalTickets: allTicketIds.size, - ticketsWithShadowResponses: shadowTicketIds.length, - ticketsWithOrcaResponses: orcaTickets.length, - ticketsWithBoth, - averageShadowResponseTimeMs: avgResponseTime, - averageOrcaResponseTimeMs: avg(orcaResponseTimes), - contentQuality: { - averageShadowLength: avgShadowLen, - averageOrcaLength: avgOrcaLen, - shadowCodeBlockCount: shadowCodeBlocks, - orcaCodeBlockCount: orcaCodeBlocks, - shadowLinkCount: shadowLinks, - orcaLinkCount: orcaLinks, - }, - confidenceDistribution: confidenceDist, - recommendation, - reasons, - }; -} - -// ─── Report Formatting ────────────────────────────────────────────────────── - -function formatReport(metrics: QualityMetrics): string { - const lines: string[] = [ - '', - '═══ Outpost Shadow Mode Quality Report ═══', - '', - ` Tickets analyzed: ${metrics.totalTickets}`, - ` With shadow responses: ${metrics.ticketsWithShadowResponses}`, - ` With Orca responses: ${metrics.ticketsWithOrcaResponses}`, - ` With both (comparable): ${metrics.ticketsWithBoth}`, - '', - '─── Response Time ───', - ` Outpost average: ${Math.round(metrics.averageShadowResponseTimeMs / 1000)}s`, - ` Orca average: ${Math.round(metrics.averageOrcaResponseTimeMs / 1000)}s`, - '', - '─── Content Quality ───', - ` Outpost avg length: ${Math.round(metrics.contentQuality.averageShadowLength)} chars`, - ` Orca avg length: ${Math.round(metrics.contentQuality.averageOrcaLength)} chars`, - ` Outpost code blocks: ${metrics.contentQuality.shadowCodeBlockCount}`, - ` Orca code blocks: ${metrics.contentQuality.orcaCodeBlockCount}`, - ` Outpost links: ${metrics.contentQuality.shadowLinkCount}`, - ` Orca links: ${metrics.contentQuality.orcaLinkCount}`, - '', - '─── Confidence Distribution ───', - ` High: ${metrics.confidenceDistribution.high}`, - ` Medium: ${metrics.confidenceDistribution.medium}`, - ` Low: ${metrics.confidenceDistribution.low}`, - '', - '─── Recommendation ───', - ` Status: ${metrics.recommendation}`, - ]; - - for (const reason of metrics.reasons) { - lines.push(` - ${reason}`); - } - - lines.push(''); - return lines.join('\n'); -} - -// ─── Main ─────────────────────────────────────────────────────────────────── - -async function main(): Promise { - const args = parseArgs(process.argv); - const prisma = new PrismaClient(); - - try { - console.log('\n Analyzing shadow mode quality...'); - const metrics = await validateQuality(prisma, args); - console.log(formatReport(metrics)); - - // Exit with non-zero if not ready - if (metrics.recommendation === 'NOT_READY') { - process.exit(1); - } - } finally { - await prisma.$disconnect(); - } -} - -// Only run when executed directly (not when imported for testing) -const isDirectExecution = process.argv[1]?.endsWith('validate-quality.ts') ?? false; -if (isDirectExecution) { - main().catch((err) => { - console.error('Quality validation failed:', err); - process.exit(1); - }); -} diff --git a/scripts/lib/migration-report.ts b/scripts/lib/migration-report.ts deleted file mode 100644 index cbf3a086..00000000 --- a/scripts/lib/migration-report.ts +++ /dev/null @@ -1,81 +0,0 @@ -// ─── Migration Report ─────────────────────────────────────────────────────── -// Tracks and summarizes migration results. - -export interface EntityStats { - created: number; - skipped: number; - failed: number; - errors: Array<{ id: string; message: string }>; -} - -export interface MigrationReport { - accounts: EntityStats; - users: EntityStats; - tickets: EntityStats; - messages: { total: number }; - startedAt: Date; - completedAt: Date | null; - durationMs: number | null; - dryRun: boolean; -} - -export function createReport(dryRun: boolean): MigrationReport { - return { - accounts: { created: 0, skipped: 0, failed: 0, errors: [] }, - users: { created: 0, skipped: 0, failed: 0, errors: [] }, - tickets: { created: 0, skipped: 0, failed: 0, errors: [] }, - messages: { total: 0 }, - startedAt: new Date(), - completedAt: null, - durationMs: null, - dryRun, - }; -} - -export function finalizeReport(report: MigrationReport): MigrationReport { - report.completedAt = new Date(); - report.durationMs = report.completedAt.getTime() - report.startedAt.getTime(); - return report; -} - -export function formatReport(report: MigrationReport): string { - const lines: string[] = []; - const divider = '─'.repeat(60); - - lines.push(''); - lines.push(divider); - lines.push(report.dryRun ? ' MIGRATION DRY RUN REPORT' : ' MIGRATION REPORT'); - lines.push(divider); - lines.push(''); - - lines.push(` Accounts: ${report.accounts.created} created, ${report.accounts.skipped} skipped, ${report.accounts.failed} failed`); - lines.push(` Users: ${report.users.created} created, ${report.users.skipped} skipped, ${report.users.failed} failed`); - lines.push(` Tickets: ${report.tickets.created} created, ${report.tickets.skipped} skipped, ${report.tickets.failed} failed`); - lines.push(` Messages: ${report.messages.total} imported`); - lines.push(''); - - if (report.durationMs !== null) { - const seconds = (report.durationMs / 1000).toFixed(1); - lines.push(` Duration: ${seconds}s`); - lines.push(''); - } - - const allErrors = [ - ...report.accounts.errors.map(e => ` [account ${e.id}] ${e.message}`), - ...report.users.errors.map(e => ` [user ${e.id}] ${e.message}`), - ...report.tickets.errors.map(e => ` [ticket ${e.id}] ${e.message}`), - ]; - - if (allErrors.length > 0) { - lines.push(' ERRORS:'); - for (const err of allErrors) { - lines.push(err); - } - lines.push(''); - } - - lines.push(divider); - lines.push(''); - - return lines.join('\n'); -} diff --git a/scripts/lib/orca-transformer.ts b/scripts/lib/orca-transformer.ts deleted file mode 100644 index 621a951e..00000000 --- a/scripts/lib/orca-transformer.ts +++ /dev/null @@ -1,142 +0,0 @@ -// ─── Orca → Outpost Data Transformer ──────────────────────────────────────── -// Maps Orca export entities to Outpost Prisma model shapes. - -import type { OrcaAccount, OrcaMessage, OrcaTicket, OrcaUser } from './orca-types.js'; - -// ─── Status Mapping ───────────────────────────────────────────────────────── - -const STATUS_MAP: Record = { - 'open': 'OPEN', - 'new': 'OPEN', - 'in_progress': 'IN_PROGRESS', - 'in progress': 'IN_PROGRESS', - 'pending': 'IN_PROGRESS', - 'waiting': 'WAITING_ON_CUSTOMER', - 'waiting_on_customer': 'WAITING_ON_CUSTOMER', - 'waiting_on_team': 'WAITING_ON_TEAM', - 'resolved': 'RESOLVED', - 'closed': 'CLOSED', -}; - -const PRIORITY_MAP: Record = { - 'critical': 'CRITICAL', - 'urgent': 'CRITICAL', - 'high': 'HIGH', - 'medium': 'MEDIUM', - 'normal': 'MEDIUM', - 'low': 'LOW', -}; - -const TYPE_MAP: Record = { - 'bug': 'BUG', - 'feature_request': 'FEATURE_REQUEST', - 'feature': 'FEATURE_REQUEST', - 'question': 'QUESTION', - 'integration_help': 'INTEGRATION_HELP', - 'integration': 'INTEGRATION_HELP', - 'account_issue': 'ACCOUNT_ISSUE', - 'account': 'ACCOUNT_ISSUE', - 'other': 'OTHER', -}; - -const MESSAGE_TYPE_MAP: Record = { - 'user': 'USER', - 'customer': 'USER', - 'bot': 'BOT', - 'ai': 'BOT', - 'system': 'SYSTEM', - 'auto': 'SYSTEM', -}; - -// ─── Transformed Types ────────────────────────────────────────────────────── -// These match the shape Prisma expects for create operations. - -export interface TransformedAccount { - name: string; - domain: string | null; - owner: string | null; -} - -export interface TransformedUser { - name: string; - email: string; - domain: string | null; - externalId: string | null; - source: 'ORCA'; -} - -export interface TransformedTicket { - displayId: string; - title: string; - description: string; - status: string; - priority: string; - type: string; - source: 'ORCA'; - sourceId: string; - sourceUrl: string | null; - createdAt: Date; - updatedAt: Date; -} - -export interface TransformedMessage { - author: string; - content: string; - type: string; - isAiGenerated: boolean; - attachments: unknown[] | null; - createdAt: Date; -} - -// ─── Transformers ─────────────────────────────────────────────────────────── - -export function transformAccount(orca: OrcaAccount): TransformedAccount { - return { - name: orca.name, - domain: orca.domain ?? null, - owner: orca.owner ?? null, - }; -} - -export function transformUser(orca: OrcaUser): TransformedUser { - return { - name: orca.name, - email: orca.email, - domain: orca.domain ?? null, - externalId: orca.external_id ?? null, - source: 'ORCA', - }; -} - -export function transformTicket(orca: OrcaTicket, displayId: string): TransformedTicket { - const statusKey = (orca.status ?? 'open').toLowerCase(); - const priorityKey = (orca.priority ?? 'medium').toLowerCase(); - const typeKey = (orca.type ?? 'question').toLowerCase(); - - return { - displayId, - title: orca.title, - description: orca.description ?? '', - status: STATUS_MAP[statusKey] ?? 'OPEN', - priority: PRIORITY_MAP[priorityKey] ?? 'MEDIUM', - type: TYPE_MAP[typeKey] ?? 'OTHER', - source: 'ORCA', - sourceId: orca.id, - sourceUrl: orca.source_url ?? null, - createdAt: orca.created_at ? new Date(orca.created_at) : new Date(), - updatedAt: orca.updated_at ? new Date(orca.updated_at) : new Date(), - }; -} - -export function transformMessage(orca: OrcaMessage): TransformedMessage { - const typeKey = (orca.type ?? 'user').toLowerCase(); - - return { - author: orca.author, - content: orca.content, - type: MESSAGE_TYPE_MAP[typeKey] ?? 'USER', - isAiGenerated: orca.is_ai_generated ?? false, - attachments: orca.attachments ?? null, - createdAt: orca.created_at ? new Date(orca.created_at) : new Date(), - }; -} diff --git a/scripts/lib/orca-types.ts b/scripts/lib/orca-types.ts deleted file mode 100644 index 7ba7eb4e..00000000 --- a/scripts/lib/orca-types.ts +++ /dev/null @@ -1,156 +0,0 @@ -// ─── Orca Export Data Types ───────────────────────────────────────────────── -// Types representing the shape of data exported from Orca (app.getorca.ai). -// Used by the migration script to validate and transform incoming data. - -export interface OrcaUser { - id: string; - name: string; - email: string; - domain?: string | null; - external_id?: string | null; - created_at?: string | null; -} - -export interface OrcaAccount { - id: string; - name: string; - domain?: string | null; - owner?: string | null; - created_at?: string | null; -} - -export interface OrcaMessage { - id: string; - ticket_id: string; - author: string; - content: string; - type?: string | null; // "user" | "bot" | "system" - is_ai_generated?: boolean | null; - attachments?: unknown[] | null; - created_at?: string | null; -} - -export interface OrcaTicket { - id: string; - title: string; - description: string; - status?: string | null; // "open" | "in_progress" | "waiting" | "resolved" | "closed" - priority?: string | null; // "critical" | "high" | "medium" | "low" - type?: string | null; // "bug" | "feature_request" | "question" | etc. - assignee_email?: string | null; - account_id?: string | null; - user_id?: string | null; - messages?: OrcaMessage[]; - source_url?: string | null; - created_at?: string | null; - updated_at?: string | null; -} - -export interface OrcaExport { - accounts: OrcaAccount[]; - users: OrcaUser[]; - tickets: OrcaTicket[]; -} - -// ─── Validation ───────────────────────────────────────────────────────────── - -export interface ValidationError { - entity: string; - id: string; - field: string; - message: string; -} - -export function validateOrcaExport(data: unknown): { valid: boolean; errors: ValidationError[] } { - const errors: ValidationError[] = []; - - if (typeof data !== 'object' || data === null) { - errors.push({ entity: 'export', id: '', field: 'root', message: 'Export data must be an object' }); - return { valid: false, errors }; - } - - const obj = data as Record; - - if (!Array.isArray(obj.accounts)) { - errors.push({ entity: 'export', id: '', field: 'accounts', message: 'Missing or invalid accounts array' }); - } else { - for (const account of obj.accounts) { - errors.push(...validateOrcaAccount(account)); - } - } - - if (!Array.isArray(obj.users)) { - errors.push({ entity: 'export', id: '', field: 'users', message: 'Missing or invalid users array' }); - } else { - for (const user of obj.users) { - errors.push(...validateOrcaUser(user)); - } - } - - if (!Array.isArray(obj.tickets)) { - errors.push({ entity: 'export', id: '', field: 'tickets', message: 'Missing or invalid tickets array' }); - } else { - for (const ticket of obj.tickets) { - errors.push(...validateOrcaTicket(ticket)); - } - } - - return { valid: errors.length === 0, errors }; -} - -function validateOrcaAccount(data: unknown): ValidationError[] { - const errors: ValidationError[] = []; - if (typeof data !== 'object' || data === null) { - errors.push({ entity: 'account', id: '?', field: 'root', message: 'Account must be an object' }); - return errors; - } - const obj = data as Record; - const id = typeof obj.id === 'string' ? obj.id : '?'; - if (typeof obj.id !== 'string' || obj.id.length === 0) { - errors.push({ entity: 'account', id, field: 'id', message: 'Missing or invalid id' }); - } - if (typeof obj.name !== 'string' || obj.name.length === 0) { - errors.push({ entity: 'account', id, field: 'name', message: 'Missing or invalid name' }); - } - return errors; -} - -function validateOrcaUser(data: unknown): ValidationError[] { - const errors: ValidationError[] = []; - if (typeof data !== 'object' || data === null) { - errors.push({ entity: 'user', id: '?', field: 'root', message: 'User must be an object' }); - return errors; - } - const obj = data as Record; - const id = typeof obj.id === 'string' ? obj.id : '?'; - if (typeof obj.id !== 'string' || obj.id.length === 0) { - errors.push({ entity: 'user', id, field: 'id', message: 'Missing or invalid id' }); - } - if (typeof obj.name !== 'string' || obj.name.length === 0) { - errors.push({ entity: 'user', id, field: 'name', message: 'Missing or invalid name' }); - } - if (typeof obj.email !== 'string' || obj.email.length === 0) { - errors.push({ entity: 'user', id, field: 'email', message: 'Missing or invalid email' }); - } - return errors; -} - -function validateOrcaTicket(data: unknown): ValidationError[] { - const errors: ValidationError[] = []; - if (typeof data !== 'object' || data === null) { - errors.push({ entity: 'ticket', id: '?', field: 'root', message: 'Ticket must be an object' }); - return errors; - } - const obj = data as Record; - const id = typeof obj.id === 'string' ? obj.id : '?'; - if (typeof obj.id !== 'string' || obj.id.length === 0) { - errors.push({ entity: 'ticket', id, field: 'id', message: 'Missing or invalid id' }); - } - if (typeof obj.title !== 'string' || obj.title.length === 0) { - errors.push({ entity: 'ticket', id, field: 'title', message: 'Missing or invalid title' }); - } - if (typeof obj.description !== 'string') { - errors.push({ entity: 'ticket', id, field: 'description', message: 'Missing or invalid description' }); - } - return errors; -} diff --git a/scripts/migrate-from-orca.ts b/scripts/migrate-from-orca.ts deleted file mode 100644 index 81e91883..00000000 --- a/scripts/migrate-from-orca.ts +++ /dev/null @@ -1,417 +0,0 @@ -#!/usr/bin/env npx tsx -// ─── Orca → Outpost Migration Script ─────────────────────────────────────── -// One-time migration of historical data from Orca (app.getorca.ai) to Outpost. -// -// Usage: -// npx tsx scripts/migrate-from-orca.ts --input /path/to/orca-export.json -// npx tsx scripts/migrate-from-orca.ts --input export.json --dry-run -// npx tsx scripts/migrate-from-orca.ts --rollback --confirm - -import { readFileSync } from 'fs'; -import { resolve } from 'path'; -import { PrismaClient } from '@prisma/client'; -import { validateOrcaExport, type OrcaExport } from './lib/orca-types.js'; -import { - transformAccount, - transformUser, - transformTicket, - transformMessage, -} from './lib/orca-transformer.js'; -import { - createReport, - finalizeReport, - formatReport, - type MigrationReport, -} from './lib/migration-report.js'; - -// ─── CLI Argument Parsing ─────────────────────────────────────────────────── - -interface CliArgs { - input: string | null; - dryRun: boolean; - rollback: boolean; - confirm: boolean; -} - -function parseArgs(argv: string[]): CliArgs { - const args: CliArgs = { - input: null, - dryRun: false, - rollback: false, - confirm: false, - }; - - for (let i = 2; i < argv.length; i++) { - switch (argv[i]) { - case '--input': - args.input = argv[++i] ?? null; - break; - case '--dry-run': - args.dryRun = true; - break; - case '--rollback': - args.rollback = true; - break; - case '--confirm': - args.confirm = true; - break; - } - } - - return args; -} - -// ─── Display ID Generator ─────────────────────────────────────────────────── - -async function getNextDisplayIdCounter(prisma: PrismaClient): Promise { - const lastTicket = await prisma.ticket.findFirst({ - orderBy: { displayId: 'desc' }, - select: { displayId: true }, - }); - - if (!lastTicket) return 1; - - const match = lastTicket.displayId.match(/^TKT-(\d+)$/); - return match ? parseInt(match[1], 10) + 1 : 1; -} - -function formatDisplayId(counter: number): string { - return `TKT-${counter.toString().padStart(4, '0')}`; -} - -// ─── Progress Reporting ───────────────────────────────────────────────────── - -function logProgress(label: string, current: number, total: number): void { - process.stdout.write(`\r Migrating ${label}... ${current}/${total}`); - if (current === total) { - process.stdout.write('\n'); - } -} - -// ─── Migration Logic ──────────────────────────────────────────────────────── - -async function migrateAccounts( - prisma: PrismaClient, - data: OrcaExport, - report: MigrationReport, - dryRun: boolean, -): Promise> { - const orcaIdToOutpostId = new Map(); - const total = data.accounts.length; - - for (let i = 0; i < total; i++) { - const orcaAccount = data.accounts[i]; - logProgress('accounts', i + 1, total); - - try { - const transformed = transformAccount(orcaAccount); - - if (dryRun) { - orcaIdToOutpostId.set(orcaAccount.id, `dry-run-${orcaAccount.id}`); - report.accounts.created++; - continue; - } - - // Check for existing account by name + domain to avoid duplicates - const existing = await prisma.account.findFirst({ - where: { - name: transformed.name, - ...(transformed.domain ? { domain: transformed.domain } : {}), - }, - }); - - if (existing) { - orcaIdToOutpostId.set(orcaAccount.id, existing.id); - report.accounts.skipped++; - continue; - } - - const created = await prisma.account.create({ - data: transformed, - }); - orcaIdToOutpostId.set(orcaAccount.id, created.id); - report.accounts.created++; - } catch (err) { - report.accounts.failed++; - report.accounts.errors.push({ - id: orcaAccount.id, - message: err instanceof Error ? err.message : String(err), - }); - } - } - - return orcaIdToOutpostId; -} - -async function migrateUsers( - prisma: PrismaClient, - data: OrcaExport, - report: MigrationReport, - dryRun: boolean, - accountMap: Map, -): Promise> { - const orcaIdToOutpostId = new Map(); - const total = data.users.length; - - for (let i = 0; i < total; i++) { - const orcaUser = data.users[i]; - logProgress('users', i + 1, total); - - try { - const transformed = transformUser(orcaUser); - - if (dryRun) { - orcaIdToOutpostId.set(orcaUser.id, `dry-run-${orcaUser.id}`); - report.users.created++; - continue; - } - - // Check for existing user by email - const existing = await prisma.user.findUnique({ - where: { email: transformed.email }, - }); - - if (existing) { - orcaIdToOutpostId.set(orcaUser.id, existing.id); - report.users.skipped++; - continue; - } - - // Try to link user to account via domain - let accountId: string | undefined; - if (transformed.domain) { - for (const [orcaAcctId, outpostAcctId] of accountMap.entries()) { - const orcaAcct = data.accounts.find(a => a.id === orcaAcctId); - if (orcaAcct?.domain === transformed.domain) { - accountId = outpostAcctId; - break; - } - } - } - - const created = await prisma.user.create({ - data: { - ...transformed, - ...(accountId ? { accountId } : {}), - }, - }); - orcaIdToOutpostId.set(orcaUser.id, created.id); - report.users.created++; - } catch (err) { - report.users.failed++; - report.users.errors.push({ - id: orcaUser.id, - message: err instanceof Error ? err.message : String(err), - }); - } - } - - return orcaIdToOutpostId; -} - -async function migrateTickets( - prisma: PrismaClient, - data: OrcaExport, - report: MigrationReport, - dryRun: boolean, - accountMap: Map, - userMap: Map, - startingCounter: number, -): Promise { - const total = data.tickets.length; - let counter = startingCounter; - - for (let i = 0; i < total; i++) { - const orcaTicket = data.tickets[i]; - logProgress('tickets', i + 1, total); - - try { - const displayId = formatDisplayId(counter); - const transformed = transformTicket(orcaTicket, displayId); - - if (dryRun) { - report.tickets.created++; - report.messages.total += (orcaTicket.messages ?? []).length; - counter++; - continue; - } - - // Check for existing ticket by sourceId to avoid duplicates - const existing = await prisma.ticket.findFirst({ - where: { source: 'ORCA', sourceId: orcaTicket.id }, - }); - - if (existing) { - report.tickets.skipped++; - continue; - } - - // Resolve foreign keys - const accountId = orcaTicket.account_id - ? accountMap.get(orcaTicket.account_id) ?? undefined - : undefined; - const userId = orcaTicket.user_id - ? userMap.get(orcaTicket.user_id) ?? undefined - : undefined; - - const ticket = await prisma.ticket.create({ - data: { - displayId: transformed.displayId, - title: transformed.title, - description: transformed.description, - status: transformed.status as never, - priority: transformed.priority as never, - type: transformed.type as never, - source: 'ORCA', - sourceId: transformed.sourceId, - sourceUrl: transformed.sourceUrl, - createdAt: transformed.createdAt, - updatedAt: transformed.updatedAt, - ...(accountId ? { accountId } : {}), - ...(userId ? { userId } : {}), - }, - }); - - // Migrate messages for this ticket - const messages = orcaTicket.messages ?? []; - for (const orcaMsg of messages) { - const msg = transformMessage(orcaMsg); - await prisma.message.create({ - data: { - ticketId: ticket.id, - author: msg.author, - content: msg.content, - type: msg.type as never, - isAiGenerated: msg.isAiGenerated, - attachments: msg.attachments ?? undefined, - createdAt: msg.createdAt, - }, - }); - report.messages.total++; - } - - report.tickets.created++; - counter++; - } catch (err) { - report.tickets.failed++; - report.tickets.errors.push({ - id: orcaTicket.id, - message: err instanceof Error ? err.message : String(err), - }); - } - } -} - -// ─── Rollback ─────────────────────────────────────────────────────────────── - -async function rollback(prisma: PrismaClient, confirm: boolean): Promise { - if (!confirm) { - console.error('\n Rollback requires --confirm flag to execute.'); - console.error(' Usage: npx tsx scripts/migrate-from-orca.ts --rollback --confirm\n'); - process.exit(1); - } - - console.log('\n Rolling back ORCA migration data...'); - - // Delete messages on ORCA tickets first (cascade would handle this, but be explicit) - const orcaTickets = await prisma.ticket.findMany({ - where: { source: 'ORCA' }, - select: { id: true }, - }); - const ticketIds = orcaTickets.map(t => t.id); - - // Wrap all deletes in a transaction for atomicity — either everything - // rolls back or nothing does. - const [messagesDeleted, ticketsDeleted, usersDeleted] = await prisma.$transaction([ - prisma.message.deleteMany({ - where: { ticketId: { in: ticketIds } }, - }), - prisma.ticket.deleteMany({ - where: { source: 'ORCA' }, - }), - prisma.user.deleteMany({ - where: { source: 'ORCA' }, - }), - ]); - - console.log(` Deleted ${messagesDeleted.count} messages`); - console.log(` Deleted ${ticketsDeleted.count} tickets`); - console.log(` Deleted ${usersDeleted.count} users`); - - console.log('\n Rollback complete.\n'); -} - -// ─── Main ─────────────────────────────────────────────────────────────────── - -async function main(): Promise { - const args = parseArgs(process.argv); - - const prisma = new PrismaClient(); - - try { - // Handle rollback mode - if (args.rollback) { - await rollback(prisma, args.confirm); - return; - } - - // Validate input file argument - if (!args.input) { - console.error('\n Usage: npx tsx scripts/migrate-from-orca.ts --input /path/to/orca-export.json'); - console.error(' npx tsx scripts/migrate-from-orca.ts --input export.json --dry-run'); - console.error(' npx tsx scripts/migrate-from-orca.ts --rollback --confirm\n'); - process.exit(1); - } - - // Read and parse export file - const inputPath = resolve(args.input); - console.log(`\n Reading export file: ${inputPath}`); - - let rawData: unknown; - try { - const content = readFileSync(inputPath, 'utf-8'); - rawData = JSON.parse(content); - } catch (err) { - console.error(` Failed to read/parse input file: ${err instanceof Error ? err.message : String(err)}`); - process.exit(1); - } - - // Validate data structure - const validation = validateOrcaExport(rawData); - if (!validation.valid) { - console.error('\n Validation errors:'); - for (const err of validation.errors) { - console.error(` [${err.entity} ${err.id}] ${err.field}: ${err.message}`); - } - process.exit(1); - } - - const data = rawData as OrcaExport; - - console.log(` Found: ${data.accounts.length} accounts, ${data.users.length} users, ${data.tickets.length} tickets`); - - if (args.dryRun) { - console.log(' Mode: DRY RUN (no database writes)'); - } - - // Run migration - const report = createReport(args.dryRun); - - const startingCounter = args.dryRun ? 1 : await getNextDisplayIdCounter(prisma); - - console.log(''); - const accountMap = await migrateAccounts(prisma, data, report, args.dryRun); - const userMap = await migrateUsers(prisma, data, report, args.dryRun, accountMap); - await migrateTickets(prisma, data, report, args.dryRun, accountMap, userMap, startingCounter); - - finalizeReport(report); - console.log(formatReport(report)); - } finally { - await prisma.$disconnect(); - } -} - -main().catch((err) => { - console.error('Migration failed:', err); - process.exit(1); -}); From b733ae9452416caa66c2df8285f3c65168be4994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nathan=20=F0=9F=94=B6=20Tarbert?= <66887028+NathanTarbert@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:22:44 -0500 Subject: [PATCH 2/2] docs(shadow-mode): say the worker's flag is what holds replies back --- .claude/skills/deep-read-issue/SKILL.md | 2 +- apps/discord-bot/src/lib/shadow-mode.ts | 12 +++++------- docs/deployment.md | 19 ++++++++++--------- 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/.claude/skills/deep-read-issue/SKILL.md b/.claude/skills/deep-read-issue/SKILL.md index 3c82bc61..331b88c1 100644 --- a/.claude/skills/deep-read-issue/SKILL.md +++ b/.claude/skills/deep-read-issue/SKILL.md @@ -54,7 +54,7 @@ Capture per issue: - **Surface package MATURITY explicitly** (`stable` / `deprecated` / `experimental` / `pre-release 0.x` / `beta`). If the reporter is on anything that isn't a stable current release, say so loudly — the orchestrator must put this in the card's FIRST SENTENCE (What line), not bury it, so Nathan can tell at a glance it may be a "just migrate/upgrade" case and NOT tag engineering. Output e.g. `MATURITY: deprecated (@copilotkitnext)` or `MATURITY: pre-release 0.x (@ag-ui/*)`. - **`@copilotkitnext/*` = DEPRECATED (the useAgent-era experimental v2 line).** As of 2026-06-18 the `@copilotkitnext/*` packages are deprecated on npm and merged into `@copilotkit` v2 — `@copilotkitnext/core` → `@copilotkit/core`, `@copilotkitnext/react` → `@copilotkit/react-core/v2`, `@copilotkitnext/runtime` → `@copilotkit/runtime/v2` (last publish 1.54.1; current `@copilotkit` is on the 1.6x line). **Two things follow:** (1) a reporter on `@copilotkitnext/*` is on a dead package → the version line should note `(deprecated — migrate to @copilotkit/*/v2)` and the fix plan should first check whether the bug is already gone in current `@copilotkit` v2 (often it's a "just migrate" case, not a code fix); (2) **cite the exact subpackage the reporter used, never the bare scope `@copilotkitnext`** (which isn't a valid package). Also note: coding agents frequently *invent* `@copilotkitnext` from training data because it was real during useAgent development — so only report it when the REPORTER'S OWN text uses it; don't let an agent's guess put it on the card. - **Maintainer status, quoted.** Any comment from a MEMBER / OWNER / COLLABORATOR (check authorAssociation) that states status — "fixed in 1.60.1", "closing, reopen if not", "this is a real bug", a Linear/ENT-#### ref, "PR up". Quote it with author + date. -- **Ignore the support bot for status.** `copilotkit-support-bot` "Recommended Solutions" are auto-generated guesses, NOT maintainer status or confirmation. Note bot advice only if a human endorsed it. +- **Ignore support bots for status.** Auto-generated "Recommended Solutions" comments, from `copilotkit-support-bot` or any other account, are guesses, NOT maintainer status or confirmation. Note bot advice only if a human endorsed it. - Whether the *reporter* confirmed the fix (vs a maintainer closing speculatively). - Cross-references (Discord threads, related issues, sibling-repo dup). - **TRUE COMMUNITY (by subject, not repo).** Decide whether the issue is really a CopilotKit or an AG-UI problem from *what is actually broken*, not which repo it was filed in. **Trigger:** an `ag-ui` issue whose subject/repro is a **CopilotKit** bug (it says CopilotKit chat/runtime/component breaks, or the fix shipped in a CopilotKit release) is **MIS-FILED → attribute to CopilotKit** (and the reverse). Output `COMMUNITY: CK | AG-UI` + `MIS-FILED: yes/no (filed in , true owner , because )`. **Caveat:** ownership of the broken *tool* wins over mere mentions — `create-ag-ui-app` failing is AG-UI's even though it scaffolds CopilotKit. Flag every mis-filed issue so the orchestrator lists it on the right page only. (Precedent the agent previously MISSED: `ag-ui#1891` "Illegal invocation" — an `HttpAgent` bug that breaks CopilotKit chat, fixed in CopilotKit 1.60.1 → it's CopilotKit's, not AG-UI's.) diff --git a/apps/discord-bot/src/lib/shadow-mode.ts b/apps/discord-bot/src/lib/shadow-mode.ts index ddcfca41..d0332b29 100644 --- a/apps/discord-bot/src/lib/shadow-mode.ts +++ b/apps/discord-bot/src/lib/shadow-mode.ts @@ -4,14 +4,12 @@ import { TicketSource, buildTicketSourceId, truncate } from '@copilotkit/outpost import type { ThreadChannel, Message } from 'discord.js'; /** - * Shadow mode lets Outpost run against a live server without posting replies. + * Shadow-mode handlers for the Discord bot. * - * When SHADOW_MODE=true: - * - Tickets are created in the Outpost DB as normal - * - AI responses are generated but NOT posted to Discord - * - Shadow responses are logged so their quality can be reviewed - * - * Use it to validate responses on a server before Outpost answers there. + * When SHADOW_MODE=true, the bot records tickets through these handlers instead + * of the normal ingest flow. The AI response is held back by the worker, which + * reads SHADOW_MODE itself, so set the flag on the worker too. See "Shadow mode + * (staging safety)" in docs/deployment.md. */ export function isShadowMode(): boolean { return process.env.SHADOW_MODE === 'true'; diff --git a/docs/deployment.md b/docs/deployment.md index fef121a3..4dedd2d5 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -237,15 +237,16 @@ to verify agent behavior without replying to real users. `SHADOW_MODE` is read by **more than one service**, and each one gates a different point in the flow. Set it consistently across an environment rather than on a single service: -| Service | What the flag changes | -| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `outpost-discord-bot` | At ingest. `thread-create.ts` and `message-create.ts` call `isShadowMode()` and divert to `handleShadowThreadCreate` / `handleShadowMessage`, recording the ticket and a shadow response silently instead of running the normal visible flow (`src/lib/shadow-mode.ts`). | -| `outpost-worker` | At post-back. The `AI_RESPONSE` handler checks the flag immediately before `adapter.postResponse` and persists the response as a shadow `Message` row instead of posting (`queue/src/handlers/ai-response.ts`). Also gates `ONBOARDING_DIGEST`, which posts a daily digest straight to Discord via `DISCORD_DIGEST_CHANNEL_ID` over raw REST. | - -For Discord either gate alone is enough to stop a post, so they are belt-and-braces. The -worker's gate is the one that covers **every** platform (GitHub, Slack, Teams) plus the -digest job, because that is where the adapter call lives — so a staging environment must -have it set on `outpost-worker`, not only on a bot. +| Service | What the flag changes | +| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `outpost-discord-bot` | At ingest. `thread-create.ts` and `message-create.ts` call `isShadowMode()` and divert to `handleShadowThreadCreate` / `handleShadowMessage`, recording the new ticket or reply (and, for a new thread, queueing its AI response) instead of running the normal flow (`src/lib/shadow-mode.ts`). The shadow response row itself is written by the worker. | +| `outpost-worker` | At post-back. The `AI_RESPONSE` handler checks the flag immediately before `adapter.postResponse` and persists the response as a shadow `Message` row instead of posting (`queue/src/handlers/ai-response.ts`). Also gates `ONBOARDING_DIGEST`, which posts a daily digest straight to Discord via `DISCORD_DIGEST_CHANNEL_ID` over raw REST. | + +The bot's gate does not stop the AI response: for a new thread the bot still queues the +`AI_RESPONSE` job, and a worker without the flag posts it. The worker's gate is the one that +covers **every** platform (GitHub, Slack, Teams) plus the digest job, because that is where +the adapter call lives — so a staging environment must have it set on `outpost-worker`, not +only on a bot. When adding any new outbound post path, check `SHADOW_MODE` before posting — otherwise staging will deliver to real users regardless of the flag.