← 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'
// The stub deliberately has no `events` export: modules must still load.
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/' };
export async function credential(key) { throw new Error('credential not mapped: ' + key); }
export async function credentials() { return [] }
export const kody = {};
`
registerHooks({
resolve(spec, ctx, next) {
// Wake alerts can post to Discord; tests stub it (wake-transport tests also swap it out).
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 { setDispatchForTests, emitFactoryEvent, emitHealthEvent, TOPICS, clipToBytes, utf8Bytes } = await import('./emit.ts')
const { buildWakeRequest, roleForBot } = await import('./wake-request.ts')
const { handleSourceEvent, drCardParams, outageCardParams, loadEventCardLog, SOURCE_TOPICS } = await import('./cards.ts')
const { patchSettings, loadSettings } = await import('../lib/settings.ts')
const { upsertProject } = await import('../projects/config.ts')
const { default: eventsStatus } = await import('../exports/events-status.ts')
const { default: create } = await import('../exports/create.ts')
type Sent = { topic: string; idempotencyKey: string; payload: Record<string, unknown> }
const sent: Sent[] = []
setDispatchForTests(async (input) => {
sent.push(input)
return { status: 'enqueued' }
})
function reset() {
sent.length = 0
;(globalThis as { __factoryStore?: Map<string, unknown> }).__factoryStore?.clear()
}
test('settings: health events off and event cards in shadow by default', async () => {
reset()
const s = await loadSettings()
assert.equal(s.emitHealthEvents, false)
assert.equal(s.eventCardsMode, 'shadow')
await patchSettings({ eventCardsMode: 'bogus' as never })
assert.equal((await loadSettings()).eventCardsMode, 'shadow')
})
test('wake prompt is clipped to the byte budget and roles map by bot', () => {
const big = 'é'.repeat(40_000)
const { payload } = buildWakeRequest({ source: 'signal', bot: 'cole', prompt: big, reason: 'r', ref: 's', now: 0 })
assert.ok(utf8Bytes(payload.prompt) <= 48 * 1024)
assert.equal(payload.role, 'platform')
assert.equal(roleForBot('pam'), 'package-triage')
assert.equal(clipToBytes('abc', 2), 'ab')
})
test('an emit failure never throws', async () => {
reset()
setDispatchForTests(async () => { throw new Error('queue down') })
const r = await emitFactoryEvent(TOPICS.cardCreated, 'k', { itemId: 'x', projectId: 'kody' })
assert.equal(r.emitted, false)
assert.match(String(r.error), /queue down/)
setDispatchForTests(async (input) => { sent.push(input); return { status: 'enqueued' } })
})
test('health events stay off until emitHealthEvents is on', async () => {
reset()
assert.equal((await emitHealthEvent(TOPICS.fingerprintQueued, 'k1', { fingerprint: 'f' })).skipped, 'emitHealthEvents-off')
await patchSettings({ emitHealthEvents: true })
assert.equal((await emitHealthEvent(TOPICS.fingerprintQueued, 'k1', { fingerprint: 'f' })).emitted, true)
assert.equal(sent.at(-1)!.topic, '@kody/factory.health.fingerprint.queued')
})
test('create() always emits card.created with needsKent, url, and tags', async () => {
reset()
await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'k', repoRef: 'kody-hq/kody', host: 'github', enabled: true }] } as never)
const r = await create({ projectId: 'kody', title: 'loud', priority: 2, labels: ['bug'] })
const created = sent.filter((e) => e.topic === '@kody/factory.card.created')
assert.equal(created.length, 1, 'emitted with emitHealthEvents off')
assert.equal(created[0]!.payload.itemId, r.item.id)
assert.equal(created[0]!.payload.priority, 2)
assert.equal(created[0]!.payload.needsKent, false)
assert.match(String(created[0]!.payload.url), /\/c\//)
assert.deepEqual(created[0]!.payload.tags, ['kind:bug', 'source:manual'])
await create({ projectId: 'kody', title: 'imported', quiet: true })
assert.equal(sent.filter((e) => e.topic === '@kody/factory.card.created').length, 2, 'quiet creates still emit')
})
const drPayload = { day: '2026-11-22', kind: 'paced-seal-missing', priority: 1, urgent: false, title: 'DR backup 2026-11-22: Paced D1 backup not sealed', problem: 'Paced D1 backup for 2026-11-22 is not sealed for APP_DB', idempotencyKey: 'dr-backup-2026-11-22-paced-seal-missing' }
const drEnvelope = (payload: Record<string, unknown> = drPayload, kodyId = 'dr-backup-health') => ({ event: SOURCE_TOPICS.drProblemDetected, source: { type: 'package', package_id: 'p', kody_id: kodyId }, idempotency_key: 'x', payload })
test('drCardParams reuses the key Cole files by hand and raises urgent to P0', () => {
const p = drCardParams(drPayload)!
assert.equal(p.idempotencyKey, 'dr-backup-2026-11-22-paced-seal-missing')
assert.equal(p.priority, 1)
assert.equal(drCardParams({ ...drPayload, urgent: true })!.priority, 0)
assert.equal(drCardParams({ day: 'nope', kind: 'x' }), null)
})
test('outage cards dedupe on the sorted incident set', () => {
const a = outageCardParams({ incidentIds: ['b', 'a'], components: ['API'] })!
const b = outageCardParams({ incidentIds: ['a', 'b'] })!
assert.equal(a.idempotencyKey, b.idempotencyKey)
assert.equal(a.priority, 0)
assert.equal(outageCardParams({ incidentIds: [] }), null)
})
test('shadow mode records would-create once and never touches the ledger', async () => {
reset()
await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'k', repoRef: 'kody-hq/kody', host: 'github', enabled: true }] } as never)
const first = await handleSourceEvent(SOURCE_TOPICS.drProblemDetected, drEnvelope())
const again = await handleSourceEvent(SOURCE_TOPICS.drProblemDetected, drEnvelope())
assert.equal(first.action, 'would-create')
assert.equal(again.action, 'replayed')
const log = await loadEventCardLog()
assert.equal(log.length, 1)
const store = (globalThis as { __factoryStore?: Map<string, string> }).__factoryStore!
assert.equal(store.get('factory:ledger:v1'), undefined)
const status = await eventsStatus()
assert.equal(status.switches.eventCardsMode, 'shadow')
assert.equal(status.recentEventCards.length, 1)
})
test('events from an unexpected package are ignored', async () => {
reset()
const r = await handleSourceEvent(SOURCE_TOPICS.drProblemDetected, drEnvelope(drPayload, 'some-other-package'))
assert.equal(r.action, 'ignored')
assert.equal((await loadEventCardLog()).length, 0)
})
test('live mode files one card through create() and replays a hand-filed card with the same key', async () => {
reset()
await upsertProject({ id: 'kody', displayName: 'Kody', enabled: true, defaultRunnerId: 'single-agent', repos: [{ id: 'k', repoRef: 'kody-hq/kody', host: 'github', enabled: true }] } as never)
await patchSettings({ eventCardsMode: 'live' })
// Cole filed this cause by hand first, with the same key.
const manual = await create({ projectId: 'kody', title: 'hand filed', idempotencyKey: 'dr-backup-2026-11-22-paced-seal-missing' })
const r = await handleSourceEvent(SOURCE_TOPICS.drProblemDetected, drEnvelope())
assert.equal(r.action, 'replayed')
assert.equal(r.itemId, manual.item.id)
assert.equal(sent.filter((e) => e.topic === '@kody/factory.wake.requested').length, 0, 'a replayed card sends no wake')
const o = await handleSourceEvent(SOURCE_TOPICS.outageOpened, { source: { type: 'package', kody_id: 'status-alerts' }, payload: { incidentIds: ['i1'], components: ['API'] } })
assert.equal(o.action, 'created')
const wakes = sent.filter((e) => e.topic === '@kody/factory.wake.requested')
assert.equal(wakes.length, 1, 'a new outage card asks the relay for one wake')
assert.equal(wakes[0]!.payload.role, 'outage')
assert.equal('bot' in wakes[0]!.payload, false)
assert.equal(wakes[0]!.payload.cardId, o.itemId)
assert.equal(wakes[0]!.payload.dryRun, false)
assert.equal(o.wakeRequestId, wakes[0]!.payload.requestId)
assert.match(String(wakes[0]!.payload.prompt), /untrusted data/)
const o2 = await handleSourceEvent(SOURCE_TOPICS.outageOpened, { source: { type: 'package', kody_id: 'status-alerts' }, payload: { incidentIds: ['i1'] } })
assert.equal(o2.action, 'replayed')
assert.equal(o2.itemId, o.itemId)
const c = await handleSourceEvent(SOURCE_TOPICS.outageCleared, { source: { type: 'package', kody_id: 'status-alerts' }, payload: { incidentIds: ['i1'] } })
assert.equal(c.action, 'noted')
const after = sent.filter((e) => e.topic === '@kody/factory.wake.requested')
assert.equal(after.length, 2, 'replays send no wake; the clear sends one all-clear')
assert.equal(after[1]!.payload.role, 'outage')
assert.equal(after[1]!.payload.cardId, o.itemId)
assert.match(String(after[1]!.payload.prompt), /All clear/)
const c2 = await handleSourceEvent(SOURCE_TOPICS.outageCleared, { source: { type: 'package', kody_id: 'status-alerts' }, payload: { incidentIds: ['i1'] } })
assert.equal(c2.action, 'replayed')
assert.equal(sent.filter((e) => e.topic === '@kody/factory.wake.requested').length, 2, 'a replayed clear sends nothing')
})
test('self-test emits one dry-run wake.requested that fits the declared schema', async () => {
reset()
const { default: selfTest } = await import('../exports/events-self-test.ts')
const r = await selfTest({ role: 'platform', note: 'smoke' })
assert.equal(r.emitted, true)
assert.equal(sent.length, 1)
const [e] = sent
assert.equal(e!.topic, '@kody/factory.wake.requested')
assert.equal(e!.payload.dryRun, true)
assert.equal(e!.payload.shadow, true)
assert.equal(e!.payload.role, 'platform')
assert.equal(e!.payload.source, 'self-test')
const fs = await import('node:fs')
const pkg = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8'))
const allowed = Object.keys(pkg.kody.emits['@kody/factory.wake.requested'].payloadSchema.properties)
for (const k of Object.keys(e!.payload)) assert.ok(allowed.includes(k), `undeclared field ${k}`)
const bogus = await selfTest({ role: 'nope' })
assert.equal(sent[1]!.payload.role, 'package-triage')
assert.equal(bogus.dryRun, true)
})