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)) }, async sql() { throw new Error('sql not stubbed') }, }); 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) { if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true } if (spec.startsWith('kody:@kody/')) return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true })')}`, shortCircuit: true } return next(spec, ctx) }, }) const { setShadowStoreForTests } = await import('./shadow-store.ts') const { setIngestForTests } = await import('./bridge.ts') const { handleGithubEvent, GITHUB_EVENT_TOPICS, toGithubJson, normalizeGithubEventsMode } = await import('./handle.ts') const { default: report, buildShadowReport } = await import('./report.ts') const { default: issuesWebhook } = await import('../webhooks/github-issues.ts') const { default: ciWebhook } = await import('../webhooks/github-ci.ts') const { patchSettings, loadSettings } = await import('../lib/settings.ts') const { upsertProject } = await import('../projects/config.ts') const { loadJson, storageKeys } = await import('../lib/storage.ts') const pkg = (await import('../../package.json', { with: { type: 'json' } })).default as { kody: { subscriptions: Record } } type Row = { deliveryId: string; side: 'webhook' | 'event'; decision: string; topic: string; at: string; detail: string } const rows = new Map() setShadowStoreForTests({ async put(r) { rows.set(`${r.deliveryId}|${r.side}`, r) }, async recent(limit) { return [...rows.values()].sort((a, b) => b.at.localeCompare(a.at)).slice(0, limit) }, }) const bridged: Array<{ event: string; deliveryId: string }> = [] setIngestForTests(async (input) => { bridged.push({ event: input.event, deliveryId: input.deliveryId }) if (input.event === 'issues') return { ok: true, emitted: [{ topic: `@kody/github.issue.${(input.json as { action: string }).action}` }] } if (input.event === 'issue_comment') return { ok: true, emitted: [{ topic: '@kody/github.issue.commented' }] } return { ok: true, emitted: [] , ignored: 'x' } }) const repository = { full_name: 'kody-hq/kody', name: 'kody', owner: { login: 'kody-hq' } } const issue = (n: number, extra: Record = {}) => ({ number: n, title: `Issue ${n}`, body: 'b', state: 'open', labels: [{ name: 'bug' }], html_url: `https://github.com/kody-hq/kody/issues/${n}`, ...extra }) const headers = (event: string, id: string) => ({ 'X-GitHub-Event': event, 'X-GitHub-Delivery': id }) /** The payload @kody/github would emit for the same delivery (contract shape). */ const eventPayload = (id: string, action: string, i: ReturnType) => ({ deliveryId: id, event: 'issues', action, repo: { fullName: 'kody-hq/kody', owner: 'kody-hq', name: 'kody', defaultBranch: 'main' }, issue: { number: i.number, title: i.title, body: i.body, state: i.state, labels: ['bug'], htmlUrl: i.html_url, isPullRequest: false }, }) const envelope = (payload: Record, kodyId = 'github') => ({ event: 't', source: { type: 'package', kody_id: kodyId }, idempotency_key: `github:${payload.deliveryId}`, payload }) const ledgerSize = async () => Object.keys((await loadJson<{ items: Record }>(storageKeys.LEDGER_KEY, { items: {} })).items ?? {}).length await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'kody-hq__kody', repoRef: 'kody-hq/kody', host: 'github', enabled: true }] } as never) await patchSettings({ pilotScope: { mode: 'allowlist', projectIds: ['kody'], repoRefs: ['kody-hq/kody'] } }) test('every GitHub event topic has a declared subscription handler', () => { for (const t of Object.values(GITHUB_EVENT_TOPICS)) assert.ok(pkg.kody.subscriptions[t]?.handler, t) }) test('settings default to shadow, bridge on, source github', async () => { const s = await loadSettings() assert.equal(s.githubEventsMode, 'shadow') assert.equal(s.githubEventsBridge, true) assert.equal(s.githubEventsSource, 'github') assert.equal(normalizeGithubEventsMode('nope'), 'shadow') }) test('shadow: webhook does the work and forwards; the event records the same decision with no writes', async () => { const i = issue(101) const live = (await issuesWebhook({ request: { headers: headers('issues', 'd-101'), json: { action: 'opened', issue: i, repository } } })) as Record assert.equal((live.created as string[]).length, 1) assert.deepEqual(bridged.at(-1), { event: 'issues', deliveryId: 'd-101' }) const before = await ledgerSize() const ev = (await handleGithubEvent(GITHUB_EVENT_TOPICS.issueOpened, envelope(eventPayload('d-101', 'opened', i)))) as Record assert.equal(ev.mode, 'shadow') assert.equal(await ledgerSize(), before) assert.equal(rows.get('d-101|webhook')?.decision, 'ingest:kody:kody-hq/kody') assert.equal(rows.get('d-101|event')?.decision, 'ingest:kody:kody-hq/kody') // Close: the webhook drops the card first; the event still classifies the same way. await issuesWebhook({ request: { headers: headers('issues', 'd-102'), json: { action: 'closed', issue: { ...i, state: 'closed' }, repository } } }) await handleGithubEvent(GITHUB_EVENT_TOPICS.issueClosed, envelope(eventPayload('d-102', 'closed', { ...i, state: 'closed' }))) // Out of scope repo: both skip with the same reason. const other = { full_name: 'o/x', name: 'x', owner: { login: 'o' } } await issuesWebhook({ request: { headers: headers('issues', 'd-103'), json: { action: 'opened', issue: issue(5), repository: other } } }) await handleGithubEvent(GITHUB_EVENT_TOPICS.issueOpened, envelope({ ...eventPayload('d-103', 'opened', issue(5)), repo: { fullName: 'o/x', owner: 'o', name: 'x' } })) // Comments are not mirrored on purpose. await issuesWebhook({ request: { headers: headers('issue_comment', 'd-104'), json: { action: 'deleted', issue: i, comment: { id: 1 }, repository } } }) const r = await report({}) assert.equal(r.matched, 3, JSON.stringify(r.mismatched)) assert.equal(r.mismatched.length, 0) assert.equal(r.notMirrored, 1) }) test('a deleted comment never drops the issue card', async () => { const i = issue(150) await issuesWebhook({ request: { headers: headers('issues', 'd-150'), json: { action: 'opened', issue: i, repository } } }) const r = (await issuesWebhook({ request: { headers: headers('issue_comment', 'd-151'), json: { action: 'deleted', issue: i, comment: { id: 9 }, repository } } })) as Record assert.equal(r.skipped, true) assert.match(String(r.reason), /comment deleted/) }) test('wrong emitter is refused and off mode ignores events', async () => { const r = (await handleGithubEvent(GITHUB_EVENT_TOPICS.issueOpened, envelope(eventPayload('d-200', 'opened', issue(200)), 'not-github'))) as Record assert.equal(r.ok, false) await patchSettings({ githubEventsMode: 'off' }) const off = (await handleGithubEvent(GITHUB_EVENT_TOPICS.issueOpened, envelope(eventPayload('d-201', 'opened', issue(201))))) as Record assert.equal(off.skipped, true) await patchSettings({ githubEventsMode: 'shadow' }) }) test('live: the webhook only forwards and the event files and drops the card', async () => { await patchSettings({ githubEventsMode: 'live' }) const i = issue(300) const before = await ledgerSize() const wh = (await issuesWebhook({ request: { headers: headers('issues', 'd-300'), json: { action: 'opened', issue: i, repository } } })) as Record assert.equal(wh.forwardedOnly, true) assert.equal(await ledgerSize(), before) const ev = (await handleGithubEvent(GITHUB_EVENT_TOPICS.issueOpened, envelope(eventPayload('d-300', 'opened', i)))) as Record assert.equal((ev.created as string[]).length, 1) assert.equal(await ledgerSize(), before + 1) const again = (await handleGithubEvent(GITHUB_EVENT_TOPICS.issueUpdated, envelope(eventPayload('d-301', 'labeled', i)))) as Record assert.equal((again.created as string[]).length, 0) const closed = (await handleGithubEvent(GITHUB_EVENT_TOPICS.issueClosed, envelope(eventPayload('d-302', 'closed', { ...i, state: 'closed' })))) as Record assert.equal(closed.change, 'dropped') await patchSettings({ githubEventsMode: 'shadow' }) }) test('CI: shadow plans without writing; the webhook path still ingests red runs', async () => { const before = await ledgerSize() const payload = { deliveryId: 'd-400', event: 'workflow_run', action: 'completed', repo: { fullName: 'kody-hq/kody', owner: 'kody-hq', name: 'kody' }, ci: { kind: 'workflow_run', conclusion: 'failure', failed: true, headSha: 'abc', headBranch: 'main' } } const ev = (await handleGithubEvent(GITHUB_EVENT_TOPICS.ciCompleted, envelope(payload))) as Record assert.deepEqual(ev.wouldIngest, ['ci-failure:kody-hq/kody:main:abc']) assert.equal(await ledgerSize(), before) const wh = (await ciWebhook({ request: { headers: headers('workflow_run', 'd-400'), json: { action: 'completed', workflow_run: { conclusion: 'failure', head_sha: 'abc', head_branch: 'main' }, repository } } })) as Record assert.equal((wh.created as string[]).length, 1) assert.deepEqual(toGithubJson(payload).workflow_run, { conclusion: 'failure', head_sha: 'abc', head_branch: 'main', name: undefined, html_url: undefined }) }) test('report flags missing events only after the grace period', () => { const now = Date.parse('2026-11-22T12:00:00Z') const old = { deliveryId: 'a', side: 'webhook' as const, decision: 'ingest:x', topic: 't', at: '2026-11-22T11:00:00Z', detail: '' } const fresh = { ...old, deliveryId: 'b', at: '2026-11-22T11:59:00Z' } const r = buildShadowReport([old, fresh], now) assert.equal(r.missingEvent.length, 1) assert.equal(r.missingEvent[0].deliveryId, 'a') const withError = buildShadowReport([{ ...old, detail: JSON.stringify({ bridge: { error: 'schema' } }) }], now) assert.equal(withError.bridgeErrors, 1) assert.equal(withError.bridgeErrorSample, 'schema') })