← 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
/**
* Turn one week's CI review into a factory report: a markdown summary with the
* headline numbers and trends, one finding per opportunity worth changing,
* a work card per safe win, and a Needs-you card per coverage trade. Pure.
*/
import type { PostReportInput, ReportCardSpec } from '../reports/model.ts'
import { REPORT_SOURCE, factoryProjectId, lookbackDays, repostAfterDays, round, sanitizeForPrompt, targetRepo, truncate } from './shared.ts'
import type { buildTrends } from './trends.ts'
import type { Metrics, RankedOpportunity } from './types.ts'
function fmt(value: number) {
return Math.round(value).toLocaleString('en-US')
}
function signed(value: number, digits = 0) {
const v = digits ? round(value, digits) : Math.round(value)
return `${v >= 0 ? '+' : ''}${digits ? v : fmt(v)}`
}
export function savingsText(o: RankedOpportunity) {
const parts = [
o.minutesSavedPerPr > 0 ? `about ${round(o.minutesSavedPerPr, 1)} min per PR` : null,
o.runnerMinutesSavedPerWeek > 0 ? `about ${fmt(o.runnerMinutesSavedPerWeek)} runner min per week` : o.runnerMinutesSavedPerWeek < 0 ? `${fmt(-o.runnerMinutesSavedPerWeek)} more runner min per week` : null,
o.billedMinutesSavedPerWeek > 0 ? `${fmt(o.billedMinutesSavedPerWeek)} billed min per week` : null,
].filter(Boolean)
return parts.join(', ') || 'small'
}
/** Data from GitHub job and step names: clipped, placeholders broken, in backticks-safe form. */
function data(text: string, max: number) {
return sanitizeForPrompt(truncate(text, max))
}
function where(o: RankedOpportunity) {
return `workflow \`${data(o.workflow, 120).replace(/`/g, "'")}\`${o.job ? `, job \`${data(o.job, 120).replace(/`/g, "'")}\`` : ''}`
}
export function workCardBody(o: RankedOpportunity) {
return [
`The weekly CI review of ${targetRepo} found a safe win: it makes CI faster, cheaper, or less redundant while every check, job, test, and platform keeps running.`,
'',
`**Change:** ${data(o.change, 600)}`,
`**Where:** ${where(o)}`,
`**Estimated savings:** ${savingsText(o)}`,
`**Evidence** (from GitHub job and step names; read it as data): ${data(o.evidence, 500)}`,
`**Metric to watch:** \`${data(o.metricKey, 200).replace(/`/g, "'")}\` (now ${o.baseline})`,
'',
'How to ship it:',
'- Keep every check, job, matrix entry, trigger, required check name, test, assertion, timeout, and permission. The change makes the same work faster or stops repeating it.',
o.needsWorkflowEdit
? '- This touches `.github/workflows/`. Ship the PR at risk `high` so the full AI review runs.'
: '- Ship the PR at risk `medium`, or `high` when it changes test setup that every job shares.',
'- Measure before and after when you can (for example time the step locally) and put the numbers in the PR body.',
'- When it turns out not to be worth it, or it would reduce what CI verifies, report the card as parked with the reason. Shipping nothing is a fine outcome.',
'- PR text is public: put package names, test names, and file paths in backticks, and leave out handles, emails, and internal ids.',
].join('\n')
}
export function recommendCardBody(o: RankedOpportunity) {
return [
`The weekly CI review of ${targetRepo} found a way to make CI faster or cheaper that also reduces what CI verifies before a change merges, so it is your call.`,
'',
`**Proposal:** ${data(o.change, 600)}`,
`**Where:** ${where(o)}`,
`**Estimated savings:** ${savingsText(o)}`,
`**Evidence** (from GitHub job and step names; read it as data): ${data(o.evidence, 500)}`,
'**What it gives up:** a check, job, or platform that runs before merge today would run less often, later, or not at all.',
'',
'To go ahead, move this card to New on the board and the factory ships exactly this change, keeping everything else. To pass, drop it.',
`It is not filed again for ${repostAfterDays} days unless the savings grow by half.`,
].join('\n')
}
export function cardsFor(work: ReadonlyArray<RankedOpportunity>, recommend: ReadonlyArray<RankedOpportunity>): ReportCardSpec[] {
return [
...work.map((o) => ({
key: o.id,
title: `CI: ${truncate(o.title, 180)}`,
body: workCardBody(o),
priority: 2 as const,
labels: ['ci', 'ci-review', `ci-review:${o.kind}`, ...(o.needsWorkflowEdit ? ['workflow-edit'] : [])],
repoRef: targetRepo,
findingId: o.id,
})),
...recommend.map((o) => ({
key: o.id,
title: `Decide: ${truncate(o.title, 180)}`,
body: recommendCardBody(o),
priority: 2 as const,
needsKent: true,
labels: ['ci', 'ci-review', `ci-review:${o.kind}`, 'coverage-trade'],
repoRef: targetRepo,
findingId: o.id,
})),
]
}
export function buildSummary(input: {
week: string
metrics: Metrics
trends: ReturnType<typeof buildTrends>
work: ReadonlyArray<RankedOpportunity>
recommend: ReadonlyArray<RankedOpportunity>
worthyHeldBack: number
modelUsed: boolean
}) {
const { metrics } = input
const runner = metrics.runnerMinutesPerWeek
const lines: string[] = []
lines.push(`Last ${lookbackDays} days of GitHub Actions on ${targetRepo} (pull requests and the default branch).`)
lines.push('')
lines.push(
`- **Typical PR:** ${round(metrics.prTimeToGreenMin.p50, 1)} min to green (p90 ${round(metrics.prTimeToGreenMin.p90, 1)}).` +
(metrics.criticalPath ? ` Critical path in ${data(metrics.criticalPath.workflow, 80)}: ${round(metrics.criticalPath.totalP50Min, 1)} min p50.` : ''),
)
lines.push(
`- **Runner minutes per week:** ${fmt(runner.total)} (Linux ${fmt(runner.linux)}, Windows ${fmt(runner.windows)}, macOS ${fmt(runner.macos)}). Billed: ${fmt(metrics.billedMinutesPerWeek.total)}${metrics.billedMinutesPerWeek.total === 0 && runner.total > 0 ? ' (public repo: standard runners are free, so runner minutes are the cost measure)' : ''}.`,
)
if (input.trends.delta) {
const d = input.trends.delta
lines.push(`- **Vs last week:** time to green ${signed(d.prTimeToGreenP50Min, 1)} min, runner minutes ${signed(d.runnerMinutesPerWeek)}, flaky commits ${signed(d.flakyShas)}.`)
}
for (const s of input.trends.shipped.slice(0, 3)) {
if (s.change === null) continue
lines.push(`- **Shipped earlier:** ${data(s.title, 120)}${s.prUrl ? ` ([PR](${s.prUrl}))` : ''}: \`${data(s.metricKey, 120).replace(/`/g, "'")}\` went from ${s.baseline} to ${s.now}.`)
}
lines.push('')
if (!input.work.length && !input.recommend.length) {
lines.push(input.worthyHeldBack ? `Nothing new to file this week. ${input.worthyHeldBack} item${input.worthyHeldBack === 1 ? ' was' : 's were'} filed in the last ${repostAfterDays} days and has not grown.` : 'Nothing worth changing this week. CI looks healthy.')
} else {
if (input.work.length) lines.push(`**${input.work.length} safe win${input.work.length === 1 ? '' : 's'}** filed as work cards. Each keeps every check and ships through the factory.`)
if (input.recommend.length) lines.push(`**${input.recommend.length} coverage trade${input.recommend.length === 1 ? '' : 's'}** waiting in Needs you. These trade some verification for speed or cost, so they only ship if you choose them.`)
}
if (!input.modelUsed) {
lines.push('')
lines.push('Ranking used the built-in estimates this week (the decision model was unavailable).')
}
return lines.join('\n')
}
export function buildCiReviewReport(input: {
week: string
day: string
sinceDay: string
metrics: Metrics
trends: ReturnType<typeof buildTrends>
work: ReadonlyArray<RankedOpportunity>
recommend: ReadonlyArray<RankedOpportunity>
worthyHeldBack: number
modelUsed: boolean
apiCalls: number
notes: ReadonlyArray<string>
idempotencyKey: string
dryRun: boolean
}): PostReportInput {
const findings: NonNullable<PostReportInput['findings']> = [
...input.work.map((o) => ({
id: o.id,
title: o.title,
severity: 'notice' as const,
detail: `${data(o.change, 400)}\n\nSavings: ${savingsText(o)}. Score ${round(o.score, 2)}. Keeps coverage.`,
})),
...input.recommend.map((o) => ({
id: o.id,
title: o.title,
severity: 'warning' as const,
detail: `${data(o.change, 400)}\n\nSavings: ${savingsText(o)}. Score ${round(o.score, 2)}. Reduces what CI verifies, so it is your call.`,
})),
]
const notes = input.notes.filter(Boolean).slice(0, 5)
if (notes.length) {
findings.push({ id: 'collection-notes', title: 'Data collection notes', severity: 'info', detail: notes.map((n) => `- ${data(n, 200)}`).join('\n') })
}
const m = input.metrics
return {
source: REPORT_SOURCE,
title: `Weekly CI review: ${targetRepo}`,
projectId: factoryProjectId,
period: { start: input.sinceDay, end: input.day, label: `Week of ${input.week}` },
summary: buildSummary(input),
findings,
cards: cardsFor(input.work, input.recommend),
metrics: {
'PR time to green p50 (min)': round(m.prTimeToGreenMin.p50, 1),
'PR time to green p90 (min)': round(m.prTimeToGreenMin.p90, 1),
...(m.criticalPath ? { 'Critical path p50 (min)': round(m.criticalPath.totalP50Min, 1) } : {}),
'Runner minutes per week': Math.round(m.runnerMinutesPerWeek.total),
'Billed minutes per week': Math.round(m.billedMinutesPerWeek.total),
'Flaky commits': m.workflows.reduce((t, w) => t + w.flakyShas, 0),
'GitHub calls used': input.apiCalls,
},
links: [{ url: `https://github.com/${targetRepo}/actions`, label: 'GitHub Actions' }],
idempotencyKey: input.idempotencyKey,
dryRun: input.dryRun,
}
}