import assert from 'node:assert/strict' import { registerHooks } from 'node:module' import { test } from 'node:test' const STUB = ` const store = globalThis.__factoryStore ??= new Map(); export const packageStorage = () => ({ async get(k) { return store.get(k) ?? null }, async set(k, v) { store.set(k, JSON.stringify(v)) }, }); export const packageContext = { appBasePath: '/apps/factory/' }; export async function credential(key) { throw new Error('credential not mapped: ' + key); } export async function credentials() { return [] } export const kody = {}; ` registerHooks({ resolve(spec, ctx, next) { // Wake alerts can post to Discord; tests stub it (wake-transport tests also swap it out). if (spec === 'kody:@kody/discord/post-message') return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true })')}`, shortCircuit: true } if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true } return next(spec, ctx) }, }) const { setDispatchForTests } = await import('./emit.ts') const { routeWake, handleWakeResult, reconcilePendingWakes, loadPending, listWakeAlerts, setAlertDepsForTests, WAKE_UNDELIVERED_LABEL } = await import('./wake-transport.ts') const { patchSettings, loadSettings } = await import('../lib/settings.ts') const { default: selfTest } = await import('../exports/events-self-test.ts') const { saveJson, loadJson, storageKeys } = await import('../lib/storage.ts') type Sent = { topic: string; idempotencyKey: string; payload: Record } const sent: Sent[] = [] let failEmit = false setDispatchForTests(async (input) => { if (failEmit) throw new Error('queue down') sent.push(input) return { status: 'enqueued' } }) const discord: Array<{ channelId: string; content: string }> = [] setAlertDepsForTests({ postDiscord: async (m) => { discord.push(m) } }) function reset() { sent.length = 0 discord.length = 0 failEmit = false ;(globalThis as { __factoryStore?: Map }).__factoryStore?.clear() } const relayEnv = (requestId: string, payload: Record = {}, kodyId = 'wake-relay') => ({ event: 'x', source: { type: 'package', kody_id: kodyId }, payload: { requestId, role: 'package-triage', dryRun: false, ...payload }, }) const input = (ref = 'fp1', bot = 'patch') => ({ source: 'health' as const, bot, prompt: 'hello', reason: 'r', ref }) test('settings: wakeAlertMinutes defaults to 5, reads the older fallback value, and clamps', async () => { reset() assert.equal((await loadSettings()).wakeAlertMinutes, 5) const raw = await loadJson>(storageKeys.SETTINGS_KEY, {}) await saveJson(storageKeys.SETTINGS_KEY, { ...raw, eventWakeFallbackMinutes: 7 }) assert.equal((await loadSettings()).wakeAlertMinutes, 7) await patchSettings({ wakeAlertMinutes: 999 }) assert.equal((await loadSettings()).wakeAlertMinutes, 60) }) test('every bot goes through the relay: one real request, pending recorded, delivered marks it', async () => { reset() for (const bot of ['patch', 'cole', 'pam']) { const r = await routeWake(input(`fp-${bot}`, bot)) assert.equal(r.ok, true) } assert.equal(sent.length, 3) assert.deepEqual(sent.map((e) => e.payload.bot), ['patch', 'cole', 'pam']) for (const e of sent) { assert.equal(e.topic, '@kody/factory.wake.requested') assert.equal(e.payload.dryRun, false) assert.equal(e.payload.shadow, false) } assert.equal(sent[1]!.payload.role, 'platform') const id = String(sent[0]!.payload.requestId) assert.equal((await loadPending(id))!.status, 'pending') assert.equal((await handleWakeResult('delivered', relayEnv(id, { httpStatus: 200 }))).status, 'delivered') // A later answer for the same id changes nothing. assert.equal((await handleWakeResult('failed', relayEnv(id, { reason: 'late' }))).handled, false) assert.equal((await listWakeAlerts()).length, 0) }) test('a role-only request carries no bot so the relay routes it', async () => { reset() await routeWake({ source: 'outage', role: 'outage', prompt: 'p', reason: 'r', ref: 'k' }) assert.equal(sent[0]!.payload.role, 'outage') assert.equal('bot' in sent[0]!.payload, false) }) test('relay wake.failed raises one alert, marks the card, posts Discord when on, never posts to a bot', async () => { reset() await patchSettings({ discordNotificationsEnabled: true, discordNotificationsChannelId: 'chan' }) const ledger = await loadJson<{ items: Record }>(storageKeys.LEDGER_KEY, { items: {} }) ledger.items.wi_1 = { id: 'wi_1', projectId: 'kody', title: 't', body: '', state: 'inbox', labels: [], events: [], updatedAt: new Date().toISOString() } await saveJson(storageKeys.LEDGER_KEY, ledger) const r = await routeWake({ ...input('c1', 'cole'), cardId: 'wi_1' }) const done = await handleWakeResult('failed', relayEnv(r.requestId, { reason: 'unknown bot cole: not in the relay roster' })) assert.equal(done.status, 'failed') const alerts = await listWakeAlerts() assert.equal(alerts.length, 1) assert.equal(alerts[0]!.status, 'failed') assert.match(alerts[0]!.reason, /not in the relay roster/) assert.equal(alerts[0]!.cardMarked, true) assert.equal(alerts[0]!.discord, 'sent') assert.equal(discord.length, 1) assert.match(discord[0]!.content, /WAKE NOT DELIVERED/) const after = await loadJson<{ items: Record }>(storageKeys.LEDGER_KEY, { items: {} }) assert.ok(after.items.wi_1!.labels.includes(WAKE_UNDELIVERED_LABEL)) assert.equal(after.items.wi_1!.events.length, 1) assert.equal(sent.length, 1, 'no second request and no direct post') }) test('no relay answer in wakeAlertMinutes raises an undelivered alert once', async () => { reset() const r = await routeWake(input('slow')) const later = Date.now() + 6 * 60_000 const first = await reconcilePendingWakes(later) assert.deepEqual(first.alerted.map((a) => a.requestId), [r.requestId]) assert.equal((await loadPending(r.requestId))!.status, 'undelivered') const second = await reconcilePendingWakes(later + 60_000) assert.equal(second.alerted.length, 0) assert.equal((await listWakeAlerts())[0]!.status, 'undelivered') assert.equal((await listWakeAlerts())[0]!.discord, 'off') }) test('an emit failure returns ok:false and raises an emit-failed alert', async () => { reset() failEmit = true const r = await routeWake(input('down')) assert.equal(r.ok, false) assert.equal((await loadPending(r.requestId))!.status, 'emit-failed') assert.equal((await listWakeAlerts())[0]!.status, 'emit-failed') }) test('results from a package other than wake-relay are ignored', async () => { reset() const r = await routeWake(input('x')) const res = await handleWakeResult('failed', relayEnv(r.requestId, {}, 'impostor')) assert.equal(res.handled, false) assert.equal((await loadPending(r.requestId))!.status, 'pending') }) test('a dryRun-only delivered answer for a real request raises an alert', async () => { reset() const r = await routeWake(input('d')) const res = await handleWakeResult('delivered', relayEnv(r.requestId, { dryRun: true })) assert.equal(res.status, 'failed') assert.match((await listWakeAlerts())[0]!.reason, /dryRun only/) }) test('self-test: dry by default; live once per 24 hours, alerts skip Discord', async () => { reset() const dry = await selfTest({}) assert.equal(sent[0]!.payload.dryRun, true) assert.equal((dry as { dryRun?: boolean }).dryRun, true) const live = await selfTest({ live: true, bot: 'cole', note: 'n' }) assert.equal((live as { ok: boolean }).ok, true) assert.equal(sent[1]!.payload.bot, 'cole') assert.equal(sent[1]!.payload.dryRun, false) assert.match(String(sent[1]!.payload.prompt), /No action needed, nothing to file, do not reply/) const again = await selfTest({ live: true }) assert.equal((again as { ok: boolean }).ok, false) await patchSettings({ discordNotificationsEnabled: true, discordNotificationsChannelId: 'chan' }) await handleWakeResult('failed', relayEnv(String((live as { requestId: string }).requestId), { reason: 'x' })) assert.equal((await listWakeAlerts())[0]!.discord, 'skipped') assert.equal(discord.length, 0) })