Skip to content
← 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.

FollowFork

Files

now.test.ts

166 lines · 8.3 KB · TypeScript
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { test } from 'node:test'
import type { StatusNowInput } from './now.ts'
import type { WorkItem } from '../core/work-item.ts'

// kody:runtime stand-in that records every write, so the export test can
// prove the read is side-effect free.
const STUB = `
import { DatabaseSync } from 'node:sqlite';
const g = globalThis.__statusNow ??= { kv: new Map(), writes: [], sqlWrites: [], runs: [], db: new DatabaseSync(':memory:') };
export const packageStorage = () => ({
  async get(k) { return g.kv.get(k) ?? null },
  async set(k, v) { g.writes.push(k); g.kv.set(k, JSON.stringify(v)) },
  async sql(q, p = []) { if (!/^\\s*select/i.test(q)) g.sqlWrites.push(q); const s = g.db.prepare(q); return /^\\s*select/i.test(q) ? { rows: s.all(...p) } : (s.run(...p), { rows: [] }) },
});
export const packageContext = { appBasePath: '/apps/factory', packageId: 'pkg-factory', kodyId: 'kody-factory' };
export const kody = { async runList(input) { return { runs: g.runs.filter((r) => !input.status || r.status === input.status), next_cursor: null } } };
export async function credential() { throw new Error('no credentials in status tests') }
export async function credentials() { return [] }
`
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 { buildStatusNow } = await import('./now.ts')
const { defaultColumnTimeLimits } = await import('../core/board.ts')

const NOW = Date.parse('2026-11-19T18:00:00.000Z')
const H = 60 * 60_000
const iso = (msAgo: number) => new Date(NOW - msAgo).toISOString()

function item(id: string, over: Partial<WorkItem> = {}): WorkItem {
	const state = over.state ?? 'running'
	const at = over.updatedAt ?? iso(H)
	return {
		id, projectId: 'kody', title: `Item ${id}`, body: '', state, priority: 2, needsKent: false, rank: 1,
		source: 'github-issues', externalId: null, fingerprint: id, signalIds: [], labels: [], repoRef: 'kody-hq/kody',
		planCardId: null, runId: null, createdAt: iso(10 * H), updatedAt: at,
		events: [{ at, from: 'planned', to: state, reason: 'test', actor: 'system' }], shadow: false, ...over,
	}
}

function input(over: Partial<StatusNowInput> = {}): StatusNowInput {
	return {
		now: NOW,
		ledger: { version: 1, items: {} },
		settings: { shadowMode: true, maxConcurrentRuns: 1, pilotScope: { mode: 'allowlist', projectIds: ['kody'], repoRefs: ['kody-hq/kody'] }, columnTimeLimits: defaultColumnTimeLimits() } as unknown as StatusNowInput['settings'],
		projects: { projects: { kody: { id: 'kody', defaultRunnerId: 'devin' } } } as unknown as StatusNowInput['projects'],
		planStore: { version: 1, plans: {} },
		claims: { claims: {} },
		runMeta: { runs: {} },
		health: { report: { level: 'ok', summary: 'Healthy', reasons: [] }, switches: { intakeEnabled: true, reconcileEnabled: false, wakesEnabled: false } },
		snapshot: null,
		jobs: { source: 'skipped' },
		...over,
	}
}

test('lists running work with agent, session, age, and last activity', () => {
	const ledger = { version: 1 as const, items: {
		a: item('a', { runId: 'devin-abc', updatedAt: iso(30 * 60_000) }),
		b: item('b', { state: 'dropped' }),
		c: item('c', { state: 'intake', updatedAt: iso(60_000) }),
	} }
	const out = buildStatusNow(input({ ledger, runMeta: { runs: { 'devin-abc': { devinId: 'abc', url: 'https://app.devin.ai/sessions/abc' } } } }))
	assert.equal(out.inProgress.length, 1)
	const a = out.inProgress[0]!
	assert.equal(a.id, 'a')
	assert.equal(a.agent, 'devin')
	assert.equal(a.sessionUrl, 'https://app.devin.ai/sessions/abc')
	assert.equal(a.repoRef, 'kody-hq/kody')
	assert.equal(a.idleMinutes, 30)
	assert.equal(a.stalled, false)
	assert.equal(out.counts.queued, 1)
	assert.match(out.headline, /1 in progress; 1 queued/)
	assert.match(out.headline, /shadow on/)
})

test('flags idle and over-limit work, and stalled plans', () => {
	const ledger = { version: 1 as const, items: {
		idle: item('idle', { updatedAt: iso(3 * H) }),
		old: item('old', { updatedAt: iso(8 * H) }),
	} }
	const planStore = { version: 1 as const, plans: {
		p1: { id: 'p1', title: 'Plan', body: '', status: 'proposed', priority: null, projectId: 'kody', links: [], progressNotes: [], createdAt: iso(40 * 24 * H), updatedAt: iso(40 * 24 * H), statusChangedAt: iso(40 * 24 * H), events: [], archived: false, workItemIds: [] },
	} } as unknown as StatusNowInput['planStore']
	const out = buildStatusNow(input({ ledger, planStore }))
	const idle = out.inProgress.find((i) => i.id === 'idle')!
	assert.deepEqual(idle.stallReasons, ['no activity for 180 min'])
	const old = out.inProgress.find((i) => i.id === 'old')!
	assert.ok(old.stallReasons.includes('over running limit'))
	assert.equal(out.counts.stalledWork, 2)
	assert.equal(out.counts.stalledPlans, 1)
	assert.equal(out.stalled.find((s) => s.kind === 'plan')?.id, 'p1')
})

test('uses an active claim as the agent and honors projectId and limit', () => {
	const ledger = { version: 1 as const, items: {
		a: item('a'),
		b: item('b', { projectId: 'other' }),
		k: item('k', { state: 'needs-kent' }),
	} }
	const claims = { claims: {
		a: { id: 'a', kind: 'work' as const, agent: 'patch', claimedAt: iso(H), expiresAt: iso(-H) },
		b: { id: 'b', kind: 'work' as const, agent: 'old', claimedAt: iso(3 * H), expiresAt: iso(H) },
	} }
	const out = buildStatusNow(input({ ledger, claims, projectId: 'kody', limit: 1 }))
	assert.equal(out.inProgress.length, 1)
	assert.equal(out.inProgress[0]!.agent, 'patch')
	assert.equal(out.counts.needsKent, 1)
	assert.equal(out.claims.length, 1)
})

test('falls back to the stored platform snapshot when live jobs are not read', () => {
	const snapshot = {
		collectedAt: iso(2 * H), ok: true,
		jobs: { ok: true as const, groups: [{ name: 'sweep', total: 4, errors: 0, lastAt: iso(H), lastStatus: 'success', lastError: null }] },
		webhooks: { ok: false as const, error: 'timed out' },
		errorRate: { ok: true as const, total: 0, errors: 0, windowStart: null },
		openErrors: { ok: true as const, count: 0, more: false },
		stuckRuns: { ok: true as const, count: 0, oldestAt: null, names: [] },
	}
	const out = buildStatusNow(input({ snapshot, jobs: { source: 'unavailable', error: 'run list timed out' } }))
	assert.equal(out.jobs.source, 'unavailable')
	assert.ok('lastKnown' in out.jobs)
	assert.equal(out.jobs.lastKnown?.ageMinutes, 120)
	assert.match(out.headline, /jobs not read/)
})

test('reports live running jobs and a health error without throwing', () => {
	const out = buildStatusNow(input({
		health: { error: 'health read failed: no such table' },
		jobs: { source: 'live', readAt: iso(0), running: [{ id: 'r1', surface: 'job', name: 'sweep', status: 'running', startedAt: iso(60_000), ageMs: 60_000 }], recent: [] },
	}))
	assert.equal(out.health.level, 'unknown')
	assert.equal(out.jobs.source, 'live')
	assert.match(out.headline, /1 runs going/)
})

test('export reads storage and run list only, writes nothing', async () => {
	const g = (globalThis as unknown as { __statusNow: { kv: Map<string, string>; writes: string[]; sqlWrites: string[]; runs: unknown[]; db: { exec: (q: string) => void } } }).__statusNow
	const store = await import('../health/store.ts')
	await store.initSchema()
	g.sqlWrites.length = 0
	const now = Date.now()
	const running = item('live', { updatedAt: new Date(now - 10 * 60_000).toISOString(), runId: 'devin-1' })
	running.events = [{ at: running.updatedAt, from: 'planned', to: 'running', reason: 't', actor: 'system' }]
	g.kv.set('factory:ledger:v1', JSON.stringify({ version: 1, items: { live: running } }))
	g.runs = [{ id: 'run1', surface: 'job', name: 'sweep', status: 'running', started_at: new Date(now - 60_000).toISOString(), package_id: 'pkg-factory' }]
	const { default: statusNow } = await import('../exports/status-now.ts')
	const out = await statusNow()
	assert.equal(out.inProgress.length, 1)
	assert.equal(out.inProgress[0]!.agent, 'devin')
	assert.equal(out.jobs.source, 'live')
	assert.ok('running' in out.jobs && out.jobs.running.length === 1)
	assert.notEqual(out.health.level, undefined)
	assert.deepEqual(g.writes, [])
	assert.deepEqual(g.sqlWrites, [])
	const skipped = await statusNow({ jobs: false })
	assert.equal(skipped.jobs.source, 'skipped')
})