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 delete(k) { store.delete(k) }, async sql() { return [] }, }); export const packageContext = { appBasePath: '/apps/factory/', hostedUrl: 'https://kody-factory--kody.kody.run/', kodyId: 'kody-factory' }; export async function credential(key) { throw new Error('credential not mapped: ' + key); } export async function credentials() { return [] } export const kody = { async metaGetCurrentUser() { const v = globalThis.__visitor; if (!v) throw new Error('Authenticated MCP user is required'); return v } }; export const workflows = null; ` registerHooks({ resolve(spec, ctx, next) { if (spec.startsWith('kody:@kody/')) 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 { parseCardRefs } = await import('./refs.ts') const { planPrRefs, applyPrRefs, normalizeMergedPr } = await import('./pr-refs.ts') const { scanMergedPrs, PR_REFS_KEY } = await import('./pr-scan.ts') const { handleMergedPrEvent, setPrMergedDepsForTests } = await import('./pr-merged-event.ts') const { handleGithubEvent, GITHUB_EVENT_TOPICS } = await import('../github-events/handle.ts') const { saveJson, loadJson, storageKeys } = await import('../lib/storage.ts') const { patchSettings } = await import('../lib/settings.ts') const { appBaseUrl, cardLink } = await import('../lib/links.ts') const { cardUrl } = await import('./report.ts') const { agentHandoff } = await import('../core/orchestrator.ts') const { default: entry } = await import('../app/entry.ts') type Item = { id: string; state: string; needsKent: boolean; links?: Array<{ kind: string; url: string }>; pr?: { url: string; merged?: { mergeCommit?: string } }; postMerge?: { phase: string }; events: Array<{ reason: string; to: string }> } type Ledger = { version: 1; items: Record } const g = globalThis as { __factoryStore?: Map; __visitor?: unknown } const reset = () => { g.__factoryStore?.clear(); g.__visitor = undefined } setPrMergedDepsForTests({ sleep: async () => {} }) const ID_A = 'wi_aaaaaaaaaaaaaaaa' const ID_B = 'wi_bbbbbbbbbbbbbbbb' const ID_C = 'wi_cccccccccccccccc' const SHA = 'a'.repeat(40) function card(id: string, extra: Record = {}) { const at = '2026-11-22T00:00:00.000Z' return { id, projectId: 'kody', title: `Card ${id}`, 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])) }) } const ledger = () => loadJson(storageKeys.LEDGER_KEY, { version: 1, items: {} }) const BODY = `## What changed Shorter retry loop. ## Referenced issues/PRs Closes https://factory.kody.build/c/${ID_A} Related: https://kody-factory--kody.kody.run/cards/${ID_B} ` test('parser: closing keywords, bare refs, short form, and ignored comments and code', () => { const refs = parseCardRefs(`${BODY} fixes: factory:${ID_C} \`Closes https://factory.kody.build/c/wi_dddddddddddddddd\` \`\`\` Resolves https://factory.kody.build/c/wi_eeeeeeeeeeeeeeee \`\`\` Fixed https://kody-factory--kody.kody.run/apps/x/work?card=wi_ffffffffffffffff closing https://factory.kody.build/c/wi_1111111111111111 Closes https://factory.kody.build/c/`) const by = Object.fromEntries(refs.map((r) => [r.cardId, r])) assert.equal(by[ID_A]!.closes, true) assert.equal(by[ID_A]!.keyword, 'closes') assert.equal(by[ID_B]!.closes, false) assert.equal(by[ID_C]!.closes, true, 'short form with "fixes:"') assert.equal(by.wi_ffffffffffffffff!.closes, true, 'work?card= form') assert.equal(by.wi_1111111111111111!.closes, false, '"closing" is not a keyword') assert.equal(by.wi_dddddddddddddddd, undefined, 'inline code ignored') assert.equal(by.wi_eeeeeeeeeeeeeeee, undefined, 'fenced code ignored') for (const k of ['close', 'closes', 'closed', 'fix', 'fixes', 'fixed', 'resolve', 'resolves', 'resolved']) { assert.equal(parseCardRefs(`${k.toUpperCase()} https://factory.kody.build/c/${ID_A}`)[0]!.closes, true, k) } assert.deepEqual(parseCardRefs(null), []) assert.equal(parseCardRefs(`see https://factory.kody.build/c/${ID_A} and later closes https://factory.kody.build/c/${ID_A}`)[0]!.closes, true, 'keyword anywhere wins') }) test('merged PR: closing ref ships the card with a PR link and note; bare ref links; replay is a no-op', () => { const l: Ledger = { version: 1, items: { [ID_A]: card(ID_A) as never, [ID_B]: card(ID_B, { state: 'needs-kent', needsKent: true }) as never, [ID_C]: card(ID_C, { state: 'shipped' }) as never } } const pr = normalizeMergedPr({ url: 'https://github.com/kody-hq/kody/pull/42', body: `${BODY}\nFixes https://factory.kody.build/c/${ID_C}\nCloses https://factory.kody.build/c/wi_9999999999999999`, mergeCommit: SHA })! const plan = planPrRefs(l as never, pr) const by = Object.fromEntries(plan.map((d) => [d.cardId, d.action])) assert.deepEqual(by, { [ID_A]: 'ship', [ID_B]: 'link', [ID_C]: 'link', wi_9999999999999999: 'skip' }) const changed = applyPrRefs(l as never, pr, plan, 'sweep') assert.equal(changed.length, 3) const a = l.items[ID_A]! assert.equal(a.state, 'shipped') assert.equal(a.pr?.url, pr.url, 'own repo, no PR yet: merge recorded on the card') assert.equal(a.pr?.merged?.mergeCommit, SHA) assert.equal(a.postMerge?.phase, 'watching') assert.match(a.events.at(-1)!.reason, /closed by merged PR #42 .*"closes"/) assert.ok(a.links!.some((x) => x.kind === 'pr' && x.url === pr.url)) const b = l.items[ID_B]! assert.equal(b.state, 'needs-kent', 'bare ref never moves a card') assert.match(b.events.at(-1)!.reason, /mentioned in merged PR #42/) assert.equal(l.items[ID_C]!.state, 'shipped') // Replay: nothing left to do. const again = planPrRefs(l as never, pr) assert.ok(again.every((d) => d.action === 'skip')) assert.equal(applyPrRefs(l as never, pr, again, 'sweep').length, 0) }) test('merged PR from another repo ships the card but leaves its own PR alone', () => { const own = { url: 'https://github.com/kody-hq/kody/pull/7', number: 7, reviewState: 'pending', ready: false, updatedAt: 'x' } const l: Ledger = { version: 1, items: { [ID_A]: card(ID_A, { state: 'verifying', pr: own }) as never } } const pr = normalizeMergedPr({ url: 'https://github.com/kody-hq/other/pull/3', body: `Resolves factory:${ID_A}`, mergeCommit: SHA })! applyPrRefs(l as never, pr, planPrRefs(l as never, pr), 'system') assert.equal(l.items[ID_A]!.state, 'shipped') assert.equal(l.items[ID_A]!.pr?.url, own.url) assert.equal(l.items[ID_A]!.postMerge, undefined) }) test('sweep scan: first tick sets the cursor, later merges apply once', async () => { reset() await seed(card(ID_A)) let prs: unknown[] = [] let calls = 0 const github = async (url: string) => { calls++; assert.match(url, /\/repos\/kody-hq\/kody\/pulls\?state=closed/); return new Response(JSON.stringify(prs), { status: 200 }) } const first = await scanMergedPrs((await ledger()) as never, ['kody-hq/kody'], github, { now: () => Date.parse('2026-11-23T00:00:00Z') }) await first.persist() assert.equal(calls, 0, 'first tick only sets the cursor') prs = [ { html_url: 'https://github.com/kody-hq/kody/pull/42', number: 42, body: `Closes https://factory.kody.build/c/${ID_A}`, merged_at: '2026-11-23T01:00:00Z', merge_commit_sha: SHA }, { html_url: 'https://github.com/kody-hq/kody/pull/41', number: 41, body: `Closes https://factory.kody.build/c/${ID_A}`, merged_at: '2026-11-22T01:00:00Z', merge_commit_sha: SHA }, { html_url: 'https://github.com/kody-hq/kody/pull/40', number: 40, body: `Closes https://factory.kody.build/c/${ID_A}`, merged_at: null }, ] const l = await ledger() const second = await scanMergedPrs(l as never, ['kody-hq/kody'], github) assert.equal(second.merged, 1, 'only PRs merged after the cursor') assert.deepEqual(second.changed, [ID_A]) assert.equal(l.items[ID_A]!.state, 'shipped') await saveJson(storageKeys.LEDGER_KEY, l) await second.persist() const third = await scanMergedPrs((await ledger()) as never, ['kody-hq/kody'], github) assert.equal(third.merged, 0, 'seen PRs are not replayed') const state = await loadJson<{ repos: Record }>(PR_REFS_KEY, { repos: {} }) assert.deepEqual(state.repos['kody-hq/kody']!.seen, ['https://github.com/kody-hq/kody/pull/42']) const dry = await scanMergedPrs((await ledger()) as never, ['kody-hq/new'], github, { dryRun: true }) await dry.persist() assert.equal((await loadJson<{ repos: Record }>(PR_REFS_KEY, { repos: {} })).repos['kody-hq/new'], undefined, 'dry run writes nothing') }) test('@kody/github.pr.merged: shadow plans only, live applies, replay is a no-op', async () => { reset() await seed(card(ID_A), card(ID_B, { state: 'intake' })) const envelope = { source: { kody_id: 'github' }, idempotency_key: 'd1', payload: { deliveryId: 'd1', action: 'closed', repo: { fullName: 'kody-hq/kody', owner: 'kody-hq', name: 'kody' }, pr: { number: 42, merged: true, htmlUrl: 'https://github.com/kody-hq/kody/pull/42', body: BODY, mergeCommitSha: SHA } } } const shadow = await handleGithubEvent(GITHUB_EVENT_TOPICS.prMerged, envelope) as { mode: string; decision: string } assert.equal(shadow.mode, 'shadow') assert.equal(shadow.decision, 'pr-refs:ship=1,link=1,skip=0') assert.equal((await ledger()).items[ID_A]!.state, 'running', 'shadow writes nothing') await patchSettings({ githubEventsMode: 'live' }) const live = await handleGithubEvent(GITHUB_EVENT_TOPICS.prMerged, envelope) as { changed: string[] } assert.deepEqual(live.changed.sort(), [ID_A, ID_B]) assert.equal((await ledger()).items[ID_A]!.state, 'shipped') assert.equal((await ledger()).items[ID_B]!.state, 'intake') const replay = await handleGithubEvent(GITHUB_EVENT_TOPICS.prMerged, envelope) as { changed: string[] } assert.deepEqual(replay.changed, []) const notMerged = await handleMergedPrEvent({ pr: { merged: false, htmlUrl: 'https://github.com/kody-hq/kody/pull/43' } }, false) assert.equal(notMerged.decision, 'not-merged') const wrongSource = await handleGithubEvent(GITHUB_EVENT_TOPICS.prMerged, { ...envelope, source: { kody_id: 'evil' } }) as { skipped?: boolean } assert.equal(wrongSource.skipped, true) }) test('links: short /c/ form, publicBaseUrl switches every link, /c/ and /cards/ both open the card', async () => { reset() assert.equal(await appBaseUrl(), 'https://kody-factory--kody.kody.run') assert.equal(cardUrl(ID_A), `https://kody-factory--kody.kody.run/c/${ID_A}`) assert.match(agentHandoff(ID_A), new RegExp(`Closes https://kody-factory--kody\\.kody\\.run/c/${ID_A}`)) await patchSettings({ publicBaseUrl: 'https://factory.kody.build/' }) assert.equal(await appBaseUrl(), 'https://factory.kody.build') assert.equal(cardLink(await appBaseUrl(), ID_A), `https://factory.kody.build/c/${ID_A}`) assert.match(agentHandoff(ID_A, await appBaseUrl()), new RegExp(`Closes https://factory\\.kody\\.build/c/${ID_A}`)) await patchSettings({ publicBaseUrl: 'http://insecure.example' }) assert.equal(await appBaseUrl(), 'https://kody-factory--kody.kody.run', 'non-https base is ignored') for (const p of ['c', 'cards']) { const res = await entry.fetch(new Request(`https://kody-factory--kody.kody.run/apps/factory/${p}/${ID_A}`)) assert.equal(res.status, 302) assert.match(res.headers.get('location') ?? '', new RegExp(`/work\\?card=${ID_A}$`)) } }) test('appAccess members: anonymous goes to Sign in with Kody, non-members are refused, members get in', async () => { reset() await seed(card(ID_A)) const get = (path: string, headers: Record = {}) => entry.fetch(new Request(`https://factory.kody.build${path}`, { headers })) // platform (default): the app trusts Kody's own gate. assert.equal((await get(`/api/cards/${ID_A}`)).status, 200) await patchSettings({ appAccess: 'members' }) const anon = await get(`/c/${ID_A}`) assert.equal(anon.status, 302) assert.equal(anon.headers.get('location'), `/-/auth/login?app=kody-factory&return_to=${encodeURIComponent(`/c/${ID_A}`)}`) assert.equal((await get(`/api/cards/${ID_A}`)).status, 401) assert.equal((await get('/health')).status, 200, 'uptime check stays open') const outsider = { 'x-kody-visitor': JSON.stringify({ userId: 'u2', username: 'someone', role: null }) } assert.equal((await get('/work', outsider)).status, 403) assert.equal((await get(`/api/cards/${ID_A}`, outsider)).status, 403) const member = { 'x-kody-visitor': JSON.stringify({ userId: 'u1', username: 'kentcdodds', role: 'owner' }) } assert.equal((await get(`/api/cards/${ID_A}`, member)).status, 200) g.__visitor = { user_id: 'u1', username: 'kentcdodds', role: 'owner' } assert.equal((await get(`/api/cards/${ID_A}`)).status, 200, 'falls back to metaGetCurrentUser') })