Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

post-merge.test.ts

110 lines · 6.0 KB · TypeScript
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { test } from 'node:test'

const STUB = `export const packageStorage = () => ({ async get() { return null }, async set() {} }); export async function credential() { throw new Error('no') }; export async function credentials() { return [] }`
registerHooks({
	resolve(spec, ctx, next) {
		if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
		return next(spec, ctx)
	},
})
const { advanceWatch, beginWatch } = await import('./post-merge.ts')
type Ledger = import('./work-item.ts').Ledger
type WorkItem = import('./work-item.ts').WorkItem

const SHA = 'a'.repeat(40)
const FIX = 'b'.repeat(40)
const S = { postMergeFixTimeoutMinutes: 60, postMergePendingTimeoutMinutes: 180 }
const T0 = Date.parse('2026-11-18T02:00:00Z')

function shippedItem(): WorkItem {
	const base = {
		id: 'w1', projectId: 'kody', title: 't', body: '', state: 'shipped', priority: 2, needsKent: false, rank: 2, source: 'github-issues', externalId: '1',
		fingerprint: 'f', signalIds: [], labels: [], repoRef: 'kody-hq/kody', planCardId: null, runId: 'sess1', createdAt: '', updatedAt: '', events: [], shadow: false,
		pr: { url: 'https://github.com/kody-hq/kody/pull/9', number: 9, reviewState: 'approved', ready: true, updatedAt: '', merged: { at: '', by: 'pipeline', attestedBy: 'github-api', mergeCommit: SHA } },
	} as WorkItem
	return beginWatch(base, SHA, new Date(T0).toISOString())
}

/** GitHub mock: merge commit checks, main head sha and its checks. */
function gh(opts: { merge: string; head?: string; headChecks?: string }) {
	return async (u: string) => {
		if (u.includes(`/commits/${SHA}/check-runs`)) return Response.json({ check_runs: [{ name: 'test', status: opts.merge === 'pending' ? 'in_progress' : 'completed', conclusion: opts.merge === 'pending' ? null : opts.merge }] })
		if (u.endsWith('/repos/kody-hq/kody')) return Response.json({ default_branch: 'main' })
		if (u.endsWith('/commits/main')) return Response.json({ sha: opts.head ?? SHA })
		if (u.includes(`/commits/${FIX}/check-runs`)) return Response.json({ check_runs: [{ name: 'test', status: 'completed', conclusion: opts.headChecks ?? 'success' }] })
		return new Response('nf', { status: 404 })
	}
}

const ledgerOf = (i: WorkItem): Ledger => ({ version: 1, items: { [i.id]: i } })

test('beginWatch needs a PR, repo, and a full merge sha', () => {
	const i = shippedItem()
	assert.equal(i.postMerge!.phase, 'watching')
	assert.equal(i.postMerge!.implementerRunId, 'sess1')
	assert.equal(beginWatch({ ...i, postMerge: undefined }, 'abc').postMerge, undefined)
})

test('green merge commit ends the watch with no messages', async () => {
	const l = ledgerOf(shippedItem())
	let sent = 0
	const o = await advanceWatch(l, 'w1', S, { github: gh({ merge: 'success' }), shadowMode: false, notify: async () => { sent++; return true }, now: () => T0 + 60_000 })
	assert.equal(o!.to, 'green')
	assert.equal(sent, 0)
})

test('red main: the implementer is asked first, then fixed when main is green again', async () => {
	const l = ledgerOf(shippedItem())
	const msgs: Array<[string, string]> = []
	const notify = async (r: string, m: string) => { msgs.push([r, m]); return true }
	const o1 = await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure' }), shadowMode: false, notify, now: () => T0 + 60_000 })
	assert.equal(o1!.to, 'implementer-notified')
	assert.equal(msgs.length, 1)
	assert.equal(msgs[0]![0], 'sess1')
	assert.match(msgs[0]![1], /Failing checks: test/)
	// still red inside the timeout: nothing happens
	assert.equal(await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure' }), shadowMode: false, notify, now: () => T0 + 30 * 60_000 }), null)
	const o2 = await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure', head: FIX, headChecks: 'success' }), shadowMode: false, notify, now: () => T0 + 40 * 60_000 })
	assert.equal(o2!.to, 'fixed')
	assert.equal(Object.keys(l.items).length, 1, 'no fallback item')
})

test('implementer timeout queues one P0 red-main fallback item', async () => {
	const l = ledgerOf(shippedItem())
	const notify = async () => true
	await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure' }), shadowMode: false, notify, now: () => T0 + 60_000 })
	const o = await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure' }), shadowMode: false, notify, now: () => T0 + 62 * 60_000 })
	assert.equal(o!.to, 'fallback-queued')
	const fb = Object.values(l.items).find((i) => i.id !== 'w1')!
	assert.equal(fb.state, 'planned')
	assert.equal(fb.priority, 0)
	assert.equal(fb.repoRef, 'kody-hq/kody')
	assert.equal(fb.fingerprint, `red-main:kody-hq/kody:${SHA}`)
	assert.equal(l.items.w1!.postMerge!.fallbackItemId, fb.id)
	assert.equal(await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure' }), shadowMode: false, notify, now: () => T0 + 90 * 60_000 }), null, 'watch is done')
})

test('unreachable implementer goes straight to the fallback', async () => {
	const l = ledgerOf(shippedItem())
	const o = await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure' }), shadowMode: false, notify: async () => false, now: () => T0 + 60_000 })
	assert.equal(o!.to, 'fallback-queued')
	assert.equal(Object.keys(l.items).length, 2)
})

test('shadow mode observes red but sends nothing and queues nothing', async () => {
	const l = ledgerOf(shippedItem())
	let sent = 0
	const o = await advanceWatch(l, 'w1', S, { github: gh({ merge: 'failure' }), shadowMode: true, notify: async () => { sent++; return true }, now: () => T0 + 60_000 })
	assert.equal(o!.to, 'gave-up')
	assert.equal(sent, 0)
	assert.equal(Object.keys(l.items).length, 1)
})

test('pending checks wait, then give up after the pending timeout', async () => {
	const l = ledgerOf(shippedItem())
	const deps = { github: gh({ merge: 'pending' }), shadowMode: false, notify: async () => true }
	assert.equal(await advanceWatch(l, 'w1', S, { ...deps, now: () => T0 + 60_000 }), null)
	assert.equal((await advanceWatch(l, 'w1', S, { ...deps, now: () => T0 + 181 * 60_000 }))!.to, 'gave-up')
})