← 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
/**
* Build eval fixtures from real factory data: GitHub issues, ledger work
* items with outcomes, Sentry issue cards (filed from @kody/sentry-events
* events), and friction records. Stores only non-private fields (no stack
* traces or user data). Labels expected outcomes from what actually happened.
*
* This runs inside the kody org with the factory's credentials.
*/
import { loadJson, storageKeys } from '../../lib/storage.ts'
import { emptyLedger, type Ledger, type WorkItem } from '../../core/work-item.ts'
import { githubCredentialFetch, githubReadonlyRequest, GithubSetupError } from '../../lib/github-readonly.ts'
import { issueNumberOf } from '../../core/overlap.ts'
import { outcomeLabel } from './labels.ts'
export type RealFixture = {
id: string
title: string
body: string
source: string
labels: string[]
severity: string
projectId: string
expectedLabel: 'create_work_item' | 'wake_grok' | 'ignore'
origin: string
}
/** GitHub `state_reason` for a dropped item's source issue, or null when unknown. */
async function sourceStateReason(
fetchFn: ((url: string, init?: RequestInit) => Promise<Response>) | null,
item: WorkItem,
): Promise<string | null> {
// Prefer the item's fields; fall back to the `github-issue:<owner/repo>:<n>` fingerprint.
const fp = /^github-issue:([\w.-]+\/[\w.-]+):(\d+)$/.exec(item.fingerprint ?? '')
const n = issueNumberOf(item) ?? (fp ? Number(fp[2]) : null)
const repo = item.repoRef ?? fp?.[1] ?? null
if (!fetchFn || n == null || !repo) return null
try {
const issue = await githubReadonlyRequest<{ state_reason?: string | null }>(fetchFn, `/repos/${repo}/issues/${n}`)
return issue?.state_reason ?? null
} catch {
return null
}
}
function severityFromItem(item: WorkItem): string {
if (item.priority === 0) return 'critical'
if (item.priority === 1) return 'high'
if (item.priority === 2) return 'medium'
return 'low'
}
export async function fixturesFromLedger(): Promise<RealFixture[]> {
const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
const items = Object.values(ledger.items)
const terminal = items.filter((i) => ['shipped', 'dropped', 'needs-kent'].includes(i.state))
let fetchFn: ((url: string, init?: RequestInit) => Promise<Response>) | null = null
if (terminal.some((i) => i.state === 'dropped')) {
try {
fetchFn = await githubCredentialFetch()
} catch {
fetchFn = null
}
}
const fixtures: RealFixture[] = []
for (const item of terminal.slice(0, 25)) {
const reason = item.state === 'dropped' ? await sourceStateReason(fetchFn, item) : null
fixtures.push({
id: `ledger:${item.id}`,
title: item.title.slice(0, 200),
body: item.body.slice(0, 500),
source: item.source,
labels: item.labels.slice(0, 10),
severity: severityFromItem(item),
projectId: item.projectId,
expectedLabel: outcomeLabel(item, reason),
origin: `ledger item ${item.id}, state=${item.state}${reason ? `, source=${reason}` : ''}`,
})
}
return fixtures
}
type GithubIssue = {
number?: number
title?: string
body?: string | null
html_url?: string
state?: string
state_reason?: string | null
labels?: Array<string | { name?: string }>
pull_request?: unknown
}
function labelFromGithubIssue(issue: GithubIssue): 'create_work_item' | 'ignore' {
if (issue.state === 'closed') {
const reason = issue.state_reason ?? ''
if (reason === 'not_planned' || reason === 'duplicate') return 'ignore'
return 'create_work_item'
}
return 'create_work_item'
}
function labelsFromGithub(raw: GithubIssue['labels']): string[] {
if (!Array.isArray(raw)) return []
return raw.map((l) => typeof l === 'string' ? l : String((l as { name?: string }).name ?? '')).filter(Boolean)
}
export async function fixturesFromGithub(repo = 'kody-hq/kody', limit = 30): Promise<RealFixture[]> {
let fetchFn: (url: string, init?: RequestInit) => Promise<Response>
try {
fetchFn = await githubCredentialFetch()
} catch (err) {
if (err instanceof GithubSetupError) return []
throw err
}
const fixtures: RealFixture[] = []
const states = ['closed', 'open']
for (const state of states) {
if (fixtures.length >= limit) break
const remaining = limit - fixtures.length
try {
const issues = await githubReadonlyRequest<GithubIssue[]>(
fetchFn,
`/repos/${repo}/issues?state=${state}&per_page=${Math.min(remaining, 30)}&sort=updated&direction=desc`,
)
for (const issue of issues) {
if (issue.pull_request) continue
const labels = labelsFromGithub(issue.labels)
fixtures.push({
id: `github:${repo}:${issue.number}`,
title: String(issue.title ?? '').slice(0, 200),
body: String(issue.body ?? '').slice(0, 500),
source: 'github-issues',
labels,
severity: labels.some((l) => /^P0$/i.test(l)) ? 'critical' : labels.some((l) => /^P1$/i.test(l)) ? 'high' : 'medium',
projectId: 'kody',
expectedLabel: labelFromGithubIssue(issue),
origin: `github ${repo}#${issue.number}, state=${issue.state}, reason=${issue.state_reason ?? 'none'}`,
})
}
} catch {
break
}
}
return fixtures
}
/**
* Sentry fixtures from the cards Sentry events filed (label `source:sentry`).
* A dropped card was not worth filing; any other state was.
*/
export async function fixturesFromSentry(opts: { limit?: number } = {}): Promise<RealFixture[]> {
const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
const limit = opts.limit ?? 15
const fixtures: RealFixture[] = []
for (const item of Object.values(ledger.items)) {
if (fixtures.length >= limit) break
if (!item.labels?.includes('source:sentry') || !item.title) continue
const level = item.labels.find((l) => l.startsWith('sentry-level:'))?.slice('sentry-level:'.length) ?? 'error'
fixtures.push({
id: `sentry:${item.id}`,
title: item.title.replace(/^Sentry: /, '').slice(0, 200),
body: String(item.body ?? '').split('\n').filter((l) => /^(Level|Culprit|Events so far|Alert rule):/.test(l)).join('. ').slice(0, 500),
source: 'sentry',
labels: ['sentry', level],
severity: level === 'fatal' || level === 'error' ? 'critical' : level === 'warning' ? 'high' : level === 'info' ? 'medium' : 'low',
projectId: item.projectId,
expectedLabel: item.state === 'dropped' ? 'ignore' : 'create_work_item',
origin: `sentry card ${item.id}, state=${item.state}`,
})
}
return fixtures
}
export async function fixturesFromFriction(): Promise<RealFixture[]> {
const store = await loadJson<{ items?: Record<string, { title?: string; body?: string; projectId?: string; labels?: string[] }> }>('factory:friction:v1', { items: {} })
const fixtures: RealFixture[] = []
const items = Object.values(store.items ?? {}).slice(0, 10)
for (const [i, item] of items.entries()) {
if (!item.title) continue
fixtures.push({
id: `friction:${i}`,
title: String(item.title).slice(0, 200),
body: String(item.body ?? '').slice(0, 500),
source: 'friction',
labels: Array.isArray(item.labels) ? item.labels.slice(0, 10) : ['friction'],
severity: 'medium',
projectId: item.projectId ?? 'kody',
expectedLabel: 'create_work_item',
origin: 'friction storage',
})
}
return fixtures
}
export async function buildAllFixtures(): Promise<{ fixtures: RealFixture[]; sources: Record<string, number> }> {
const [ledger, github, sentry, friction] = await Promise.all([
fixturesFromLedger().catch(() => []),
fixturesFromGithub().catch(() => []),
fixturesFromSentry().catch(() => []),
fixturesFromFriction().catch(() => []),
])
const fixtures = [...ledger, ...github, ...sentry, ...friction]
const sources: Record<string, number> = {}
for (const f of fixtures) {
sources[f.source] = (sources[f.source] ?? 0) + 1
}
return { fixtures, sources }
}