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

collect-core.test.ts

91 lines · 5.5 KB · TypeScript
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { CallBudget, BudgetExhausted, collectDataset, dayRanges, inspectWorkflowFile, isPipelineRun, spread, toRun } from './collect-core.ts'

function fakeGithub(options: { runsPerWorkflow: number; failEvery?: number }) {
	const calls: string[] = []
	const runs = Array.from({ length: options.runsPerWorkflow }, (_, index) => ({
		id: index + 1,
		workflow_id: 7,
		event: index % 3 === 0 ? 'push' : 'pull_request',
		head_branch: index % 3 === 0 ? 'main' : `b${index}`,
		head_sha: `s${index}`,
		status: 'completed',
		conclusion: options.failEvery && index % options.failEvery === 0 ? 'failure' : 'success',
		run_attempt: 1,
		created_at: new Date(Date.parse('2026-11-01T00:00:00Z') + index * 60000).toISOString(),
		run_started_at: new Date(Date.parse('2026-11-01T00:00:00Z') + index * 60000).toISOString(),
		updated_at: new Date(Date.parse('2026-11-01T00:10:00Z') + index * 60000).toISOString(),
		pull_requests: index % 3 === 0 ? [] : [{ number: index }],
	}))
	const request = async ({ path }: { path: string }) => {
		calls.push(path)
		if (path === '/repos/acme/widgets') return { ok: true, status: 200, data: { default_branch: 'main' } }
		if (path.startsWith('/repos/acme/widgets/actions/workflows?')) {
			return { ok: true, status: 200, data: { workflows: [{ id: 7, name: 'CI', path: '.github/workflows/ci.yml', state: 'active' }, { id: 8, name: 'Copilot', path: 'dynamic/x', state: 'active' }] } }
		}
		if (path.startsWith('/repos/acme/widgets/actions/workflows/7/runs')) {
			const page = Number(/[?&]page=(\d+)/.exec(path)?.[1] ?? 1)
			return { ok: true, status: 200, data: { total_count: runs.length, workflow_runs: runs.slice((page - 1) * 100, page * 100) } }
		}
		if (path.includes('/contents/')) return { ok: true, status: 200, data: { content: btoa('on:\n  pull_request:\n    branches: [main]\nconcurrency:\n  cancel-in-progress: true\n') } }
		if (/\/actions\/runs\/\d+\/jobs/.test(path) || /attempts\/\d+\/jobs/.test(path)) return { ok: true, status: 200, data: { jobs: [{ id: 1, name: 'test', conclusion: 'success', status: 'completed', created_at: '2026-11-01T00:00:00Z', started_at: '2026-11-01T00:00:10Z', completed_at: '2026-11-01T00:05:00Z', labels: ['ubuntu-latest'], steps: [] }] } }
		if (path.endsWith('/timing')) return { ok: true, status: 200, data: { billable: { UBUNTU: { total_ms: 0 } } } }
		if (path.includes('/actions/caches')) return { ok: true, status: 200, data: { actions_caches: [] } }
		if (path.includes('/files')) return { ok: true, status: 200, data: [{ filename: 'README.md' }] }
		return { ok: false, status: 404, text: 'not found' }
	}
	return { request, calls }
}

test('collector paginates, keeps pipeline runs, and stays under the call cap', async () => {
	const fake = fakeGithub({ runsPerWorkflow: 250, failEvery: 25 })
	const data = await collectDataset({ repo: 'acme/widgets', request: fake.request as any, now: new Date('2026-11-04T00:00:00Z'), maxApiCalls: 80 })
	assert.equal(data.workflows.length, 1, 'dynamic workflows are skipped')
	assert.equal(data.workflows[0].runs.length, 250)
	assert.ok(data.apiCalls <= 80)
	assert.equal(fake.calls.length, data.apiCalls)
	assert.ok(Object.keys(data.jobsByRun).length > 0)
	assert.deepEqual(data.workflows[0].file, { hasPullRequestPaths: false, hasConcurrency: true, cancelInProgress: true })
	assert.ok(Object.keys(data.prFiles).length > 0)
})

test('collector with a tiny budget still returns what it has', async () => {
	const fake = fakeGithub({ runsPerWorkflow: 50 })
	const data = await collectDataset({ repo: 'acme/widgets', request: fake.request as any, now: new Date('2026-11-04T00:00:00Z'), maxApiCalls: 4 })
	assert.equal(data.apiCalls, 4)
	assert.ok(data.notes.includes('api budget reached'))
})

test('budget refuses past the cap', () => {
	const budget = new CallBudget(1)
	budget.take()
	assert.throws(() => budget.take(), BudgetExhausted)
})

test('pipeline filter keeps PR and default-branch runs only', () => {
	assert.equal(isPipelineRun(toRun({ event: 'pull_request', head_branch: 'x' }, 'w'), 'main'), true)
	assert.equal(isPipelineRun(toRun({ event: 'push', head_branch: 'main' }, 'w'), 'main'), true)
	assert.equal(isPipelineRun(toRun({ event: 'push', head_branch: 'feature' }, 'w'), 'main'), false)
	assert.equal(isPipelineRun(toRun({ event: 'issue_comment', head_branch: 'main' }, 'w'), 'main'), false)
	assert.equal(isPipelineRun(toRun({ event: 'workflow_run', head_branch: 'main' }, 'w'), 'main'), true)
})

test('workflow file checks', () => {
	const text = 'name: x\non:\n  pull_request:\n    paths-ignore:\n      - docs/**\n  push:\n    branches: [main]\njobs:\n  a:\n    runs-on: ubuntu-latest\n'
	assert.deepEqual(inspectWorkflowFile(text), { hasPullRequestPaths: true, hasConcurrency: false, cancelInProgress: false })
})

test('dayRanges and spread', () => {
	assert.equal(dayRanges(new Date('2026-11-01T00:00:00Z'), new Date('2026-11-04T00:00:00Z')).length, 3)
	assert.deepEqual(spread([1, 2, 3, 4, 5, 6], 3), [1, 3, 5])
	assert.deepEqual(spread([1, 2], 5), [1, 2])
})

test('failures and reruns never crowd out first-attempt successes', async () => {
	const fake = fakeGithub({ runsPerWorkflow: 120, failEvery: 2 })
	const data = await collectDataset({ repo: 'acme/widgets', request: fake.request as any, now: new Date('2026-11-04T00:00:00Z'), maxApiCalls: 450 })
	const sampled = data.workflows[0].runs.filter((run) => data.jobsByRun[String(run.id)])
	assert.ok(sampled.filter((run) => run.conclusion === 'success').length >= 15)
	assert.ok(sampled.filter((run) => run.conclusion === 'failure').length >= 15)
})