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

github-permissions.test.ts

90 lines · 5.3 KB · TypeScript
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/' };
export async function credential() { if (globalThis.__hang) return new Promise(() => {}); throw new Error('credential not mapped') }
export async function credentials() { return [] }
`
registerHooks({ resolve(s, c, n) { return s === 'kody:runtime' ? { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true } : n(s, c) } })
const g = globalThis as unknown as { __hang?: boolean }
const { githubPreflight, optionalGithubFetch, SHIP_PERMISSIONS, PREVIEW_PERMISSIONS, NOT_REQUESTED } = await import('./github-permissions.ts')
const { default: refreshPr, summarizeReviews, summarizeChecks } = await import('../exports/refresh-pr.ts')
const { default: create } = await import('../exports/create.ts')
const { default: linkPr } = await import('../exports/link-pr.ts')
const { upsertProject } = await import('../projects/config.ts')
const { loadJson, storageKeys } = await import('./storage.ts')
const { emptyLedger } = await import('../core/work-item.ts')

await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'k', repoRef: 'kody-hq/kody', host: 'github', enabled: true }] })

test('profiles: preview is read-only; ship adds contents + pull_requests write; no hooks/admin/workflows', () => {
	assert.ok(Object.values(PREVIEW_PERMISSIONS).every((a) => a === 'read'))
	assert.equal(SHIP_PERMISSIONS.contents, 'write')
	assert.equal(SHIP_PERMISSIONS.pull_requests, 'write')
	assert.equal(SHIP_PERMISSIONS.checks, 'read')
	for (const k of ['administration', 'workflows', 'repository_hooks']) assert.ok(!(k in SHIP_PERMISSIONS))
	assert.ok(NOT_REQUESTED.some((x) => /hooks/.test(x)))
})

test('unmapped or hanging credential returns null fast, no throw', async () => {
	assert.equal(await optionalGithubFetch(50), null)
	g.__hang = true
	const t = Date.now()
	assert.equal(await optionalGithubFetch(50), null)
	assert.ok(Date.now() - t < 1000)
	g.__hang = false
	const r = await githubPreflight(null, 'kody-hq/kody')
	assert.equal(r.credential, 'missing')
	assert.equal(r.probes.length, 0)
	assert.equal(r.preview.ready, false)
	assert.equal(r.ship.ready, false)
})

test('preflight probes reads only (GET api.github.com) and reports missing permissions', async () => {
	const seen: Array<[string, string]> = []
	const fetchFn = async (u: string, init?: RequestInit) => {
		seen.push([init?.method ?? 'GET', u])
		return u.includes('/actions/') ? new Response('{}', { status: 403 }) : Response.json(u.endsWith('/kody') ? {} : [])
	}
	const r = await githubPreflight(fetchFn, 'kody-hq/kody')
	assert.ok(seen.every(([m, u]) => m === 'GET' && new URL(u).host === 'api.github.com'))
	assert.deepEqual(r.preview.missing, ['actions:read'])
	assert.equal(r.ship.ready, false, 'ship never claims ready: writes are unverifiable read-only')
	assert.deepEqual(r.ship.unverifiedWrites.sort(), ['contents:write', 'pull_requests:write'])
})

test('review and check summaries', () => {
	assert.equal(summarizeReviews([{ state: 'APPROVED', user: { login: 'a' } }, { state: 'CHANGES_REQUESTED', user: { login: 'b' } }]), 'changes_requested')
	assert.equal(summarizeReviews([{ state: 'CHANGES_REQUESTED', user: { login: 'a' } }, { state: 'APPROVED', user: { login: 'a' } }]), 'approved')
	assert.equal(summarizeChecks({ check_runs: [{ status: 'completed', conclusion: 'success' }, { status: 'in_progress', conclusion: null }] }), 'pending')
	assert.equal(summarizeChecks({ check_runs: [{ status: 'completed', conclusion: 'failure' }] }), 'failure')
})

test('refresh-pr: dry run by default, ready only when approved + green, merge needs attestMerged', async () => {
	const { item } = await create({ projectId: 'kody', title: 'refresh me' })
	assert.equal((await refreshPr({ workItemId: item.id }, { fetch: null })).ok, false)
	await linkPr({ workItemId: item.id, prUrl: 'https://github.com/kody-hq/kody/pull/7' })
	const sha = 'a'.repeat(40)
	let merged = false
	const fetchFn = async (u: string) => {
		if (u.endsWith('/pulls/7')) return Response.json({ state: merged ? 'closed' : 'open', merged, merge_commit_sha: merged ? 'b'.repeat(40) : null, head: { sha } })
		if (u.includes('/reviews')) return Response.json([{ state: 'APPROVED', user: { login: 'kent' } }])
		return Response.json({ check_runs: [{ status: 'completed', conclusion: 'success' }] })
	}
	const dry = await refreshPr({ workItemId: item.id }, { fetch: fetchFn })
	assert.equal(dry.dryRun, true)
	assert.equal(dry.pr!.ready, true)
	const stored = (await loadJson(storageKeys.LEDGER_KEY, emptyLedger())).items[item.id]!
	assert.equal(stored.pr!.ready, false, 'dry run did not write')
	merged = true
	const seen = await refreshPr({ workItemId: item.id, dryRun: false }, { fetch: fetchFn })
	assert.equal(seen.wouldShip, false, 'observed merge is not an attestation by itself')
	assert.equal(seen.pr!.github!.merged, true)
	const att = await refreshPr({ workItemId: item.id, dryRun: false, attestMerged: true }, { fetch: fetchFn })
	assert.equal(att.wouldShip, true)
	assert.equal(att.pr!.merged!.attestedBy, 'github-api')
})