import assert from 'node:assert/strict' import { readFileSync, readdirSync } from 'node:fs' import { beforeEach, describe, it } from 'node:test' // @ts-expect-error test helper is plain JS import { createStorageMock } from '../test/storage-mock.mjs' type ExecCall = { code: string; params: Record; writable?: boolean } const calls: ExecCall[] = [] let executeImpl: (call: ExecCall) => unknown = () => ({ ok: true, result: {} }) let mock = createStorageMock() ;(globalThis as any).__kodyMocks['kody:runtime'] = { packageStorage: () => mock.storage, kody: { execute: async (call: ExecCall) => { calls.push(call) return executeImpl(call) }, }, } const { resetSchemaCacheForTests } = await import('./store.ts') const { default: queue } = await import('./queue.ts') const { default: list } = await import('./list.ts') const { default: digest } = await import('./digest.ts') const { default: status } = await import('./status.ts') const { default: override } = await import('./override.ts') const { default: fallbackDigest, DEFAULT_FALLBACK_CHANNEL_ID } = await import('./fallback-digest.ts') beforeEach(() => { mock = createStorageMock() resetSchemaCacheForTests() calls.length = 0 executeImpl = () => ({ ok: true, result: { item: { id: 'wom-1' } } }) }) const night = (iso: string) => ({ now: iso }) describe('queue', () => { it('stores items and lists them as unread', async () => { await queue({ bot: 'Cole', kind: 'done', title: 'Fixed 2 Sentry issues', ...night('2026-10-18T06:00:00Z') }) await queue({ bot: 'Pam', kind: 'fyi', title: 'X mention handled', ...night('2026-10-18T07:00:00Z') }) const unread = await list() assert.equal(unread.count, 2) assert.deepEqual(unread.items.map((i: any) => i.bot), ['Cole', 'Pam']) assert.equal(unread.since, null) }) it('validates kind, priority, and link', async () => { await assert.rejects(queue({ bot: 'Cole', kind: 'nope' as any, title: 'x' }), /kind must be/) await assert.rejects(queue({ bot: 'Cole', kind: 'fyi', priority: 'meh' as any, title: 'x' }), /priority/) await assert.rejects(queue({ bot: 'Cole', kind: 'needs-decision', title: 'x' }), /link is required/) await assert.rejects(queue({ bot: 'Cole', kind: 'fyi', title: 'x', link: 'ftp://x' }), /http/) }) it('refuses Lilly and Imogen without writing', async () => { for (const bot of ['Lilly', 'imogen', ' IMOGEN ']) { const result = await queue({ bot, kind: 'done', title: 'x' }) assert.equal(result.queued, false) assert.equal((result as any).excluded, true) } assert.equal((await list()).count, 0) }) it('accepts legacy kent-request', async () => { const result = await queue({ bot: 'Cole', kind: 'kent-request', title: 'Auth refactor' }) assert.equal(result.queued, true) }) }) describe('waiting-on-me mirror', () => { it('mirrors needs-decision via execute with a static waiting-on-me/create import', async () => { const result = await queue({ bot: 'Cole', kind: 'needs-decision', priority: 'urgent', title: 'Approve rollback cleanup PR #2412', link: 'https://github.com/kody-hq/kody/pull/2412', detail: 'Prod stable since 2:10 AM', deadline: '2026-10-18T18:00:00Z', }) assert.equal(calls.length, 1) assert.match(calls[0].code, /import create from 'kody:@kentcdodds\/waiting-on-me\/create'/) assert.equal(calls[0].writable, true) const p = calls[0].params assert.equal(p.nativeId, `quiet-hours:${result.item!.id}`) assert.equal(p.idempotencyKey, p.nativeId) assert.equal(p.actionUrl, 'https://github.com/kody-hq/kody/pull/2412') assert.equal(p.urgency, 'critical') assert.equal(p.title, 'Cole: Approve rollback cleanup PR #2412') assert.equal(p.summary, 'Prod stable since 2:10 AM') assert.equal(p.actor, 'agent') assert.deepEqual(result.waitingOnMe, { ok: true, id: 'wom-1' }) const stored = (await list()).items[0] assert.deepEqual(stored.waitingOnMe, { ok: true, id: 'wom-1' }) }) it('does not mirror done/fyi', async () => { await queue({ bot: 'Cole', kind: 'done', title: 'x' }) await queue({ bot: 'Cole', kind: 'fyi', title: 'y' }) assert.equal(calls.length, 0) }) it('a failing mirror never fails the queue call', async () => { executeImpl = () => ({ ok: false, error: 'waiting-on-me down' }) const result = await queue({ bot: 'Felix', kind: 'needs-decision', title: 'Categorize receipts', link: 'https://example.com/r' }) assert.equal(result.queued, true) assert.deepEqual(result.waitingOnMe, { ok: false, error: 'waiting-on-me down' }) executeImpl = () => { throw new Error('boom') } const second = await queue({ bot: 'Felix', kind: 'needs-decision', title: 'Again', link: 'https://example.com/r' }) assert.equal(second.queued, true) assert.equal(second.waitingOnMe?.ok, false) }) }) describe('digest ordering and delivery', () => { it('orders urgent-resolved, deadline today, decisions, then done/fyi; marks delivered', async () => { const now = '2026-10-18T14:00:00Z' // Sun 8:00 AM MDT await queue({ bot: 'Connie', kind: 'done', title: 'Thumbnail brief', now: '2026-10-18T05:00:00Z' }) await queue({ bot: 'Felix', kind: 'needs-decision', priority: 'normal', title: 'Receipts', link: 'https://e.com/1', now: '2026-10-18T05:01:00Z' }) await queue({ bot: 'Pam', kind: 'needs-decision', title: 'Sponsor reply', link: 'https://e.com/2', deadline: '2026-10-18T18:00:00Z', now: '2026-10-18T05:02:00Z' }) await queue({ bot: 'Cole', kind: 'done', priority: 'urgent', title: 'Rolled back prod 5xx', now: '2026-10-18T05:03:00Z' }) await queue({ bot: 'Cole', kind: 'needs-decision', priority: 'high', title: 'Approve PR #2412', link: 'https://e.com/3', now: '2026-10-18T05:04:00Z' }) await queue({ bot: 'Pam', kind: 'needs-decision', title: 'Next-week deadline', link: 'https://e.com/4', deadline: '2026-10-25T18:00:00Z', now: '2026-10-18T05:05:00Z' }) await queue({ bot: 'Cole', kind: 'kent-request', title: 'Auth refactor', now: '2026-10-18T05:06:00Z' }) const preview = await digest({ dryRun: true, now }) assert.equal(preview.dryRun, true) assert.equal((await list()).count, 7, 'dry run marks nothing') const d = await digest({ via: 'kody-routine', now }) assert.deepEqual(d.buckets.map((b: any) => b.bucket), ['urgent-resolved', 'deadline-today', 'decision', 'fyi']) assert.deepEqual(d.items.map((i: any) => i.title), [ 'Rolled back prod 5xx', 'Sponsor reply', 'Approve PR #2412', 'Next-week deadline', 'Receipts', 'Thumbnail brief', 'Auth refactor', ]) assert.deepEqual(d.counts, { total: 7, done: 2, needsDecision: 4, fyi: 1 }) assert.match(d.text, /^Morning\. Overnight: 2 done, 4 need you\./) assert.match(d.text, /Needs you \(decisions\):\n1\. Cole: Approve PR #2412/) assert.ok(d.digestId) assert.equal((await list()).count, 0) assert.equal((await list()).since, '2026-10-18T14:00:00.000Z') }) it('empty digest says quiet night and still records delivery', async () => { const d = await digest({ now: '2026-10-18T14:00:00Z' }) assert.equal(d.text, 'Quiet night. Nothing needs you.') assert.equal((await list()).lastDigest?.via, 'digest') }) }) describe('status and override', () => { it('clock decides without override; excluded bots never quiet', async () => { const s = await status({ now: '2026-10-18T06:00:00Z' }) assert.deepEqual(s, { quiet: true, until: '2026-10-18T14:00:00.000Z', override: null }) const lilly = await status({ bot: 'Lilly', now: '2026-10-18T06:00:00Z' }) assert.equal(lilly.quiet, false) assert.equal(lilly.excluded, true) }) it('off / on / clear', async () => { const off = await override({ mode: 'off', by: 'kent', now: '2026-10-18T05:40:00Z' }) assert.equal(off.override?.expiresAt, '2026-10-19T04:00:00.000Z') assert.equal((await status({ now: '2026-10-18T06:00:00Z' })).quiet, false) assert.equal((await status({ now: '2026-10-19T04:00:00Z' })).quiet, true, 'expires at next 10 PM') await override({ mode: 'on', now: '2026-10-18T06:10:00Z' }) const on = await status({ now: '2026-10-18T06:11:00Z' }) assert.equal(on.quiet, true) assert.equal(on.override?.mode, 'on') await override('clear') assert.equal((await status({ now: '2026-10-18T06:12:00Z' })).override, null) await assert.rejects(override({ mode: 'later' as any }), /override mode/) }) it('storage failure degrades to the clock instead of throwing', async () => { mock.failNextCalls(10) const s = await status({ now: '2026-10-18T06:00:00Z' }) assert.equal(s.quiet, true) assert.equal(s.degraded, true) }) }) describe('fallback-digest job', () => { it('skips while still quiet and when the digest was delivered this window', async () => { assert.match(String((await fallbackDigest({ now: '2026-10-18T13:00:00Z' })).skipped), /still quiet/) await digest({ now: '2026-10-18T14:00:00Z' }) const r = await fallbackDigest({ now: '2026-10-18T14:15:00Z' }) assert.equal(r.skipped, 'digest already delivered') assert.equal(calls.length, 0) }) it("ignores yesterday's digest and posts a plain digest to #reports via discord post-message", async () => { await digest({ now: '2026-10-17T14:00:00Z' }) // yesterday await queue({ bot: 'Cole', kind: 'needs-decision', title: 'Approve PR', link: 'https://e.com/p', now: '2026-10-18T06:00:00Z' }) calls.length = 0 executeImpl = () => ({ ok: true, result: { id: 'msg-1' } }) const r = await fallbackDigest({ now: '2026-10-18T14:15:00Z' }) assert.equal(r.posted, true) assert.equal(calls.length, 1) assert.match(calls[0].code, /import postMessage from 'kody:@kentcdodds\/discord\/post-message'/) assert.equal(calls[0].params.channelId, DEFAULT_FALLBACK_CHANNEL_ID) assert.equal(DEFAULT_FALLBACK_CHANNEL_ID, '1530233790516039881') assert.match(calls[0].params.content, /1\. Cole: Approve PR/) assert.ok(calls[0].params.content.length <= 2000) assert.equal((await list()).count, 0) assert.equal((await list()).lastDigest?.via, 'discord-fallback') }) it('a failed Discord post marks nothing delivered', async () => { await queue({ bot: 'Cole', kind: 'done', title: 'x', now: '2026-10-18T06:00:00Z' }) executeImpl = () => ({ ok: false, error: 'discord down' }) await assert.rejects(fallbackDigest({ now: '2026-10-18T14:15:00Z' }), /discord down/) assert.equal((await list()).count, 1) }) it('dryRun builds without posting', async () => { const r = await fallbackDigest({ now: '2026-10-18T14:15:00Z', dryRun: true }) assert.equal(r.dryRun, true) assert.equal(calls.length, 0) }) it('long digests are truncated under the Discord limit', async () => { for (let i = 0; i < 80; i += 1) { await queue({ bot: 'Cole', kind: 'done', title: `Finished task number ${i} with a long-ish title`, now: '2026-10-18T06:00:00Z' }) } const r = await fallbackDigest({ now: '2026-10-18T14:15:00Z', dryRun: true }) assert.ok(r.content!.length <= 2000, String(r.content!.length)) assert.match(r.content!, /and \d+ more/) }) }) describe('fetch hygiene', () => { it('every direct fetch in src sends x-kody-secret-resolution: headers-only', () => { for (const file of readdirSync(new URL('.', import.meta.url))) { if (!file.endsWith('.ts') || file.endsWith('.test.ts')) continue const source = readFileSync(new URL(file, import.meta.url), 'utf8') const fetches = source.match(/\bfetch\(/g)?.length ?? 0 const headers = source.match(/'x-kody-secret-resolution': 'headers-only'/g)?.length ?? 0 assert.ok(headers >= fetches, `${file}: ${fetches} fetch call(s), ${headers} headers-only header(s)`) } }) })