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

report.ts

267 lines · 10.1 KB · TypeScript
/**
 * Agent completion reports land on the factory card, not in a chat channel.
 *
 * An agent that finishes (or parks, or gets blocked on) a card calls
 * `./cards/report` with the card id or its PR URL and a short summary. The
 * report is appended to the card's activity, can move the card (blocked or
 * failed → needs you; finished → verifying), marks ship-pr's report step done
 * for that PR, and sends a web push whose click opens the card.
 *
 * Shipping still needs a merge attestation (link-pr / record-outcome or the
 * sweep's PR refresh). A report never marks a card shipped on its own.
 */
import { appBaseUrl, cardLink, hostedBaseUrl } from '../lib/links.ts'
import { loadJson, saveJson, storageKeys } from '../lib/storage.ts'
import { emptyLedger, nowIso, withLink, type Ledger, type WorkItem, type WorkItemState } from '../core/work-item.ts'
import { rankOf } from '../core/priority-queue.ts'
import { applyPrLink } from '../exports/link-pr.ts'
import { recordEvent } from '../ship-pr/storage-port.ts'
import { loadRules } from '../notifications/store.ts'
import { resolveRules } from '../notifications/types.ts'
import { sendPush, type PushSendResult } from '../push/send.ts'
import { cardPath } from '../push/notify.ts'

const NAME = 'cards/report'

export const REPORT_OUTCOMES = ['shipped', 'done', 'parked', 'progress', 'blocked', 'failed'] as const
export type ReportOutcome = (typeof REPORT_OUTCOMES)[number]

const OUTCOME_LABEL: Record<ReportOutcome, string> = {
	shipped: 'Shipped',
	done: 'Done',
	parked: 'Parked',
	progress: 'Progress',
	blocked: 'Blocked',
	failed: 'Failed',
}

export type ReportAgent = { kind: string; id?: string; url?: string; name?: string }

export type CardReportInput = {
	/** Factory card (work item) id, e.g. `wi_…`. Optional when `prUrl` is linked to the card. */
	cardId?: string
	/** GitHub PR URL. Finds the card when `cardId` is omitted, and links the PR when the card has none. */
	prUrl?: string
	outcome: ReportOutcome
	/** What happened, in a few sentences. Shown on the card and in the notification. */
	summary: string
	/** Optional human headline of the change. */
	title?: string
	/** Who is reporting. `url` only when real (session or agent page). */
	agent?: ReportAgent
	/** Cursor agent id (`bc-…`), accepted for ship-pr callers. Never fabricate. */
	agentId?: string
	/** Optional extra links (deploys, docs). https only. */
	links?: Array<{ url: string; label?: string } | string>
	/** ship-pr report fields, kept on the card when passed. */
	difficulty?: string
	door?: string
	cleanup?: string
	cleanupNote?: string
	model?: string
	extras?: string[]
	/** ship-pr report status (Shipped / Parked / Blocked); maps to `outcome` when `outcome` is omitted. */
	status?: string
	/** Send the push. Default true; the project's notification rules (`pushEnabled`) still apply. */
	notify?: boolean
	dryRun?: boolean
}

export type CardReport = {
	outcome: ReportOutcome
	summary: string
	title?: string
	agent?: ReportAgent
	prUrl?: string
	links?: Array<{ url: string; label?: string }>
	ship?: Record<string, string | string[]>
}

export type CardReportResult = {
	ok: true
	cardId: string
	cardUrl: string
	from: WorkItemState
	to: WorkItemState
	persisted: boolean
	report: CardReport
	shipPr: 'recorded' | 'skipped'
	push: PushSendResult | { skipped: string }
}

type Deps = { sendPush: typeof sendPush }
let deps: Deps = { sendPush }
export function setCardReportDepsForTests(next: Partial<Deps> | null) {
	deps = next ? { ...deps, ...next } : { sendPush }
}

function str(v: unknown, max: number): string | undefined {
	if (typeof v !== 'string') return undefined
	const t = v.trim()
	return t ? t.slice(0, max) : undefined
}

function httpsUrl(v: unknown): string | undefined {
	const s = str(v, 500)
	if (!s) return undefined
	try {
		const u = new URL(s)
		return u.protocol === 'https:' ? u.toString() : undefined
	} catch {
		return undefined
	}
}

function normalizePrUrl(v: unknown): string | undefined {
	const s = str(v, 300)
	if (!s) return undefined
	const m = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/pull\/(\d+)/.exec(s)
	return m ? `https://github.com/${m[1]}/${m[2]}/pull/${m[3]}` : undefined
}

function outcomeOf(input: CardReportInput): ReportOutcome {
	if (typeof input.outcome === 'string' && (REPORT_OUTCOMES as readonly string[]).includes(input.outcome)) return input.outcome
	const status = String(input.status ?? '').toLowerCase()
	if (status === 'shipped' || status === 'parked' || status === 'blocked') return status
	throw new Error(`${NAME}: outcome must be one of ${REPORT_OUTCOMES.join(', ')}`)
}

/** Absolute short card URL (`<base>/c/<id>`). Pass `await appBaseUrl()` so `publicBaseUrl` applies. */
export function cardUrl(cardId: string, base?: string): string {
	return cardLink(base || hostedBaseUrl(), cardId)
}

function findCard(ledger: Ledger, cardId: string | undefined, prUrl: string | undefined): WorkItem {
	if (cardId) {
		const item = ledger.items[cardId]
		if (!item) throw new Error(`${NAME}: card not found: ${cardId}`)
		return item
	}
	if (!prUrl) throw new Error(`${NAME}: pass cardId, or a prUrl that is linked to a card`)
	const key = prUrl.toLowerCase()
	const matches = Object.values(ledger.items).filter(
		(i) => i.pr?.url?.toLowerCase() === key || (i.links ?? []).some((l) => l.kind === 'pr' && l.url.toLowerCase() === key),
	)
	if (matches.length === 0) throw new Error(`${NAME}: no card is linked to ${prUrl}; pass cardId`)
	matches.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
	return matches[0]!
}

function nextState(state: WorkItemState, outcome: ReportOutcome): WorkItemState {
	if (state === 'shipped' || state === 'dropped') return state
	if (outcome === 'blocked' || outcome === 'failed') return 'needs-kent'
	if ((outcome === 'shipped' || outcome === 'done' || outcome === 'parked') && (state === 'running' || state === 'planned' || state === 'triaged' || state === 'intake')) return 'verifying'
	return state
}

export async function reportOnCard(input: CardReportInput): Promise<CardReportResult> {
	if (!input || typeof input !== 'object') throw new Error(`${NAME}: input is required`)
	const outcome = outcomeOf(input)
	const summary = str(input.summary, 2000)
	if (!summary) throw new Error(`${NAME}: summary is required`)
	const cardId = str(input.cardId, 120)
	const prUrl = normalizePrUrl(input.prUrl)
	if (input.prUrl && !prUrl) throw new Error(`${NAME}: prUrl must be https://github.com/<owner>/<repo>/pull/<n>`)

	const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
	const item = findCard(ledger, cardId, prUrl)

	const agentIn = input.agent && typeof input.agent === 'object' ? input.agent : undefined
	const cursorId = str(input.agentId, 80)
	const agent: ReportAgent | undefined = agentIn
		? {
				kind: str(agentIn.kind, 40) ?? 'other',
				...(str(agentIn.id, 120) ? { id: str(agentIn.id, 120) } : {}),
				...(httpsUrl(agentIn.url) ? { url: httpsUrl(agentIn.url) } : {}),
				...(str(agentIn.name, 80) ? { name: str(agentIn.name, 80) } : {}),
			}
		: cursorId
			? { kind: 'cursor', id: cursorId }
			: undefined
	const links = (Array.isArray(input.links) ? input.links : [])
		.slice(0, 10)
		.map((l) => (typeof l === 'string' ? { url: httpsUrl(l) } : { url: httpsUrl(l?.url), label: str(l?.label, 80) }))
		.filter((l): l is { url: string; label?: string } => !!l.url)
		.map((l) => (l.label ? l : { url: l.url }))
	const ship: Record<string, string | string[]> = {}
	for (const k of ['difficulty', 'door', 'cleanup', 'cleanupNote', 'model', 'status'] as const) {
		const v = str(input[k], 200)
		if (v) ship[k] = v
	}
	if (Array.isArray(input.extras)) {
		const extras = input.extras.filter((e): e is string => typeof e === 'string').map((e) => e.slice(0, 200)).slice(0, 10)
		if (extras.length) ship.extras = extras
	}
	const title = str(input.title, 200)
	const report: CardReport = {
		outcome,
		summary,
		...(title ? { title } : {}),
		...(agent ? { agent } : {}),
		...(prUrl ? { prUrl } : {}),
		...(links.length ? { links } : {}),
		...(Object.keys(ship).length ? { ship } : {}),
	}

	const at = nowIso()
	let next: WorkItem = item
	if (prUrl && !item.pr) {
		try {
			next = applyPrLink(next, { workItemId: item.id, prUrl }, at)
		} catch {
			next = { ...next, links: withLink(next.links, { kind: 'pr', url: prUrl, label: 'PR', reason: 'report', at }) }
		}
	}
	if (agent?.url) next = { ...next, links: withLink(next.links, { kind: 'session', url: agent.url, label: agent.name ?? `${agent.kind} session`, reason: 'report', at }) }
	const to = nextState(item.state, outcome)
	const needsKent = to === 'needs-kent' ? true : next.needsKent
	next = {
		...next,
		state: to,
		needsKent,
		rank: rankOf(next.priority, needsKent),
		updatedAt: at,
		events: [
			...next.events,
			{ at, from: item.state, to, reason: `${OUTCOME_LABEL[outcome]}: ${summary}`, actor: 'agent', meta: { report } },
		],
	}

	const url = cardUrl(item.id, await appBaseUrl())
	if (input.dryRun) {
		return { ok: true, cardId: item.id, cardUrl: url, from: item.state, to, persisted: false, report, shipPr: 'skipped', push: { skipped: 'dry run' } }
	}
	ledger.items[item.id] = next
	await saveJson(storageKeys.LEDGER_KEY, ledger)

	let shipPr: 'recorded' | 'skipped' = 'skipped'
	if (prUrl) {
		const m = /github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)/.exec(prUrl)!
		try {
			await recordEvent(`${m[1]}/${m[2]}#${m[3]}`.toLowerCase(), 'summary_sent', 'card', { status: OUTCOME_LABEL[outcome], cardId: item.id, agentKind: agent?.kind ?? null })
			shipPr = 'recorded'
		} catch {
			shipPr = 'skipped'
		}
	}

	let push: PushSendResult | { skipped: string } = { skipped: 'notify: false' }
	if (input.notify !== false) {
		try {
			const rule = resolveRules(await loadRules(), item.projectId)
			if (!rule.pushEnabled) push = { skipped: 'push is off for this project' }
			else
				push = await deps.sendPush({
					kind: 'report',
					title: `${OUTCOME_LABEL[outcome]}: ${title ?? item.title}`.slice(0, 120),
					body: summary.slice(0, 240),
					path: cardPath(item.id),
					tag: `report-${item.id}`,
					cardId: item.id,
				})
		} catch (error) {
			push = { skipped: error instanceof Error ? error.message.slice(0, 200) : 'push failed' }
		}
	}
	return { ok: true, cardId: item.id, cardUrl: url, from: item.state, to, persisted: true, report, shipPr, push }
}