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

board.test.ts

229 lines · 9.1 KB · TypeScript
import assert from 'node:assert/strict'
import { registerHooks } from 'node:module'
import { test } from 'node:test'

const STUB = `
const store = globalThis.__factoryStore ??= new Map();
globalThis.__factoryWrites ??= { n: 0 };
export const packageStorage = () => ({
  async get(k) { return store.get(k) ?? null },
  async set(k, v) { globalThis.__factoryWrites.n++; store.set(k, JSON.stringify(v)) },
});
export const packageContext = { appBasePath: '/apps/factory/' };
export async function credential() { throw new Error('no credentials in tests') }
export async function credentials() { return [] }
export const kody = {};
export const workflows = null;
`
registerHooks({
	resolve(spec, ctx, next) {
		if (spec === 'kody:runtime') {
			return { url: `data:text/javascript,${encodeURIComponent(STUB)}`, shortCircuit: true }
		}
		return next(spec, ctx)
	},
})

const { categoryFromSource, deriveCategory, CATEGORIES, CATEGORY_LABELS } = await import('./category.ts')
const { buildUnifiedBoard, planToBoardColumn, annotateWorkCard, annotatePlanCard } = await import('./unified.ts')
const { checkWritebackGate, formatStatusComment, writebackLabel } = await import('./writeback.ts')
const { clusterFrictionSignals } = await import('./friction-cluster.ts')

// Category tests
test('categoryFromSource maps github-issues to github-issue', () => {
	assert.equal(categoryFromSource('github-issues'), 'github-issue')
})

test('categoryFromSource maps friction to friction', () => {
	assert.equal(categoryFromSource('friction'), 'friction')
})

test('categoryFromSource maps sentry to sentry', () => {
	assert.equal(categoryFromSource('sentry'), 'sentry')
})

test('categoryFromSource maps discord to discord', () => {
	assert.equal(categoryFromSource('discord'), 'discord')
})

test('categoryFromSource maps ci-failure to cleanup', () => {
	assert.equal(categoryFromSource('ci-failure'), 'cleanup')
})

test('categoryFromSource maps unknown sources to generic', () => {
	assert.equal(categoryFromSource('manual'), 'generic')
	assert.equal(categoryFromSource('email'), 'generic')
	assert.equal(categoryFromSource('something-new'), 'generic')
})

test('deriveCategory prefers label-based category', () => {
	assert.equal(deriveCategory('manual', ['ship-pr']), 'ship-pr')
	assert.equal(deriveCategory('manual', ['cleanup']), 'cleanup')
})

test('deriveCategory falls back to source when no labels match', () => {
	assert.equal(deriveCategory('sentry', ['bug', 'urgent']), 'sentry')
})

test('every category has a label', () => {
	for (const cat of CATEGORIES) {
		assert.ok(CATEGORY_LABELS[cat], `missing label for ${cat}`)
	}
})

// Unified board tests
test('planToBoardColumn maps plan columns to board columns', () => {
	assert.equal(planToBoardColumn('exploring'), 'intake')
	assert.equal(planToBoardColumn('proposed'), 'triaged')
	assert.equal(planToBoardColumn('decided'), 'planned')
	assert.equal(planToBoardColumn('in-progress'), 'running')
	assert.equal(planToBoardColumn('shipped'), 'shipped')
})

test('annotateWorkCard adds category from source', () => {
	const card = annotateWorkCard({
		id: 'w1', kind: 'work', column: 'intake', title: 'test', priority: null,
		projectId: 'p', repoRef: null, source: 'github-issues', prNumber: null, prUrl: null,
		reviewSubstate: null, watchSubstate: null, runId: null, sessionUrl: null,
		claimedBy: null, claimExpiresAt: null, enteredColumnAt: '', ageMs: 0, limitMs: 0,
		stalled: false, stalledBy: 0,
	})
	assert.equal(card.category, 'github-issue')
})

test('annotatePlanCard sets category to plan and maps column', () => {
	const card = annotatePlanCard({
		id: 'p1', kind: 'plan', column: 'exploring', title: 'test plan',
		priority: null, projectId: 'p', linkedWorkCount: 0,
		enteredColumnAt: '', ageMs: 0, limitMs: 0, stalled: false, stalledBy: 0, archived: false,
	})
	assert.equal(card.category, 'plan')
	assert.equal(card.column, 'intake')
})

test('buildUnifiedBoard merges work and plan cards', () => {
	const workColumns = {
		intake: [{ id: 'w1', kind: 'work' as const, column: 'intake' as const, title: 't', priority: null, projectId: 'p', repoRef: null, source: 'manual', prNumber: null, prUrl: null, reviewSubstate: null, watchSubstate: null, runId: null, sessionUrl: null, claimedBy: null, claimExpiresAt: null, enteredColumnAt: '', ageMs: 0, limitMs: 0, stalled: false, stalledBy: 0 }],
		triaged: [], planned: [], running: [], 'in-review': [], 'watching-main': [], shipped: [], 'needs-kent': [], dropped: [],
	}
	const planColumns = {
		exploring: [{ id: 'p1', kind: 'plan' as const, column: 'exploring' as const, title: 'plan', priority: null, projectId: 'p', linkedWorkCount: 0, enteredColumnAt: '', ageMs: 0, limitMs: 0, stalled: false, stalledBy: 0, archived: false }],
		proposed: [], decided: [], 'in-progress': [], shipped: [],
	}
	const unified = buildUnifiedBoard(workColumns, planColumns)
	assert.equal(unified.columns.intake.length, 2)
	assert.ok(unified.columns.intake.some((c) => c.id === 'w1'))
	assert.ok(unified.columns.intake.some((c) => c.id === 'p1'))
	assert.equal(unified.categoryCounts.generic, 1)
	assert.equal(unified.categoryCounts.plan, 1)
})

// Writeback gate tests
test('checkWritebackGate blocks when disabled', () => {
	const result = checkWritebackGate({
		enabled: false,
		pilotScope: { mode: 'all', projectIds: [], repoRefs: [] },
		projectId: 'kody',
		repoRef: 'kody-hq/kody',
	})
	assert.equal(result.allowed, false)
	assert.ok('reason' in result && result.reason.includes('disabled'))
})

test('checkWritebackGate blocks when no repoRef', () => {
	const result = checkWritebackGate({
		enabled: true,
		pilotScope: { mode: 'all', projectIds: [], repoRefs: [] },
		projectId: 'kody',
		repoRef: null,
	})
	assert.equal(result.allowed, false)
	assert.ok('reason' in result && result.reason.includes('repository'))
})

test('checkWritebackGate blocks when outside pilot scope', () => {
	const result = checkWritebackGate({
		enabled: true,
		pilotScope: { mode: 'allowlist', projectIds: ['kody'], repoRefs: ['kody-hq/kody'] },
		projectId: 'other',
		repoRef: 'other-org/other-repo',
	})
	assert.equal(result.allowed, false)
	assert.ok('reason' in result && result.reason.includes('outside'))
})

test('checkWritebackGate allows when enabled and in pilot scope', () => {
	const result = checkWritebackGate({
		enabled: true,
		pilotScope: { mode: 'allowlist', projectIds: ['kody'], repoRefs: ['kody-hq/kody'] },
		projectId: 'kody',
		repoRef: 'kody-hq/kody',
	})
	assert.equal(result.allowed, true)
})

test('checkWritebackGate allows with mode: all', () => {
	const result = checkWritebackGate({
		enabled: true,
		pilotScope: { mode: 'all', projectIds: [], repoRefs: [] },
		projectId: 'any',
		repoRef: 'any/repo',
	})
	assert.equal(result.allowed, true)
})

test('formatStatusComment includes column and marker', () => {
	const item = {
		id: 'wi_test', projectId: 'kody', title: 'test', body: '', state: 'running' as const,
		priority: null, needsKent: false, rank: 0, source: 'github-issues',
		externalId: null, fingerprint: 'f', signalIds: [], labels: [],
		repoRef: 'kody-hq/kody', planCardId: null, runId: null,
		createdAt: '', updatedAt: '', events: [], shadow: false,
	}
	const comment = formatStatusComment(item, 'running')
	assert.ok(comment.includes('Running'))
	assert.ok(comment.includes('wi_test'))
	assert.ok(comment.includes('edited in place'))
})

test('writebackLabel returns labels for key columns', () => {
	assert.equal(writebackLabel('running'), 'factory:building')
	assert.equal(writebackLabel('shipped'), 'factory:shipped')
	assert.equal(writebackLabel('needs-kent'), 'factory:needs-decision')
	assert.equal(writebackLabel('intake'), null)
})

test('issueWritebackEnabled defaults to false', async () => {
	const { loadSettings } = await import('../lib/settings.ts')
	const settings = await loadSettings()
	assert.equal(settings.issueWritebackEnabled, false)
})

// Friction clustering tests
test('clusterFrictionSignals returns empty for no signals', () => {
	const result = clusterFrictionSignals([])
	assert.equal(result.clusters.length, 0)
	assert.equal(result.deferred.length, 0)
})

test('clusterFrictionSignals groups signals by area', () => {
	const signals = [
		{ id: 's1', title: 'Fix UI button alignment', body: 'The button is off', labels: [], number: 1, repoRef: 'o/r', createdAt: '2024-01-01', htmlUrl: '' },
		{ id: 's2', title: 'Fix API endpoint timeout', body: 'The endpoint times out', labels: [], number: 2, repoRef: 'o/r', createdAt: '2024-01-02', htmlUrl: '' },
		{ id: 's3', title: 'React component broken', body: 'Component does not render', labels: [], number: 3, repoRef: 'o/r', createdAt: '2024-01-03', htmlUrl: '' },
	]
	const result = clusterFrictionSignals(signals)
	assert.ok(result.clusters.length >= 1)
	assert.equal(result.method, 'heuristic')
	const total = result.clusters.reduce((s, c) => s + c.signals.length, 0) + result.deferred.length
	assert.equal(total, 3)
})

test('clusterFrictionSignals respects maxGroups', () => {
	const signals = Array.from({ length: 20 }, (_, i) => ({
		id: `s${i}`, title: `Issue ${i}`, body: '', labels: [], number: i + 1,
		repoRef: 'o/r', createdAt: '2024-01-01', htmlUrl: '',
	}))
	const result = clusterFrictionSignals(signals, { maxGroups: 2, maxPerGroup: 5 })
	assert.ok(result.clusters.length <= 2)
})