← 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.
Files
/**
* GitHub permission profiles and a non-hanging, read-only preflight for one
* repo. Write permissions cannot be proven without writing, so they are
* reported as "configure in the GitHub App" and never probed.
*/
import { githubPackageFetch, githubReadonlyRequest, REPO_REF_RE, SETUP_HEADER, type GithubFetch } from './github-readonly.ts'
export type GithubAccess = 'read' | 'write'
/** Preview: backfill, overlap check, PR status refresh. No writes. */
export const PREVIEW_PERMISSIONS: Record<string, GithubAccess> = { metadata: 'read', issues: 'read', pull_requests: 'read', checks: 'read', actions: 'read' }
/** Shipping: an agent pushes a branch and opens/updates its PR. Never merges via the factory. */
export const SHIP_PERMISSIONS: Record<string, GithubAccess> = { metadata: 'read', contents: 'write', pull_requests: 'write', issues: 'read', checks: 'read', actions: 'read' }
/** Never requested: hook registration is a separate owner approval; workflow edits stay off by default. */
export const NOT_REQUESTED = ['administration', 'repository_hooks (admin:repo_hook)', 'workflows', 'secrets', 'environments']
export const CREDENTIAL_TIMEOUT_MS = 5000
/**
* The GitHub client (through @kody/github), or null when GitHub is not set up
* for this package or does not answer within `timeoutMs`. Never throws.
*/
export async function optionalGithubFetch(timeoutMs = CREDENTIAL_TIMEOUT_MS): Promise<GithubFetch | null> {
const gh = githubPackageFetch()
let timer: ReturnType<typeof setTimeout> | undefined
try {
const res = await Promise.race([
gh('https://api.github.com/rate_limit', { method: 'GET' }),
new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), timeoutMs) }),
])
return res && !res.headers.get(SETUP_HEADER) ? gh : null
} catch {
return null
} finally {
if (timer) clearTimeout(timer)
}
}
export type ProbeResult = { permission: string; access: 'read'; ok: boolean; status?: number; note?: string }
export type GithubPreflight = {
repoRef: string
credential: 'mapped' | 'missing'
probes: ProbeResult[]
preview: { ready: boolean; missing: string[] }
ship: { ready: false; verifiedReads: boolean; unverifiedWrites: string[]; note: string }
}
/** Read-only probes (one GET each). Missing credential returns immediately with no request. */
export async function githubPreflight(fetchFn: GithubFetch | null, repoRef: string): Promise<GithubPreflight> {
if (!REPO_REF_RE.test(repoRef)) throw new Error(`invalid repoRef ${repoRef}`)
const writes = Object.entries(SHIP_PERMISSIONS).filter(([, a]) => a === 'write').map(([p]) => `${p}:write`)
const shipNote = 'Write access cannot be verified without writing; set it in the GitHub App and confirm on the first supervised run.'
if (!fetchFn) {
return { repoRef, credential: 'missing', probes: [], preview: { ready: false, missing: Object.keys(PREVIEW_PERMISSIONS).map((p) => `${p}:read`) }, ship: { ready: false, verifiedReads: false, unverifiedWrites: writes, note: shipNote } }
}
const [o, r] = repoRef.split('/').map(encodeURIComponent)
const probes: Array<[string, string]> = [
['metadata', `/repos/${o}/${r}`],
['issues', `/repos/${o}/${r}/issues?state=open&per_page=1`],
['pull_requests', `/repos/${o}/${r}/pulls?state=open&per_page=1`],
['contents', `/repos/${o}/${r}/commits?per_page=1`],
['checks', `/repos/${o}/${r}/commits/HEAD/check-runs?per_page=1`],
['actions', `/repos/${o}/${r}/actions/runs?per_page=1`],
]
const results: ProbeResult[] = []
for (const [permission, path] of probes) {
try {
await githubReadonlyRequest(fetchFn, path)
results.push({ permission, access: 'read', ok: true })
} catch (err) {
const m = /(\d{3})/.exec(err instanceof Error ? err.message : '')
results.push({ permission, access: 'read', ok: false, status: m ? Number(m[1]) : undefined, note: 'not granted or repo not in the installation' })
}
}
const okSet = new Set(results.filter((x) => x.ok).map((x) => x.permission))
const missing = Object.keys(PREVIEW_PERMISSIONS).filter((p) => !okSet.has(p)).map((p) => `${p}:read`)
const shipReads = Object.keys(SHIP_PERMISSIONS).every((p) => okSet.has(p))
return { repoRef, credential: 'mapped', probes: results, preview: { ready: missing.length === 0, missing }, ship: { ready: false, verifiedReads: shipReads, unverifiedWrites: writes, note: shipNote } }
}