โ 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
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/', hostedUrl: 'https://kody-factory--kody.kody.run/' };
export async function credential(key) { throw new Error('credential not mapped: ' + key); }
export async function credentials() { return [] }
export const kody = {};
export const workflows = null;
`
registerHooks({
resolve(spec, ctx, next) {
if (spec === 'kody:@kody/discord/post-message') return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true })')}`, shortCircuit: true }
if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
return next(spec, ctx)
},
})
const { postReport, removeReport, setReportDepsForTests, findOpenReportCard } = await import('./post.ts')
const { normalizeReportInput, shouldPushReport, reportPushBody, pruneReports } = await import('./model.ts')
const { listReports, getReport } = await import('./store.ts')
const { loadJson, saveJson, storageKeys } = await import('../lib/storage.ts')
const { upsertProject } = await import('../projects/config.ts')
const { default: entry } = await import('../app/entry.ts')
const { default: listExport } = await import('../exports/reports/list.ts')
const { default: getExport } = await import('../exports/reports/get.ts')
type Ledger = { items: Record<string, { id: string; state: string; needsKent: boolean; source: string; labels: string[]; links?: Array<{ url: string }>; reportRef?: { id: string; key: string }; events: Array<{ reason: string }> }> }
const reset = () => (globalThis as { __factoryStore?: Map<string, unknown> }).__factoryStore?.clear()
async function setup() {
reset()
await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, repos: [{ host: 'github', owner: 'kody-hq', name: 'kody', enabled: true }] } as never)
const sent: Array<Record<string, unknown>> = []
setReportDepsForTests({
sendPush: async (m) => { sent.push(m as unknown as Record<string, unknown>); return { ok: true, sent: 1, failed: 0, removed: 0, errors: [] } },
sleep: async () => {},
})
return sent
}
const ledger = () => loadJson<Ledger>(storageKeys.LEDGER_KEY, { items: {} })
function base(extra: Record<string, unknown> = {}) {
return {
source: 'ci-review',
title: 'Weekly CI review: kody-hq/kody',
projectId: 'kody',
period: { start: '2026-11-16', end: '2026-11-23', label: 'Week of 2026-11-23' },
summary: 'Typical PR: **16 min** to green.\n\n- one\n- two',
...extra,
}
}
test('a quiet report is recorded with no cards and no push', async () => {
const sent = await setup()
const r = await postReport(base({ findings: [{ title: 'Nothing worth changing', severity: 'info' }] }))
assert.equal(r.noteworthy, false)
assert.equal(r.cards.length, 0)
assert.deepEqual(r.push, { skipped: 'nothing new for the owner' })
assert.equal(sent.length, 0)
const stored = await getReport(r.reportId)
assert.equal(stored?.title, 'Weekly CI review: kody-hq/kody')
assert.equal(stored?.findings[0]!.id, 'f1')
assert.match(r.reportUrl, /^https:\/\/kody-factory--kody\.kody\.run\/reports\/rp_[a-z0-9]{16}$/)
assert.equal(Object.keys((await ledger()).items).length, 0)
setReportDepsForTests(null)
})
test('one report files work cards and needs-you cards, links them both ways, and pushes once', async () => {
const sent = await setup()
const r = await postReport(base({
findings: [
{ id: 'cache-setup:validate', title: 'Cache node_modules', severity: 'notice' },
{ id: 'drop-variant:node20', title: 'Drop the Node 20 leg', severity: 'warning', flagged: true },
],
cards: [
{ key: 'cache-setup:validate', title: 'Cache node_modules in Validate', body: 'Brief', priority: 2, findingId: 'cache-setup:validate', labels: ['ci'] },
{ key: 'fix-flaky:publish', title: 'Fix the publish flake', priority: 1 },
{ key: 'drop-variant:node20', title: 'Decide: drop the Node 20 leg', needsKent: true, findingId: 'drop-variant:node20' },
],
}))
assert.equal(r.noteworthy, true)
assert.equal(r.cards.length, 3)
assert.deepEqual(r.cards.map((c) => c.relation), ['created', 'created', 'created'])
assert.equal(sent.length, 1, 'one push per report, not per card')
assert.equal(sent[0]!.path, `/reports/${r.reportId}`)
assert.equal(sent[0]!.kind, 'report')
assert.match(String(sent[0]!.body), /^3 new cards \(1 needs you\) ยท 1 flagged finding/)
const items = (await ledger()).items
const work = items[r.cards[0]!.cardId]!
assert.equal(work.state, 'intake')
assert.equal(work.source, 'ci-review')
assert.deepEqual(work.labels, ['report', 'source:ci-review', 'ci'])
assert.equal(work.reportRef?.id, r.reportId)
assert.ok(work.links?.some((l) => l.url === r.reportUrl))
const decision = items[r.cards[2]!.cardId]!
assert.equal(decision.state, 'needs-kent')
assert.equal(decision.needsKent, true)
assert.ok(decision.labels.includes('needs-you'))
const stored = (await getReport(r.reportId))!
assert.equal(stored.findings[0]!.cardId, r.cards[0]!.cardId)
assert.equal(stored.findings[1]!.cardId, r.cards[2]!.cardId)
assert.equal(r.cards[0]!.cardUrl, `https://kody-factory--kody.kody.run/c/${r.cards[0]!.cardId}`)
setReportDepsForTests(null)
})
test('a later report links the open card instead of filing a duplicate, and stays quiet about it', async () => {
const sent = await setup()
const first = await postReport(base({ cards: [{ key: 'opp-1', title: 'Speed up step' }] }))
sent.length = 0
const second = await postReport(base({ title: 'Weekly CI review (next week)', cards: [{ key: 'opp-1', title: 'Speed up step' }] }))
assert.equal(second.cards[0]!.relation, 'existing')
assert.equal(second.cards[0]!.cardId, first.cards[0]!.cardId)
assert.equal(second.noteworthy, true)
assert.equal(sent.length, 0, 'seeing an open card again does not push')
const item = (await ledger()).items[first.cards[0]!.cardId]!
assert.ok(item.links?.some((l) => l.url === second.reportUrl))
assert.match(item.events.at(-1)!.reason, /^seen again in report/)
// Once the card is done, the same key files a fresh card.
const l = await ledger()
l.items[first.cards[0]!.cardId]!.state = 'shipped'
await saveJson(storageKeys.LEDGER_KEY, l)
const third = await postReport(base({ cards: [{ key: 'opp-1', title: 'Speed up step' }] }))
assert.equal(third.cards[0]!.relation, 'created')
assert.notEqual(third.cards[0]!.cardId, first.cards[0]!.cardId)
assert.equal(findOpenReportCard(await ledger() as never, 'ci-review', 'kody', 'opp-1')?.id, third.cards[0]!.cardId)
setReportDepsForTests(null)
})
test('idempotency key replays the first report; dry run writes nothing', async () => {
const sent = await setup()
const dry = await postReport(base({ cards: [{ key: 'a', title: 'A' }], dryRun: true }))
assert.equal(dry.dryRun, true)
assert.equal(dry.cards.length, 1)
assert.equal(Object.keys((await ledger()).items).length, 0)
assert.equal((await listReports()).total, 0)
const a = await postReport(base({ idempotencyKey: 'ci-review-2026-11-23', cards: [{ key: 'a', title: 'A' }] }))
const b = await postReport(base({ idempotencyKey: 'ci-review-2026-11-23', cards: [{ key: 'a', title: 'A' }] }))
assert.equal(b.replayed, true)
assert.equal(b.reportId, a.reportId)
assert.equal(Object.keys((await ledger()).items).length, 1)
assert.equal(sent.length, 1)
setReportDepsForTests(null)
})
test('notify:false and project push off skip the push', async () => {
const sent = await setup()
const r = await postReport(base({ notify: false, cards: [{ key: 'a', title: 'A' }] }))
assert.deepEqual(r.push, { skipped: 'notify: false' })
await saveJson('factory:notification-rules:v1', { defaults: { pushEnabled: false, pushLabels: [], pushNeedsAttention: false, inApp: true }, projects: {} })
const q = await postReport(base({ cards: [{ key: 'b', title: 'B' }] }))
assert.deepEqual(q.push, { skipped: 'push is off for this project' })
assert.equal(sent.length, 0)
setReportDepsForTests(null)
})
test('validation: cards need a project, keys are unique, findingId must exist', async () => {
assert.throws(() => normalizeReportInput({ source: 'CI Review!', title: 't', summary: 's' }), /source must be a short slug/)
assert.throws(() => normalizeReportInput({ source: 'x', title: 't', summary: 's', cards: [{ key: 'a', title: 'A' }] }), /projectId is required/)
assert.throws(() => normalizeReportInput({ source: 'x', title: 't', summary: 's', projectId: 'p', cards: [{ key: 'a', title: 'A' }, { key: 'a', title: 'B' }] }), /duplicate card key/)
assert.throws(() => normalizeReportInput({ source: 'x', title: 't', summary: 's', projectId: 'p', cards: [{ key: 'a', title: 'A', findingId: 'nope' }] }), /not a finding/)
const n = normalizeReportInput({ source: 'x', title: 't', summary: 's', findings: [{ title: 'bad', severity: 'critical' }], links: ['javascript:alert(1)', 'https://ok.example/x'] })
assert.equal(n.findings[0]!.flagged, true, 'critical findings are always flagged')
assert.deepEqual(n.links, [{ url: 'https://ok.example/x' }])
await setup()
await assert.rejects(postReport({ source: 'x', title: 't', summary: 's', projectId: 'missing', cards: [{ key: 'a', title: 'A' }] }), /unknown projectId/)
setReportDepsForTests(null)
})
test('push rules: only new cards or flagged findings push', () => {
const card = (relation: 'created' | 'existing', needsKent = false) => ({ cardId: 'wi_1', key: 'k', title: 't', relation, state: 'intake' as const, needsKent })
assert.equal(shouldPushReport({ cards: [], findings: [] }), false)
assert.equal(shouldPushReport({ cards: [card('existing')], findings: [] }), false)
assert.equal(shouldPushReport({ cards: [card('created')], findings: [] }), true)
assert.equal(shouldPushReport({ cards: [], findings: [{ id: 'f', title: 'f', severity: 'warning', flagged: true }] }), true)
assert.equal(reportPushBody({ cards: [card('created', true)], findings: [], summary: '**Hi** there' }), '1 new card (1 needs you) ยท Hi there')
const store = { version: 1 as const, reports: Object.fromEntries(Array.from({ length: 5 }, (_, i) => [`r${i}`, { id: `r${i}`, createdAt: `2026-11-0${i + 1}T00:00:00Z` }])) } as never
assert.deepEqual(Object.keys(pruneReports(store, 2).reports).sort(), ['r3', 'r4'])
})
test('remove deletes the report and only untouched cards it created', async () => {
await setup()
const r = await postReport(base({ notify: false, cards: [{ key: 'a', title: 'A' }, { key: 'b', title: 'B', needsKent: true }, { key: 'c', title: 'C' }] }))
const l = await ledger()
l.items[r.cards[2]!.cardId]!.state = 'running'
await saveJson(storageKeys.LEDGER_KEY, l)
const dry = await removeReport({ reportId: r.reportId, removeCards: true, dryRun: true })
assert.equal(dry.removedCards.length, 2)
assert.ok(await getReport(r.reportId))
const out = await removeReport({ reportId: r.reportId, removeCards: true })
assert.deepEqual(out.removedCards.sort(), [r.cards[0]!.cardId, r.cards[1]!.cardId].sort())
assert.deepEqual(out.keptCards, [{ cardId: r.cards[2]!.cardId, reason: 'already running' }])
assert.equal(await getReport(r.reportId), null)
const items = (await ledger()).items
assert.equal(Object.keys(items).length, 1)
assert.ok(items[r.cards[2]!.cardId])
setReportDepsForTests(null)
})
test('app: reports list and detail render with cards, findings, and the nav link; list/get exports', async () => {
await setup()
const quiet = await postReport(base({ source: 'docs-audit', title: 'Docs audit: all fresh', notify: false }))
const r = await postReport(base({ notify: false, findings: [{ id: 'f-a', title: 'Cache setup', severity: 'notice', detail: 'Use `actions/cache`.' }], cards: [{ key: 'a', title: 'Cache setup <script>', findingId: 'f-a' }, { key: 'b', title: 'Decide coverage', needsKent: true }] }))
const listRes = await entry.fetch(new Request('https://kody-factory--kody.kody.run/apps/factory/reports'))
assert.equal(listRes.status, 200)
const listHtml = await listRes.text()
assert.match(listHtml, /href="\/apps\/factory\/reports" aria-current="page"/)
assert.ok(listHtml.includes(`/apps/factory/reports/${r.reportId}`))
assert.ok(listHtml.includes(`/apps/factory/reports/${quiet.reportId}`))
assert.match(listHtml, /<span class="chip off">Quiet<\/span>/)
assert.match(listHtml, /2 new cards/)
const quietOnly = await (await entry.fetch(new Request('https://kody-factory--kody.kody.run/apps/factory/reports?show=quiet'))).text()
assert.ok(quietOnly.includes(quiet.reportId) && !quietOnly.includes(r.reportId))
const bySource = await (await entry.fetch(new Request('https://kody-factory--kody.kody.run/apps/factory/reports?source=docs-audit'))).text()
assert.ok(bySource.includes(quiet.reportId) && !bySource.includes(r.reportId))
const detail = await (await entry.fetch(new Request(`https://kody-factory--kody.kody.run/apps/factory/reports/${r.reportId}`))).text()
assert.ok(detail.includes(`/apps/factory/cards/${r.cards[0]!.cardId}`))
assert.ok(detail.includes('Cache setup <script>'))
assert.ok(!detail.includes('<script>alert'))
assert.match(detail, /<strong>16 min<\/strong>/)
assert.match(detail, /<code>actions\/cache<\/code>/)
assert.match(detail, /Decision for you/)
assert.match(detail, /Card filed/)
const missing = await entry.fetch(new Request('https://kody-factory--kody.kody.run/apps/factory/reports/rp_0000000000000000'))
assert.equal(missing.status, 404)
const api = await (await entry.fetch(new Request(`https://kody-factory--kody.kody.run/apps/factory/api/reports/${r.reportId}`))).json() as { report: { id: string } }
assert.equal(api.report.id, r.reportId)
const listed = await listExport({ source: 'ci-review' })
assert.equal(listed.total, 1)
assert.equal(listed.reports[0]!.cards.length, 2)
const got = await getExport({ reportId: r.reportId })
assert.equal(got.cards[0]!.state, 'intake')
assert.equal(got.cards[1]!.state, 'needs-kent')
setReportDepsForTests(null)
})