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/', hostedUrl: 'https://kody-factory--kody.kody.run/' }; export async function credential(key) { throw new Error('credential not mapped: ' + key); } export async function credentials() { return [] } export const kody = {}; export const workflows = null; ` registerHooks({ resolve(spec, ctx, next) { 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 { reportOnCard, setCardReportDepsForTests, cardUrl } = await import('./report.ts') const { saveJson, loadJson, storageKeys } = await import('../lib/storage.ts') const { default: entry } = await import('../app/entry.ts') const { agentHandoff } = await import('../core/orchestrator.ts') const { cardWakePrompt } = await import('../events/cards.ts') const reset = () => (globalThis as { __factoryStore?: Map }).__factoryStore?.clear() function card(id: string, extra: Record = {}) { const at = '2026-11-22T00:00:00.000Z' return { id, projectId: 'kody', title: 'Fix the retry loop', body: 'b', state: 'running', priority: 2, needsKent: false, rank: 20, source: 'manual', externalId: null, fingerprint: id, signalIds: [], labels: [], repoRef: 'kody-hq/kody', planCardId: null, runId: 'r1', createdAt: at, updatedAt: at, events: [], shadow: false, ...extra, } } async function seed(...items: Array>) { await saveJson(storageKeys.LEDGER_KEY, { version: 1, items: Object.fromEntries(items.map((i) => [i.id, i])) }) } test('report appends to the card, moves it, records ship-pr, and pushes a card deep link', async () => { reset() await seed(card('wi_a')) const sent: Array> = [] setCardReportDepsForTests({ sendPush: async (m) => { sent.push(m as unknown as Record); return { ok: true, sent: 1, failed: 0, removed: 0, errors: [] } } }) const r = await reportOnCard({ cardId: 'wi_a', outcome: 'shipped', summary: 'Merged and deployed.', prUrl: 'https://github.com/kody-hq/kody/pull/42', agent: { kind: 'devin', url: 'https://app.devin.ai/sessions/s1', name: 'Devin' }, links: ['https://kody.codes/x', 'javascript:alert(1)'], }) assert.equal(r.to, 'verifying') assert.equal(r.cardUrl, 'https://kody-factory--kody.kody.run/c/wi_a') assert.equal(r.shipPr, 'recorded') assert.deepEqual(r.push, { ok: true, sent: 1, failed: 0, removed: 0, errors: [] }) assert.equal(sent[0]!.path, '/c/wi_a') assert.match(String(sent[0]!.title), /^Shipped: Fix the retry loop/) const ledger = await loadJson<{ items: Record; events: Array<{ reason: string; meta?: { report?: { links?: unknown[] } } }> }> }>(storageKeys.LEDGER_KEY, { items: {} }) const item = ledger.items.wi_a! assert.equal(item.state, 'verifying') assert.equal(item.pr?.url, 'https://github.com/kody-hq/kody/pull/42') assert.ok(item.links?.some((l) => l.url === 'https://app.devin.ai/sessions/s1')) assert.equal(item.events.at(-1)!.reason, 'Shipped: Merged and deployed.') assert.equal(item.events.at(-1)!.meta?.report?.links?.length, 1) const ship = await loadJson<{ events: Array<{ kind: string; prKey?: string }> }>('factory:ship-pr:v1', { events: [] }) assert.ok(JSON.stringify(ship).includes('summary_sent')) setCardReportDepsForTests(null) }) test('prUrl finds the card; blocked moves it to needs you; notify:false sends nothing', async () => { reset() await seed(card('wi_b', { pr: { url: 'https://github.com/kody-hq/kody/pull/7' } })) let calls = 0 setCardReportDepsForTests({ sendPush: async () => { calls++; return { ok: true, sent: 0, failed: 0, removed: 0, errors: [] } } }) const r = await reportOnCard({ prUrl: 'https://github.com/kody-hq/kody/pull/7', status: 'Blocked', summary: 'Needs a token.', notify: false } as never) assert.equal(r.cardId, 'wi_b') assert.equal(r.to, 'needs-kent') assert.equal(calls, 0) await assert.rejects(reportOnCard({ prUrl: 'https://github.com/kody-hq/kody/pull/999', outcome: 'done', summary: 'x' }), /no card is linked/) await assert.rejects(reportOnCard({ cardId: 'wi_b', outcome: 'nope' as never, summary: 'x' }), /outcome must be/) await assert.rejects(reportOnCard({ cardId: 'wi_b', outcome: 'done', summary: ' ' }), /summary is required/) setCardReportDepsForTests(null) }) test('dry run writes nothing; progress keeps the state; shipped cards stay shipped', async () => { reset() await seed(card('wi_c'), card('wi_d', { state: 'shipped' })) const dry = await reportOnCard({ cardId: 'wi_c', outcome: 'done', summary: 'x', dryRun: true }) assert.equal(dry.persisted, false) const l1 = await loadJson<{ items: Record }>(storageKeys.LEDGER_KEY, { items: {} }) assert.equal(l1.items.wi_c!.events.length, 0) setCardReportDepsForTests({ sendPush: async () => ({ ok: true, sent: 0, failed: 0, removed: 0, errors: [], skipped: 'no subscribed devices' }) }) assert.equal((await reportOnCard({ cardId: 'wi_c', outcome: 'progress', summary: 'halfway' })).to, 'running') assert.equal((await reportOnCard({ cardId: 'wi_d', outcome: 'failed', summary: 'late' })).to, 'shipped') setCardReportDepsForTests(null) assert.equal(cardUrl('a b', 'https://x.example/'), 'https://x.example/c/a%20b') }) test('app: /cards/ redirects to the work view and /api/cards/ returns the card', async () => { reset() await seed(card('wi_e')) const red = await entry.fetch(new Request('https://kody-factory--kody.kody.run/apps/factory/cards/wi_e')) assert.equal(red.status, 302) assert.match(red.headers.get('location') ?? '', /\/work\?card=wi_e$/) const ok = await entry.fetch(new Request('https://kody-factory--kody.kody.run/apps/factory/api/cards/wi_e')) assert.equal(ok.status, 200) assert.equal(((await ok.json()) as { item: { id: string } }).item.id, 'wi_e') const missing = await entry.fetch(new Request('https://kody-factory--kody.kody.run/apps/factory/api/cards/wi_zzz')) assert.equal(missing.status, 404) }) test('agent instructions point at the card report, not Discord', () => { const handoff = agentHandoff('wi_f') assert.match(handoff, /cards\/report/) assert.match(handoff, /wi_f/) assert.doesNotMatch(handoff, /discord/i) const wake = cardWakePrompt({ title: 't', body: 'b', priority: 1, idempotencyKey: 'k' } as never, 'wi_g', 'outage') assert.match(wake, /cards\/report/) assert.match(wake, /wi_g/) }) test('notification badge: white-on-transparent PNG served with a long cache; SW uses it and the color icon', async () => { const { BADGE_PATH, badgePng } = await import('../app/badge.ts') const { renderServiceWorker } = await import('../app/pwa.ts') const png = badgePng() assert.deepEqual([...png.slice(1, 4)], [0x50, 0x4e, 0x47]) const res = await entry.fetch(new Request(`https://kody-factory--kody.kody.run/apps/factory${BADGE_PATH}`)) assert.equal(res.status, 200) assert.equal(res.headers.get('content-type'), 'image/png') assert.match(res.headers.get('cache-control') ?? '', /max-age=31536000, immutable/) assert.equal((await res.arrayBuffer()).byteLength, png.length) const sw = renderServiceWorker('test') assert.match(sw, /badge: BADGE,/) assert.match(sw, /icon: BASE \+ '\/_assets\/icon-192\.png'/) assert.ok(sw.includes(JSON.stringify(BADGE_PATH))) })