← 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://factory.test' };
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) {
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 }
// Other package imports are not used on these paths.
if (spec.startsWith('kody:@') && spec !== 'kody:@kody/github/request') return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({}); export const evaluate = async () => ({});')}`, shortCircuit: true }
return next(spec, ctx)
},
})
const { setDispatchForTests } = await import('../events/emit.ts')
const { defaultCardRoutes, matchCardRoute, normalizeCardRoutes } = await import('./routes.ts')
const { schemeTags, isFrictionCard, isNightlyCard, hasTag } = await import('./tags.ts')
const { afterCardsCreated, afterCardTriaged, flushHeldPushes, loadAlertState } = await import('./lifecycle.ts')
const { decideCardPush, defaultNotificationRules, resolveRules } = await import('../notifications/types.ts')
const { isQuietHours } = await import('../lib/quiet-hours.ts')
const { upsertProject } = await import('../projects/config.ts')
const { default: fileFriction } = await import('../friction/file.ts')
const { frictionCardPlace } = await import('../friction/cards.ts')
const { loadJson, storageKeys } = await import('../lib/storage.ts')
const { emptyLedger } = await import('../core/work-item.ts')
const { toEntries, nightlyCardsFor, cardEntryNumber } = await import('../friction/card-list.ts')
const { buildGroupPrompt } = await import('../friction/devin-prompt.ts')
const { refreshLabels } = await import('../signals/intake.ts')
const { applySourceLifecycle } = await import('../webhooks/github-issues.ts')
const { sweepRepos } = await import('../friction/shared.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()
}
const wakes = () => sent.filter((e) => e.topic === '@kody/factory.wake.requested')
// 2026-11-24 15:00Z is 8:00 AM MST (day); 06:00Z is 11 PM MST the night before.
const DAY = Date.parse('2026-11-24T16:00:00Z')
const NIGHT = Date.parse('2026-11-24T06:00:00Z')
function card(over: Record<string, unknown> = {}) {
const at = new Date(DAY).toISOString()
return { id: `wi_${Math.random().toString(36).slice(2, 10)}`, projectId: 'kody', title: 'A card', body: 'b', state: 'intake', priority: null, needsKent: false, rank: 0, source: 'manual', externalId: null, fingerprint: `f-${Math.random()}`, signalIds: [], labels: [], repoRef: 'kody-hq/kody', planCardId: null, runId: null, createdAt: at, updatedAt: at, events: [], shadow: false, ...over } as never
}
test('quiet hours: 10 PM to 8 AM America/Denver', () => {
assert.equal(isQuietHours(NIGHT), true)
assert.equal(isQuietHours(DAY), false)
assert.equal(isQuietHours(Date.parse('2026-11-24T14:59:00Z')), true, '7:59 AM')
assert.equal(isQuietHours(Date.parse('2026-11-24T15:00:00Z')), false, '8:00 AM')
})
test('push decision: P0 any time, P1 held at night, P2 only by label or needs-kent', () => {
const rule = resolveRules(defaultNotificationRules(), 'kody')
assert.deepEqual(decideCardPush(rule, { labels: [], needsKent: false, priority: 0 }, NIGHT).send, 'now')
assert.deepEqual(decideCardPush(rule, { labels: [], needsKent: false, priority: 1 }, NIGHT).send, 'hold')
assert.deepEqual(decideCardPush(rule, { labels: [], needsKent: false, priority: 1 }, DAY).send, 'now')
assert.deepEqual(decideCardPush(rule, { labels: [], needsKent: false, priority: 2 }, DAY).send, 'none')
assert.deepEqual(decideCardPush(rule, { labels: [], needsKent: true, priority: 2 }, DAY).send, 'now')
assert.deepEqual(decideCardPush({ ...rule, pushMinPriority: null }, { labels: [], needsKent: false, priority: 0 }, DAY).send, 'none')
})
test('tags: source, kind, area, gh, repo, pkg; friction and nightly detection', () => {
const t = schemeTags({ source: 'github-issues', labels: ['bug', 'ui', 'P1: next'], ghNumber: 42, repoRef: 'kody-hq/kody' })
assert.deepEqual(t, ['bug', 'ui', 'P1: next', 'kind:bug', 'area:ui', 'source:github', 'gh:#42', 'repo:kody-hq/kody'])
assert.ok(schemeTags({ source: 'manual', labels: ['sentry'] }).includes('source:sentry'))
assert.ok(!schemeTags({ source: 'manual', labels: ['sentry'] }).includes('source:manual'))
assert.equal(isFrictionCard({ labels: ['kind:friction'], source: 'manual' }), true)
assert.equal(isNightlyCard({ labels: ['sweep:nightly'], source: 'github-issues' }), true)
assert.equal(isNightlyCard({ labels: ['source:github'], source: 'github-issues' }), false)
assert.equal(hasTag(['pkg:@kody/devin'], 'pkg:*'), true)
})
test('card routes: first match wins, in the order Kent approved', () => {
const r = defaultCardRoutes()
const m = (over: Record<string, unknown>) => matchCardRoute(r, { labels: [], priority: null, needsKent: false, ...over } as never)?.id ?? null
assert.equal(m({ priority: 0, labels: ['kind:friction'] }), 'p0')
assert.equal(m({ labels: ['kind:friction', 'area:security'] }), 'security')
assert.equal(m({ labels: ['kind:friction', 'pkg:@kody/x'] }), 'friction')
assert.equal(m({ needsKent: true, labels: ['pkg:@kody/x'] }), 'needs-kent')
assert.equal(m({ labels: ['pkg:@kody/x'] }), 'package')
assert.equal(m({ labels: ['area:billing'] }), 'platform')
assert.equal(m({ labels: ['source:github'] }), 'github')
assert.equal(m({ labels: ['source:manual'] }), null)
assert.equal(normalizeCardRoutes([{ id: 'x', match: {}, when: 'now' }]).length, 0, 'a now route needs a role or bot')
assert.equal(normalizeCardRoutes('nope').length, r.length)
})
test('created: emits always, pushes P0 now and P1 held at night once, wakes the route once', async () => {
reset()
const p0 = card({ priority: 0, title: 'Down' })
const res = await afterCardsCreated([p0], { now: NIGHT })
assert.equal(res[0]!.emitted, true)
assert.ok(['sent', 'skipped'].includes(res[0]!.push), 'pushed (skipped: no device in tests)')
assert.equal(res[0]!.route?.id, 'p0')
assert.equal(wakes().length, 1)
assert.equal(wakes()[0]!.payload.role, 'platform')
assert.equal(wakes()[0]!.payload.cardId, (p0 as { id: string }).id)
const again = await afterCardsCreated([p0], { now: NIGHT })
assert.equal(again[0]!.push, 'already')
assert.equal(again[0]!.route?.already, true)
assert.equal(wakes().length, 1, 'once per card')
const p1 = card({ priority: 1, title: 'Soon' })
assert.equal((await afterCardsCreated([p1], { now: NIGHT }))[0]!.push, 'held')
assert.equal((await loadAlertState()).held.length, 1)
assert.equal((await flushHeldPushes({ now: NIGHT })).skipped, 'quiet hours')
assert.equal((await flushHeldPushes({ now: DAY })).sent, 1)
assert.equal((await loadAlertState()).held.length, 0)
assert.equal((await afterCardTriaged([{ before: { state: 'intake', priority: 2, needsKent: false, labels: [] }, after: { ...(p1 as object), priority: 0 } as never, reason: 'raise' }], { now: DAY }))[0]!.push, 'already', 'the digest counted as its push')
})
test('quiet create (import) emits card.created and never pushes or wakes', async () => {
reset()
const res = await afterCardsCreated([card({ priority: 0, labels: ['source:github'] })], { quiet: true, now: DAY })
assert.equal(res[0]!.emitted, true)
assert.equal(res[0]!.push, 'quiet')
assert.equal(wakes().length, 0)
assert.equal(sent.filter((e) => e.topic === '@kody/factory.card.created').length, 1)
})
test('triaged: a raise pushes; staying on the same route never re-wakes', async () => {
reset()
const c = card({ labels: ['source:github'] })
await afterCardsCreated([c], { quiet: true, now: DAY })
const same = await afterCardTriaged([{ before: { state: 'intake', priority: null, needsKent: false, labels: ['source:github'] }, after: { ...(c as object), state: 'triaged', labels: ['source:github', 'bug'] } as never, reason: 'label' }], { now: DAY })
assert.equal(same[0]!.route?.already, true)
assert.equal(wakes().length, 0)
assert.equal(sent.filter((e) => e.topic === '@kody/factory.card.triaged').length, 1)
const raised = await afterCardTriaged([{ before: { state: 'triaged', priority: null, needsKent: false, labels: ['source:github'] }, after: { ...(c as object), priority: 0, labels: ['source:github'] } as never, reason: 'P0' }], { now: DAY })
assert.ok(['sent', 'skipped'].includes(raised[0]!.push))
assert.equal(raised[0]!.route?.id, 'p0')
assert.equal(wakes().length, 1)
})
test('friction/file makes intake cards, notes repeats, and routes only P0 or security', 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 target = { host: 'github' as const, repo: 'kody-hq/kody' }
const papercut = { title: 'Pre-push hook reruns knip twice', whatHappened: 'knip ran twice on every push, doubling the hook time', howToReproduce: 'git push on any branch', cost: '40s per push', preliminaryInvestigation: 'looked at .husky/pre-push' }
const first = await fileFriction({ target, items: [papercut] })
assert.equal(first.filed.length, 1)
const cardId = first.filed[0]!.cardId!
assert.match(first.filed[0]!.htmlUrl, /\/c\//)
const ledger = await loadJson(storageKeys.LEDGER_KEY, emptyLedger())
const item = ledger.items[cardId]!
assert.equal(item.state, 'intake')
assert.equal(item.source, 'friction')
for (const t of ['friction', 'source:friction', 'kind:friction', 'repo:kody-hq/kody', 'area:dev-tooling']) assert.ok(item.labels.includes(t), t)
assert.equal(wakes().length, 0, 'friction waits for the night')
const again = await fileFriction({ target, items: [{ ...papercut, cost: '60s per push now' }] })
assert.equal(again.reused.length, 1)
assert.equal(again.reused[0]!.cardId, cardId)
assert.equal(again.reused[0]!.seenCount, 1)
assert.equal(again.reused[0]!.commented, true)
const sec = await fileFriction({ target, items: [{ ...papercut, title: 'Token printed in a log', security: true }] })
assert.equal(sec.filed.length, 1)
assert.equal(wakes().length, 1)
assert.equal(wakes()[0]!.payload.role, 'platform')
const pkg = await fileFriction({ target: { host: 'kody', repo: '@kody/devin' }, items: [{ ...papercut, title: 'devin readme is stale' }] })
const pkgCard = (await loadJson(storageKeys.LEDGER_KEY, emptyLedger())).items[pkg.filed[0]!.cardId!]!
assert.ok(pkgCard.labels.includes('pkg:@kody/devin'))
assert.equal(pkgCard.repoRef, null)
assert.equal(wakes().length, 1, 'package friction waits for the night too')
assert.equal(await frictionCardPlace({ host: 'github', repo: 'someone/else' }), null, 'repos outside the factory keep the GitHub path')
})
test('nightly entries: friction and sweep:nightly cards for the repo, gh numbers kept, prompt is card-shaped', () => {
const f = card({ title: 'Friction: a', labels: ['kind:friction'], source: 'friction' })
const g = card({ title: 'Imported', labels: ['sweep:nightly', 'gh:#77'], source: 'github-issues', externalId: '77' })
const day = card({ title: 'Day work', labels: ['source:github'] })
const nk = card({ title: 'Waits', labels: ['kind:friction'], needsKent: true })
const picked = nightlyCardsFor([f, g, day, nk], 'kody-hq/kody')
assert.deepEqual(picked.map((c: { title: string }) => c.title), ['Friction: a', 'Imported'])
const e = toEntries(picked, 'https://factory.test')
assert.ok(e.cardIds.has(77))
assert.ok(e.cardIds.has(cardEntryNumber((f as { id: string }).id)))
const prompt = buildGroupPrompt({ repo: sweepRepos[0]!, groupName: 'tests', groupKey: 'k', branch: 'b', issues: e.issues, day: '2026-11-24', mode: 'all-issues', cards: e.refs })
assert.match(prompt, /nightly card sweep session/)
assert.match(prompt, /Fixes <cardUrl>/)
assert.match(prompt, /cards: \[/)
assert.match(prompt, /"ghIssue": 77/)
assert.doesNotMatch(prompt, /"number": 1\d{8}/, 'synthetic numbers stay out of the prompt')
})
test('GitHub label refresh updates priority and tags; a moved issue close keeps the card', () => {
const c = card({ source: 'github-issues', externalId: '5', labels: ['source:github', 'gh:#5', 'sweep:nightly'] })
const change = refreshLabels(c, { id: 's', projectId: 'kody', source: 'github-issues', externalId: '5', fingerprint: 'x', title: 't', body: '', severity: 'medium', labels: ['P0: now'], links: [], repoRef: 'kody-hq/kody', receivedAt: '' } as never)
assert.ok(change)
assert.equal(change!.after.priority, 0)
assert.ok(change!.after.labels.includes('sweep:nightly'), 'factory tags survive')
const moved = card({ fingerprint: 'fp', labels: ['gh:moved'] })
const ledger = { version: 1, items: { [(moved as { id: string }).id]: moved } } as never
assert.equal(applySourceLifecycle(ledger, { projectId: 'kody', fingerprint: 'fp', action: 'closed' }).change, 'noted')
})