← 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() { throw new Error('sql not stubbed') },
});
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) {
if (spec === 'kody:runtime') return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
if (spec.startsWith('kody:@kody/')) return { url: `data:text/javascript,${encodeURIComponent('export default async () => ({ ok: true })')}`, shortCircuit: true }
return next(spec, ctx)
},
})
const { setAgentShadowStoreForTests, loadRunnerSession } = await import('./store.ts')
const { handleSessionEvent, adoptStartedSession, toRunnerSession } = await import('./handle.ts')
const { eventsRunner } = await import('./events-runner.ts')
const { setDispatchForTests } = await import('../events/emit.ts')
const { defaultRunnerSettings, normalizeRunnerSettings, runnerForPackage } = await import('../adapters/agent/runners.ts')
const { runSessionUrl, sessionUrlFor } = await import('../adapters/agent/session-url.ts')
const { resolveAgentRunner } = await import('../adapters/agent/index.ts')
const { toBoardCard } = await import('../core/board.ts')
const { patchSettings, loadSettings } = await import('../lib/settings.ts')
const { saveJson, loadJson, storageKeys } = await import('../lib/storage.ts')
const pkg = (await import('../../package.json', { with: { type: 'json' } })).default as {
exports: Record<string, string>
kody: { subscriptions: Record<string, { handler: string }>; emits: Record<string, unknown> }
}
type Row = { runId: string; topic: string; match: boolean; directState: string; eventState: string }
const rows: Row[] = []
setAgentShadowStoreForTests({
async put(r) { rows.push(r) },
async recent(limit) { return rows.slice(-limit).reverse() as never },
})
const envelope = (payload: Record<string, unknown>, kodyId = 'devin') => ({ event: 't', source: { type: 'package', kody_id: kodyId }, payload })
test('runner settings default to events through @kody/devin and name its exports', () => {
const r = defaultRunnerSettings()
assert.equal(r.devin!.mode, 'events')
assert.equal(normalizeRunnerSettings({ devin: { mode: 'builtin' } }).devin!.mode, 'events')
assert.equal(r.devin!.package, 'devin')
assert.equal(r.devin!.exports.start, 'kody:@kody/devin/start')
assert.equal(r.devin!.exports.status, 'kody:@kody/devin/status')
assert.equal(runnerForPackage(r, 'devin'), 'devin')
assert.equal(runnerForPackage(r, 'other'), null)
const n = normalizeRunnerSettings({ devin: { mode: 'events', sessionUrlTemplate: 'javascript:alert(1)' } })
assert.equal(n.devin!.mode, 'events')
assert.match(n.devin!.sessionUrlTemplate, /^https:\/\//)
})
test('session links come from the runner: start link first, then template, none for dry or pending', () => {
const runners = defaultRunnerSettings()
assert.equal(runSessionUrl('abc', 'devin', runners), 'https://app.devin.ai/sessions/abc')
assert.equal(runSessionUrl('abc', 'devin', runners, [{ kind: 'session', url: 'https://runner.example/s/abc', label: 's' } as never]), 'https://runner.example/s/abc')
assert.equal(runSessionUrl('devin_dry_1', 'devin', runners), null)
assert.equal(runSessionUrl('pending_x', 'devin', runners), null)
const custom = normalizeRunnerSettings({ devin: { sessionUrlTemplate: 'https://example.com/run/{id}' } })
assert.equal(runSessionUrl('abc', 'devin', custom), 'https://example.com/run/abc')
assert.equal(runSessionUrl('abc', 'single-agent', runners), null)
const item = { runId: 'r1', links: [], events: [{ at: 'x', from: 'a', to: 'b', reason: 'r', actor: 'system', meta: { runId: 'r1', runnerId: 'devin' } }] }
assert.equal(sessionUrlFor(item as never, custom), 'https://example.com/run/r1')
const card = toBoardCard({ id: 'w1', projectId: 'p', state: 'implementing', title: 't', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...item } as never, {} as never, Date.now(), null, custom)
assert.equal(card.sessionUrl, 'https://example.com/run/r1')
})
test('resolveAgentRunner: settings runners are event runners; local stubs stay in-process', async () => {
const ev = await resolveAgentRunner('devin')
assert.match(ev!.displayName, /events/)
await patchSettings({ runners: normalizeRunnerSettings({ devin: { mode: 'builtin' } }) } as never)
assert.match((await resolveAgentRunner('devin'))!.displayName, /events/)
assert.equal((await loadSettings()).runners.devin!.mode, 'events')
assert.ok(!/events/.test((await resolveAgentRunner('single-agent'))!.displayName))
assert.equal(await resolveAgentRunner('nope'), undefined)
})
test('events runner emits start/message/cancel requests and reads status from stored sessions', async () => {
const sent: Array<{ topic: string; payload: Record<string, unknown> }> = []
setDispatchForTests(async (i) => { sent.push(i); return { status: 'ok' } })
const r = eventsRunner('devin', 'Devin')
const { runId } = await r.start({ prompt: 'do it', projectId: 'p', workItemId: 'w9', repoRef: 'kody-hq/kody' } as never)
assert.match(runId, /^pending_/)
assert.equal(sent[0]!.topic, '@kody/factory.agent.start.requested')
assert.equal(sent[0]!.payload.runner, 'devin')
assert.equal(sent[0]!.payload.title, 'factory:p:w9')
assert.equal((await r.status(runId)).state, 'queued')
assert.equal(await r.message(runId, 'hi'), false)
assert.equal(await r.message('devin-1', 'hi'), true)
await r.cancel('devin-1')
assert.deepEqual(sent.map((s) => s.topic).slice(1), ['@kody/factory.agent.message.requested', '@kody/factory.agent.cancel.requested'])
setDispatchForTests(null)
})
test('session events from an unknown package are skipped; devin events are stored and logged', async () => {
const skipped = await handleSessionEvent('@kody/devin.session.updated', envelope({ runId: 'devin-1', state: 'running' }, 'someone-else'))
assert.equal(skipped.ok, false)
const res = await handleSessionEvent('@kody/devin.session.updated', envelope({ runId: 'devin-zzz', state: 'running', url: 'https://app.devin.ai/sessions/zzz' }))
assert.equal(res.ok, true)
assert.equal((res as { mode: string }).mode, 'events')
assert.equal((await loadRunnerSession('devin-zzz'))!.state, 'running')
assert.equal(rows.at(-1)!.runId, 'devin-zzz')
assert.equal(rows.at(-1)!.directState, 'not-checked')
})
test('events mode adopts the pending run id when the runner reports session.started', async () => {
const ledger = { version: 1, items: { w1: { id: 'w1', state: 'implementing', runId: 'pending_req1', links: [], events: [], updatedAt: 'x' } } }
const s = toRunnerSession('@kody/devin.session.started', { runId: 'devin-real', state: 'running', url: 'https://app.devin.ai/sessions/devin-real', requestId: 'req1' }, 'devin')!
assert.equal(adoptStartedSession(ledger as never, s), 'w1')
assert.equal(ledger.items.w1.runId, 'devin-real')
assert.equal(sessionUrlFor(ledger.items.w1 as never), 'https://app.devin.ai/sessions/devin-real')
await saveJson(storageKeys.LEDGER_KEY, { version: 1, items: { w2: { id: 'w2', state: 'implementing', runId: 'pending_req2', links: [], events: [], updatedAt: 'x' } } })
await patchSettings({ runners: normalizeRunnerSettings({ devin: { mode: 'events' } }) } as never)
const res = await handleSessionEvent('@kody/devin.session.started', envelope({ runId: 'devin-two', state: 'running', requestId: 'req2' }))
assert.equal((res as { adoptedBy: string }).adoptedBy, 'w2')
const after = await loadJson<{ items: Record<string, { runId: string }> }>(storageKeys.LEDGER_KEY, { items: {} })
assert.equal(after.items.w2!.runId, 'devin-two')
await patchSettings({ runners: defaultRunnerSettings() } as never)
})
test('manifest wires devin session subscriptions, agent request emits, and the report export', async () => {
for (const leaf of ['started', 'updated', 'finished']) {
const sub = pkg.kody.subscriptions[`@kody/devin.session.${leaf}`]
assert.ok(sub, leaf)
await import(new URL(`../../${sub.handler.replace(/^\.\//, '')}`, import.meta.url).href)
}
for (const t of ['start', 'message', 'cancel']) assert.ok(pkg.kody.emits[`@kody/factory.agent.${t}.requested`], t)
assert.equal(pkg.exports['./agent-events/report'], './src/agent-events/report.ts')
})
test('a pending run resolves through the request index once session.started arrives', async () => {
const r = eventsRunner('devin', 'Devin')
assert.equal((await r.status('pending_req77')).state, 'queued')
await handleSessionEvent('@kody/devin.session.started', envelope({ runId: 'devin-77', state: 'running', url: 'https://app.devin.ai/sessions/devin-77', requestId: 'req77' }))
const st = await r.status('pending_req77')
assert.equal(st.state, 'running')
assert.equal(st.runId, 'devin-77')
await handleSessionEvent('@kody/devin.session.finished', envelope({ runId: 'devin-77', state: 'succeeded' }))
assert.equal((await r.status('pending_req77')).state, 'succeeded')
assert.equal((await r.status('devin-77')).runId, undefined)
})