← 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)) },
async sql(q, b = []) {
(globalThis.__sqlLog ??= []).push({ q, b });
if (/INSERT INTO ci_review_runs/.test(q)) (globalThis.__runs ??= []).push({ run_id: b[0], week: b[1], error: b[9], report_id: b[4] });
if (/FROM ci_review_runs WHERE week = \\?/.test(q)) return { rows: (globalThis.__runs ?? []).filter((r) => r.week === b[0] && r.error == null) };
return { rows: [] };
},
});
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;
`
const NOOP = 'export default async () => { throw new Error("not in tests") }'
registerHooks({
resolve(spec, ctx, next) {
if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
if (spec.startsWith('kody:@kody/')) return { url: `data:text/javascript,${encodeURIComponent(NOOP)}`, shortCircuit: true }
return next(spec, ctx)
},
})
const { runCiReview, setCiReviewDepsForTests } = await import('./run.ts')
const { setReportDepsForTests } = await import('../reports/post.ts')
const { listReports } = await import('../reports/store.ts')
const { loadJson, storageKeys } = await import('../lib/storage.ts')
const { upsertProject } = await import('../projects/config.ts')
const { rankOpportunities } = await import('./rank-core.ts')
const { dataset, run, typicalRun, workflow } = await import('./fixtures.test-helpers.ts')
const g = globalThis as { __factoryStore?: Map<string, unknown>; __sqlLog?: Array<{ q: string }>; __runs?: unknown[] }
function weekDataset() {
const runs = Array.from({ length: 20 }, (_, index) => run({ at: index * 30, wall: 10.2, headBranch: `b${index}` }))
const jobsByRun: Record<string, any> = {}
for (const r of runs) jobsByRun[r.id] = typicalRun(r.id, Date.parse(r.createdAt) / 60000 - Date.parse('2026-11-02T10:00:00Z') / 60000)
return { ...dataset({ workflows: [workflow({ name: '✅ Validate', runs })], jobsByRun }), apiCalls: 321, maxApiCalls: 450 }
}
async function setup() {
g.__factoryStore?.clear()
g.__sqlLog = []
g.__runs = []
await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, repos: [{ host: 'github', owner: 'kody-hq', name: 'kody', enabled: true }] } as never)
const pushes: unknown[] = []
setReportDepsForTests({ sendPush: async (m) => { pushes.push(m); return { ok: true, sent: 1, failed: 0, removed: 0, errors: [] } }, sleep: async () => {} })
setCiReviewDepsForTests({
collect: async () => weekDataset() as never,
rank: async (input) => rankOpportunities({ metrics: input.metrics, opportunities: input.opportunities, evaluate: null }),
now: () => new Date('2026-11-02T11:00:00Z'),
})
return pushes
}
function teardown() {
setReportDepsForTests(null)
setCiReviewDepsForTests(null)
}
test('dry run previews the report and cards and writes nothing', async () => {
const pushes = await setup()
const r = await runCiReview({ dryRun: true }) as any
assert.equal(r.dryRun, true)
assert.equal(r.week, '2026-11-02')
assert.ok(r.cards.length > 0)
assert.ok(r.cards.every((c: { relation: string }) => c.relation === 'created'))
assert.equal(r.report.title, 'Weekly CI review: kody-hq/kody')
assert.ok(r.cardBodies[0].body.length > 100)
assert.equal(pushes.length, 0)
assert.equal((await listReports()).total, 0)
assert.equal(Object.keys((await loadJson<{ items: object }>(storageKeys.LEDGER_KEY, { items: {} })).items).length, 0)
assert.ok(!g.__sqlLog!.some((e) => /^\s*(INSERT|CREATE|DELETE|UPDATE)/i.test(e.q.trim())), 'dry run never writes SQL')
teardown()
})
test('live run posts one report with work and recommendation cards, records the run, and skips a second run that week', async () => {
const pushes = await setup()
const r = await runCiReview({ dryRun: false }) as any
assert.equal(r.ok, true, r.error)
assert.match(r.reportUrl, /\/reports\/rp_/)
assert.ok(r.cards.length > 0)
assert.equal(pushes.length, 1)
const ledger = await loadJson<{ items: Record<string, { source: string; state: string; reportRef?: { id: string } }> }>(storageKeys.LEDGER_KEY, { items: {} })
const items = Object.values(ledger.items)
assert.equal(items.length, r.cards.length)
assert.ok(items.every((i) => i.source === 'ci-review' && i.reportRef?.id === r.reportId))
for (const c of r.cards) assert.equal(ledger.items[c.cardId]!.state, c.needsKent ? 'needs-kent' : 'intake')
const reports = await listReports({ source: 'ci-review' })
assert.equal(reports.total, 1)
assert.equal(reports.reports[0]!.idempotencyKey, 'ci-review-2026-11-02')
assert.ok(g.__sqlLog!.some((e) => /INSERT INTO ci_review_weekly_metrics/.test(e.q)))
assert.ok(g.__sqlLog!.some((e) => /INSERT OR REPLACE INTO ci_review_opportunities/.test(e.q)))
const again = await runCiReview({ dryRun: false }) as any
assert.equal(again.skipped, 'already ran this week')
teardown()
})
test('unknown options throw', async () => {
await setup()
await assert.rejects(runCiReview({ dryRun: true, includePrompt: true } as never), /unknown option: includePrompt/)
teardown()
})