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

entry.ts

780 lines · 36.9 KB · TypeScript
/**
 * Factory app: SPA-style views (overview, work, projects, settings) rendered as
 * a shell that loads data via GET /api/*, plus the no-JS /manage forms.
 * No inline event handlers. GET never writes. Writes: POST /manage, POST /api/create.
 */
import { packageContext } from 'kody:runtime'
import { BADGE_PATH, badgePng } from './badge.ts'
import list from '../exports/list.ts'
import status from '../exports/status.ts'
import {
	addRepoToProject,
	loadProjects,
	setProjectEnabled,
	setRepoEnabled,
	upsertProject,
	deleteProject,
} from '../projects/config.ts'
import { loadSettings, patchSettings } from '../lib/settings.ts'
import { sessionUrlFor } from '../adapters/agent/session-url.ts'
import type { WorkItem } from '../core/work-item.ts'
import { triageWorkItem } from '../core/triage.ts'
import create from '../exports/create.ts'
import { faviconSvg, renderManage, renderShell, type View } from './ui.ts'
import { parseCreateInput } from './create-input.ts'
import { loadBootstrap, projectsPayload, publicSettingsFrom } from './bootstrap.ts'
import sync from '../exports/sync.ts'
import upsertPlan from '../exports/plans/upsert.ts'
import getPlan from '../exports/plans/get.ts'
import moveCard from '../exports/move-card.ts'
import { loadProjectOverview } from './project-detail.ts'
import { loadNotifications, countUnread, markRead, markAllRead, loadRules, saveRules } from '../notifications/store.ts'
import { buildManifest, renderServiceWorker } from './pwa.ts'
import { renderFingerprint, renderFingerprintMissing, renderHealth, fingerprintUrl } from './health-ui.ts'
import { exportConfig } from '../config/export.ts'
import { validateConfigDocument } from '../config/schema.ts'
import { previewImport, applyImport } from '../config/import.ts'
import { listTemplates, getTemplate } from '../config/templates.ts'
import { computeProjectCosts } from '../core/cost-tracking.ts'
import { loadJson, storageKeys } from '../lib/storage.ts'
import { emptyLedger, type Ledger } from '../core/work-item.ts'
import { renderSourcesPage, renderSourceDetail, renderInboxPage, renderSignalDetail, renderSourceMissing, renderSignalMissing } from './signals-ui.ts'
import { listSources, getSource, createSource, updateSource, deleteSourceById } from '../signals/sources/index.ts'
import { listRecords, countRecords, getRecord } from '../signals/records/index.ts'
import { getRoutingConfig, saveRoutingConfig } from '../signals/routing/index.ts'
import { handleInboundSignal } from '../signals/inbound.ts'
import { replaySignal } from '../signals/pipeline.ts'
import { SWITCHES, loadHealthConfig, patchHealthConfig, resolveOrg, type HealthSwitch } from '../health/config.ts'
import { hourBucket } from '../health/fingerprint.ts'
import { recordOutcome, rewake } from '../health/outcome.ts'
import { buildHealthReport, loadHealthFacts, refreshPlatformSnapshot } from '../health/signals.ts'
import { getCounter, getFingerprint, initSchema, listFingerprints, listTimeline, releaseLease } from '../health/store.ts'
import { healthSweep } from '../health/sweep.ts'
import eventsSelfTest from '../exports/events-self-test.ts'
import { handlePushApi } from './push-api.ts'
import { gateRequest } from './access.ts'
import { renderReportsPage, renderReportDetail, renderReportMissing } from './reports-ui.ts'
import { getReport, listReports, loadReports } from '../reports/store.ts'

const CLOUDFLARE_ACCOUNT_ID_RE = /^[a-f0-9]{32}$/

async function publicSettings() {
	return publicSettingsFrom(await loadSettings())
}

function basePath(): string {
	return String(packageContext?.appBasePath ?? '').replace(/\/+$/, '')
}

function htmlPage(html: string, status = 200): Response {
	return new Response(html, {
		status,
		headers: { 'content-type': 'text/html; charset=utf-8' },
	})
}

function redirect(path: string, flash?: string): Response {
	const bp = basePath()
	// Response.redirect() needs an absolute URL; a relative Location is valid for 303.
	const location = `${bp}${path}${flash ? `?flash=${encodeURIComponent(flash)}` : ''}`
	return new Response(null, { status: 303, headers: { Location: location } })
}

async function renderManagePage(flash?: string): Promise<Response> {
	const [projects, settings] = await Promise.all([loadProjects(), loadSettings()])
	return htmlPage(
		renderManage({
			basePath: basePath(),
			projects: Object.values(projects.projects),
			flash,
			modelAccountSet: Boolean(settings.cloudflareAccountId),
		}),
	)
}

/** POST /api/create: JSON only (blocks cross-site form posts). Never starts triage or a sweep. */
async function handleCreate(request: Request): Promise<Response> {
	if (request.method !== 'POST') {
		return Response.json({ ok: false, error: 'Use POST' }, { status: 405, headers: { allow: 'POST' } })
	}
	if (!(request.headers.get('content-type') ?? '').includes('application/json')) {
		return Response.json({ ok: false, error: 'Send JSON' }, { status: 415 })
	}
	let raw: unknown
	try {
		raw = await request.json()
	} catch {
		return Response.json({ ok: false, error: 'Invalid JSON body' }, { status: 400 })
	}
	if (!raw || typeof raw !== 'object') {
		return Response.json({ ok: false, error: 'Invalid JSON body' }, { status: 400 })
	}
	const parsed = parseCreateInput(raw as Record<string, unknown>, await loadProjects())
	if (!parsed.ok) return Response.json({ ok: false, error: parsed.error }, { status: 400 })
	try {
		const result = await create(parsed.input)
		const { item } = result
		return Response.json(
			{ ok: true, replayed: Boolean(result.replayed), item: { id: item.id, title: item.title, state: item.state, projectId: item.projectId } },
			{ status: result.replayed ? 200 : 201 },
		)
	} catch (err) {
		return Response.json(
			{ ok: false, error: err instanceof Error ? err.message : String(err) },
			{ status: 400 },
		)
	}
}

/** POST /api/sync: JSON only. dryRun defaults to true; never starts agents. */
async function handleSync(request: Request): Promise<Response> {
	if (request.method !== 'POST') {
		return Response.json({ ok: false, error: 'Use POST' }, { status: 405, headers: { allow: 'POST' } })
	}
	if (!(request.headers.get('content-type') ?? '').includes('application/json')) {
		return Response.json({ ok: false, error: 'Send JSON' }, { status: 415 })
	}
	const raw = (await request.json().catch(() => null)) as Record<string, unknown> | null
	if (!raw || typeof raw !== 'object') return Response.json({ ok: false, error: 'Invalid JSON body' }, { status: 400 })
	const report = await sync({
		projectId: typeof raw.projectId === 'string' && raw.projectId ? raw.projectId : undefined,
		dryRun: raw.dryRun !== false,
		perRepoLimit: typeof raw.perRepoLimit === 'number' ? raw.perRepoLimit : undefined,
	})
	return Response.json(report, { status: report.setup ? 424 : 200, headers: { 'cache-control': 'no-store' } })
}

async function handleManagePost(request: Request): Promise<Response> {
	const form = await request.formData()
	const action = String(form.get('action') ?? '')
	try {
		if (action === 'upsert-project') {
			const id = String(form.get('id') ?? '').trim()
			const displayName = String(form.get('displayName') ?? id).trim()
			const repoRef = String(form.get('repoRef') ?? '').trim()
			const defaultRunnerId = String(form.get('defaultRunnerId') ?? 'devin')
			const enabled = form.get('enabled') === '1'
			await upsertProject({
				id,
				displayName,
				enabled,
				defaultRunnerId,
				repos: repoRef
					? [
							{
								id: repoRef.replace(/\//g, '__').toLowerCase(),
								repoRef,
								host: 'github',
								enabled: true,
							},
						]
					: [],
			})
			return redirect('/manage', `Saved project ${id}`)
		}
		if (action === 'add-repo') {
			const projectId = String(form.get('projectId') ?? '')
			const repoRef = String(form.get('repoRef') ?? '')
			await addRepoToProject(projectId, { repoRef, host: 'github', enabled: true })
			return redirect('/manage', `Added ${repoRef} to ${projectId}`)
		}
		if (action === 'enable-project' || action === 'disable-project') {
			const projectId = String(form.get('projectId') ?? '')
			const p = await setProjectEnabled(projectId, action === 'enable-project')
			return redirect('/manage', `${p.enabled ? 'Enabled' : 'Disabled'} ${p.displayName}`)
		}
		if (action === 'enable-repo' || action === 'disable-repo') {
			const projectId = String(form.get('projectId') ?? '')
			const repoRef = String(form.get('repoRef') ?? '')
			await setRepoEnabled(projectId, repoRef, action === 'enable-repo')
			return redirect('/manage', `Turned ${action === 'enable-repo' ? 'on' : 'off'} ${repoRef}`)
		}
		if (action === 'set-cloudflare-account') {
			// Narrow setter: only cloudflareAccountId, strict 32-hex format.
			const accountId = String(form.get('cloudflareAccountId') ?? '').trim().toLowerCase()
			if (!CLOUDFLARE_ACCOUNT_ID_RE.test(accountId)) {
				return redirect('/manage', 'Invalid Cloudflare account id (expected 32 hex chars)')
			}
			await patchSettings({ cloudflareAccountId: accountId })
			return redirect('/manage', 'Saved Cloudflare account id')
		}
		if (action === 'smoke-model') {
			// Uses the package's own credential mapping without overriding it.
			// This item must be held for Kent; no external work or ledger writes.
			const now = new Date().toISOString()
			const verdict = await triageWorkItem({
				id: 'credential-smoke', projectId: 'kody', repoRef: 'kody-hq/kody',
				title: 'Credential setup smoke', source: 'manual', needsKent: true,
				body: 'Only hold this setup check for owner review. Do not start any work.',
				priority: null, labels: [], signalIds: [], shadow: true,
				rank: 0, externalId: null, fingerprint: 'credential-smoke',
				planCardId: null, runId: null, events: [],
				 state: 'intake', createdAt: now, updatedAt: now,
			})
			return Response.json({
				modelUsed: verdict.modelUsed,
				decision: verdict.decision,
				reason: verdict.reason,
			})
		}
		if (action === 'delete-project') {
			const projectId = String(form.get('projectId') ?? '')
			const confirmId = String(form.get('confirmId') ?? '')
			if (confirmId !== projectId) {
				return redirect('/manage', 'Delete aborted: confirmation id did not match')
			}
			await deleteProject(projectId, { confirm: true })
			return redirect('/manage', `Deleted ${projectId}`)
		}
		return redirect('/manage', `Unknown action ${action}`)
	} catch (err) {
		return redirect(
			'/manage',
			`Error: ${err instanceof Error ? err.message : String(err)}`,
		)
	}
}

/** POST /signals: form-based CRUD for signal sources and inbox replay. */
async function handleSignalsPost(request: Request): Promise<Response> {
	if (!isSameOriginPost(request)) return new Response('Cross-site form posts are not accepted.', { status: 403, headers: { 'Content-Type': 'text/plain; charset=utf-8' } })
	const form = await request.formData()
	const action = String(form.get('action') ?? '')
	const bp = basePath()
	try {
		if (action === 'create-source') {
			const id = String(form.get('id') ?? '').trim()
			const name = String(form.get('name') ?? '').trim()
			const kind = String(form.get('kind') ?? 'generic-webhook')
			const scopeRaw = String(form.get('projectScope') ?? '')
			const projectScope = scopeRaw ? scopeRaw.split(',').map((s) => s.trim()).filter(Boolean) : []
			const note = String(form.get('note') ?? '').trim()
			const result = await createSource({
				id, name, kind: kind as Parameters<typeof createSource>[0]['kind'],
				projectScope, note,
			})
			return redirect(`/signals/sources/${id}`, `Source created. Signing key (shown once): ${result.signingKey ?? 'none'}`)
		}
		if (action === 'enable-source' || action === 'disable-source') {
			const id = String(form.get('id') ?? '')
			await updateSource({ id, enabled: action === 'enable-source' })
			return redirect('/signals/sources/' + id, `Source ${action === 'enable-source' ? 'enabled' : 'disabled'}`)
		}
		if (action === 'delete-source') {
			const id = String(form.get('id') ?? '')
			const confirmId = String(form.get('confirmId') ?? '')
			if (confirmId !== id) return redirect('/signals/sources', 'Delete cancelled: confirmation did not match')
			await deleteSourceById(id, { confirm: true })
			return redirect('/signals/sources', `Source "${id}" deleted`)
		}
		if (action === 'replay') {
			const signalId = String(form.get('signalId') ?? '')
			const result = await replaySignal(signalId, { dryRun: true })
			const dest = result.record.routingDecision?.destination ?? 'none'
			return redirect(`/signals/inbox/${signalId}`, `Replay (dry run): routed to ${dest} (confidence ${result.record.routingDecision?.confidence?.toFixed(2) ?? '?'})`)
		}
		return redirect('/signals', `Unknown action ${action}`)
	} catch (err) {
		return redirect('/signals', `Error: ${err instanceof Error ? err.message : String(err)}`)
	}
}

const HEALTH_GROUPS = new Set(['open', 'in-flight', 'done', 'all'])

/** GET /factory-health (`/health` stays the JSON liveness probe): signals plus the fingerprint list. Reads package storage only. */
async function renderHealthPage(url: URL, flash?: string): Promise<Response> {
	await initSchema()
	const config = await loadHealthConfig()
	const requested = url.searchParams.get('status') ?? 'open'
	const group = HEALTH_GROUPS.has(requested) ? requested : 'open'
	const query = (url.searchParams.get('q') ?? '').trim().slice(0, 120)
	const [facts, fingerprints, org] = await Promise.all([
		loadHealthFacts(config),
		listFingerprints({ group: group === 'all' ? undefined : group, query, limit: 100 }),
		resolveOrg(config),
	])
	return htmlPage(renderHealth({ basePath: basePath(), report: buildHealthReport(facts), fingerprints, group, query, org, flash }))
}

/** GET /factory-health/fingerprint?id=: one fingerprint with its runs, history, and actions. */
async function renderFingerprintPage(url: URL, flash?: string): Promise<Response> {
	await initSchema()
	const id = url.searchParams.get('id') ?? ''
	const record = id ? await getFingerprint(id) : null
	if (!record) return htmlPage(renderFingerprintMissing(basePath()), 404)
	const [timeline, config, wakesThisHour] = await Promise.all([
		listTimeline(record.fingerprint),
		loadHealthConfig(),
		getCounter(`wakes:${hourBucket()}`),
	])
	return htmlPage(renderFingerprint({ basePath: basePath(), record, timeline, config, wakesThisHour, now: Date.now(), flash }))
}

function redirectTo(location: string, flash: string): Response {
	const sep = location.includes('?') ? '&' : '?'
	return new Response(null, { status: 303, headers: { Location: `${location}${sep}flash=${encodeURIComponent(flash)}` } })
}

/**
 * Health actions change switches and can wake Patch, so a form posted from
 * another site is refused: Sec-Fetch-Site must not be cross-site, and an
 * Origin header, when sent, must be this app's origin.
 */
export function isSameOriginPost(request: Request): boolean {
	const site = (request.headers.get('sec-fetch-site') ?? '').toLowerCase()
	if (site === 'cross-site') return false
	const origin = request.headers.get('origin')
	if (!origin) return true
	const allowed = new Set<string>()
	try {
		allowed.add(new URL(request.url).origin)
	} catch {}
	try {
		allowed.add(new URL(String(packageContext?.hostedUrl ?? '')).origin)
	} catch {}
	return allowed.has(origin)
}

const SWITCH_NAMES: Record<HealthSwitch, string> = { intakeEnabled: 'Error intake', reconcileEnabled: 'Reconcile', wakesEnabled: 'Patch wakes' }

/** POST /factory-health: every health action is a form post that redirects back with a result. */
async function handleHealthPost(request: Request): Promise<Response> {
	if (!isSameOriginPost(request)) return new Response('Cross-site form posts are not accepted.', { status: 403, headers: { 'Content-Type': 'text/plain; charset=utf-8' } })
	const form = await request.formData()
	const action = String(form.get('action') ?? '')
	const home = `${basePath()}/factory-health`
	const fingerprint = String(form.get('fingerprint') ?? '')
	const detail = fingerprint ? fingerprintUrl(basePath(), fingerprint) : home
	try {
		await initSchema()
		if (action === 'set-switch') {
			const name = String(form.get('name') ?? '') as HealthSwitch
			if (!SWITCHES.includes(name)) return redirectTo(home, 'Unknown switch')
			const on = form.get('value') === '1'
			await patchHealthConfig({ [name]: on })
			return redirectTo(home, `${SWITCH_NAMES[name]} turned ${on ? 'on' : 'off'}`)
		}
		if (action === 'sweep') {
			// A reconcile writes Activity triage across the org, so the button obeys the switch.
			if (!(await loadHealthConfig()).reconcileEnabled) return redirectTo(home, 'Reconcile is off. Turn on the Reconcile switch first; nothing was scanned or changed.')
			const result = await healthSweep({ source: 'manual' })
			const r = result.reconcile
			const scanned = r && !('error' in r) ? `Scanned ${r.scanned} open error ${r.scanned === 1 ? 'run' : 'runs'}, ${r.created} new ${r.created === 1 ? 'fingerprint' : 'fingerprints'}` : `Could not read open error runs${r && 'error' in r ? ` (${r.error})` : ''}`
			return redirectTo(home, `${scanned}. ${result.woke ? `Woke Patch for ${result.woke}.` : result.wakes.skipped === 'off' ? 'No wake sent: wakes are off.' : 'No wake sent.'}`)
		}
		if (action === 'refresh-signals') {
			const snapshot = await refreshPlatformSnapshot()
			return redirectTo(home, snapshot.ok ? 'Signals refreshed' : 'Signals refreshed, but some readings were unavailable')
		}
		if (action === 'check-wake') {
			const result = await eventsSelfTest({ note: 'factory health check-wake' })
			return redirectTo(home, result.emitted ? `Dry-run wake request sent to @kody/wake-relay (${result.requestId}). Nothing is posted to any bot; the relay logs a would-deliver.` : `Could not emit the wake request: ${(result as { error?: string }).error ?? (result as { skipped?: string }).skipped ?? 'unknown error'}`)
		}
		if (action === 'release-lease') {
			await releaseLease()
			return redirectTo(home, 'Wake lease released')
		}
		if (action === 'outcome') {
			const result = await recordOutcome({
				fingerprint,
				outcome: String(form.get('outcome') ?? '') as 'fixed',
				summary: String(form.get('summary') ?? ''),
				prUrl: String(form.get('prUrl') ?? ''),
				actor: 'owner',
			})
			if ('skipped' in result) return redirectTo(detail, `Invalid: ${result.error}`)
			return redirectTo(detail, `Marked ${result.outcome}${result.triaged ? `. ${result.triaged} Activity ${result.triaged === 1 ? 'row' : 'rows'} updated.` : ''}`)
		}
		if (action === 'rewake') {
			const result = await rewake(fingerprint, await loadHealthConfig(), 'owner')
			if ('woke' in result) return redirectTo(detail, result.timedOut ? 'Wake sent to Patch. The acknowledgement timed out, so it was not retried.' : 'Wake sent to Patch')
			const why: Record<string, string> = {
				'wakes-off': 'Wakes are off. Turn on Patch wakes first.',
				'hourly-cap': 'No wake sent: the hourly cap is used up.',
				'lease-held': 'No wake sent: another fingerprint holds the wake lease.',
				'already-claimed': 'No wake sent: a wake for this fingerprint is already going out.',
				'unknown-fingerprint': 'Unknown fingerprint',
			}
			const skipped = 'skipped' in result ? result.skipped : ''
			return redirectTo(detail, why[skipped] ?? `Not sent: ${'detail' in result && result.detail ? result.detail : skipped}`)
		}
		return redirectTo(home, `Unknown action ${action}`)
	} catch (err) {
		return redirectTo(detail, `Error: ${err instanceof Error ? err.message : String(err)}`)
	}
}

const VIEWS: Record<string, [View, string]> = {
	'/': ['overview', 'Overview'],
	'/board': ['board', 'Board'],
	'/plans': ['plans', 'Plans'],
	'/work': ['work', 'Work queue'],
	'/projects': ['projects', 'Projects'],
	'/notifications': ['notifications', 'Notifications'],
	'/settings': ['settings', 'Settings'],
}

export default {
	async fetch(request: Request): Promise<Response> {
		const bp = basePath()
		const url = new URL(request.url)
		let path = url.pathname
		if (bp && path.startsWith(bp)) path = path.slice(bp.length) || '/'
		if (!path.startsWith('/')) path = `/${path}`
		const flash = url.searchParams.get('flash') ?? undefined

		// appAccess 'members': only signed-in members of the owning org (see access.ts).
		let access: 'platform' | 'members' = 'members'
		try { access = (await loadSettings()).appAccess } catch {}
		if (access === 'members') {
			const denied = await gateRequest(request, path, `${url.pathname}${url.search}`)
			if (denied) return denied
		}

		if (path === '/favicon.svg' || path === '/favicon.ico') {
			// Conventional URL; the head links <base>/_assets/favicon.svg (kody.app.assets).
			return new Response(faviconSvg(), {
				headers: { 'content-type': 'image/svg+xml; charset=utf-8', 'cache-control': 'public, max-age=86400' },
			})
		}
		if (path === BADGE_PATH) {
			return new Response(badgePng(), {
				headers: { 'content-type': 'image/png', 'cache-control': 'public, max-age=31536000, immutable' },
			})
		}
		if (path === '/apple-touch-icon.png') {
			return new Response(null, { status: 308, headers: { Location: `${bp}/_assets/apple-touch-icon.png` } })
		}
		if (path === '/manifest.webmanifest') {
			return new Response(JSON.stringify(buildManifest(bp)), {
				headers: { 'content-type': 'application/manifest+json; charset=utf-8', 'cache-control': 'no-cache' },
			})
		}
		if (path === '/sw.js') {
			return new Response(renderServiceWorker(), {
				headers: {
					'content-type': 'text/javascript; charset=utf-8',
					'cache-control': 'no-cache',
					'service-worker-allowed': `${bp}/`,
				},
			})
		}
		if (path === '/api/sync') {
			return handleSync(request)
		}
		if (path === '/health') {
			return Response.json({ ok: true, app: 'kody-factory' })
		}
		if (path === '/api/bootstrap') {
			return Response.json(await loadBootstrap(), { headers: { 'cache-control': 'no-store' } })
		}
		if (path === '/api/status') {
			return Response.json(await status())
		}
		if (path === '/api/queue') {
			const projectId = url.searchParams.get('projectId') ?? undefined
			const includeTerminal = url.searchParams.get('includeTerminal') === '1'
			const listed = await list({ projectId, limit: 100, includeTerminal })
			const runners = (await loadSettings()).runners
			const items = (listed as { items?: WorkItem[] }).items
			return Response.json(Array.isArray(items) ? { ...listed, items: items.map((i) => ({ ...i, sessionUrl: sessionUrlFor(i, runners) })) } : listed)
		}
		if (path === '/api/create') {
			return handleCreate(request)
		}
		// --- Reports (audits and reviews; read-only pages) ---
		if (path === '/reports' || path === '/reports/') {
			const sourceFilter = (url.searchParams.get('source') ?? '').slice(0, 60)
			const show = url.searchParams.get('show')
			const showFilter = show === 'noteworthy' || show === 'quiet' ? show : ''
			const [listed, all] = await Promise.all([
				listReports({ source: sourceFilter || undefined, noteworthy: showFilter ? showFilter === 'noteworthy' : undefined, limit: 100 }),
				loadReports(),
			])
			const sources = [...new Set(Object.values(all.reports).map((r) => r.source))].sort()
			return htmlPage(renderReportsPage({ basePath: bp, reports: listed.reports, total: listed.total, sources, sourceFilter, showFilter }))
		}
		const reportRoute = /^\/reports\/(rp_[a-z0-9]{16})\/?$/.exec(path)
		if (reportRoute) {
			const report = await getReport(reportRoute[1]!)
			if (!report) return htmlPage(renderReportMissing(bp), 404)
			const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
			const cardStates = Object.fromEntries(report.cards.map((c) => [c.cardId, ledger.items[c.cardId] ? { state: ledger.items[c.cardId]!.state, needsKent: ledger.items[c.cardId]!.needsKent } : undefined]))
			return htmlPage(renderReportDetail({ basePath: bp, report, cardStates }))
		}
		if (path === '/api/reports') {
			const listed = await listReports({ source: url.searchParams.get('source') ?? undefined, limit: 50 })
			return Response.json(listed, { headers: { 'cache-control': 'no-store' } })
		}
		const reportApi = /^\/api\/reports\/(rp_[a-z0-9]{16})$/.exec(path)
		if (reportApi) {
			const report = await getReport(reportApi[1]!)
			if (!report) return Response.json({ error: 'report not found' }, { status: 404 })
			return Response.json({ report }, { headers: { 'cache-control': 'no-store' } })
		}
		// --- End reports ---
		// Deep link to one card (push notifications, agent reports, and PR references link here).
		// `/c/<id>` is the short canonical form; `/cards/<id>` keeps working.
		const cardRoute = /^\/(?:c|cards)\/([^/]{1,200})\/?$/.exec(path)
		if (cardRoute) {
			return new Response(null, { status: 302, headers: { Location: `${bp}/work?card=${encodeURIComponent(decodeURIComponent(cardRoute[1]!))}`, 'cache-control': 'no-store' } })
		}
		const cardApi = /^\/api\/cards\/([^/]{1,200})$/.exec(path)
		if (cardApi) {
			const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
			const item = ledger.items[decodeURIComponent(cardApi[1]!)]
			if (!item) return Response.json({ error: 'card not found' }, { status: 404 })
			const runners = (await loadSettings()).runners
			return Response.json({ item: { ...item, sessionUrl: sessionUrlFor(item, runners) } }, { headers: { 'cache-control': 'no-store' } })
		}
		if (path.startsWith('/api/push')) {
			if (request.method !== 'GET' && !isSameOriginPost(request)) return Response.json({ error: 'Cross-site not accepted' }, { status: 403 })
			const pushed = await handlePushApi(path, request)
			if (pushed) return pushed
		}
		if (path === '/api/settings') {
			return Response.json(await publicSettings())
		}
		if (path === '/api/projects') {
			return Response.json(projectsPayload(await loadProjects()))
		}
		if (path === '/api/notifications') {
			try {
				const projectId = url.searchParams.get('project') ?? undefined
				const severity = url.searchParams.get('severity') ?? undefined
				const category = url.searchParams.get('category') ?? undefined
				const statusFilter = url.searchParams.get('status') ?? undefined
				let notifications = await loadNotifications()
				if (projectId) notifications = notifications.filter((n) => n.projectId === projectId)
				if (severity) notifications = notifications.filter((n) => n.severity === severity)
				if (category) notifications = notifications.filter((n) => n.category === category)
				if (statusFilter) notifications = notifications.filter((n) => n.status === statusFilter)
				const unread = await countUnread()
				return Response.json({ notifications: notifications.slice(0, 100), unread }, { headers: { 'cache-control': 'no-store' } })
			} catch (err) {
				return Response.json({ notifications: [], unread: 0, error: err instanceof Error ? err.message : String(err) })
			}
		}
		if (path === '/api/notifications/mark-read') {
			if (request.method !== 'POST') return Response.json({ error: 'Use POST' }, { status: 405 })
			if (!isSameOriginPost(request)) return Response.json({ error: 'Cross-site not accepted' }, { status: 403 })
			try {
				const raw = await request.json() as Record<string, unknown>
				if (raw.all) {
					const count = await markAllRead(typeof raw.projectId === 'string' ? raw.projectId : undefined)
					return Response.json({ marked: count })
				}
				const ids = Array.isArray(raw.ids) ? raw.ids.filter((id): id is string => typeof id === 'string') : []
				const count = await markRead(ids)
				return Response.json({ marked: count })
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 400 })
			}
		}
		if (path === '/api/notifications/rules') {
			if (request.method === 'GET') {
				return Response.json(await loadRules(), { headers: { 'cache-control': 'no-store' } })
			}
			if (request.method === 'POST') {
				if (!isSameOriginPost(request)) return Response.json({ error: 'Cross-site not accepted' }, { status: 403 })
				try {
					const raw = await request.json()
					await saveRules(raw as import('../notifications/types.ts').NotificationRules)
					return Response.json({ ok: true })
				} catch (err) {
					return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 400 })
				}
			}
		}
		if (path === '/api/plans/get') {
			const id = url.searchParams.get('id') ?? ''
			if (!id) return Response.json({ error: 'id is required' }, { status: 400 })
			try {
				const result = await getPlan({ id })
				if (!result.found) return Response.json({ error: 'not found' }, { status: 404 })
				return Response.json(result, { headers: { 'cache-control': 'no-store' } })
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 })
			}
		}
		if (path === '/api/plans/upsert') {
			if (request.method !== 'POST') return Response.json({ error: 'Use POST' }, { status: 405 })
			if (!isSameOriginPost(request)) return Response.json({ error: 'Cross-site not accepted' }, { status: 403 })
			if (!(request.headers.get('content-type') ?? '').includes('application/json')) return Response.json({ error: 'Send JSON' }, { status: 415 })
			try {
				const raw = await request.json() as Record<string, unknown>
				const result = await upsertPlan({ ...raw, dryRun: false } as Parameters<typeof upsertPlan>[0])
				return Response.json(result, { status: result.created ? 201 : 200 })
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 400 })
			}
		}
		if (path === '/api/move-card') {
			if (request.method !== 'POST') return Response.json({ error: 'Use POST' }, { status: 405 })
			if (!isSameOriginPost(request)) return Response.json({ error: 'Cross-site not accepted' }, { status: 403 })
			if (!(request.headers.get('content-type') ?? '').includes('application/json')) return Response.json({ error: 'Send JSON' }, { status: 415 })
			try {
				const raw = await request.json() as Record<string, unknown>
				const result = await moveCard({ ...raw, dryRun: false } as Parameters<typeof moveCard>[0])
				return Response.json(result)
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 400 })
			}
		}
		if (path === '/factory-health') {
			if (request.method === 'POST') return handleHealthPost(request)
			return renderHealthPage(url, flash)
		}
		if (path === '/factory-health/fingerprint') {
			return renderFingerprintPage(url, flash)
		}
		if (path === '/manage') {
			if (request.method === 'POST') return handleManagePost(request)
			return renderManagePage(flash)
		}
		if (path === '/api/config/export') {
			try {
				const doc = await exportConfig()
				return Response.json(doc, { headers: { 'cache-control': 'no-store' } })
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 })
			}
		}
		if (path === '/api/config/import') {
			if (request.method !== 'POST') return Response.json({ error: 'Use POST' }, { status: 405 })
			if (!isSameOriginPost(request)) return Response.json({ error: 'Cross-site not accepted' }, { status: 403 })
			if (!(request.headers.get('content-type') ?? '').includes('application/json')) return Response.json({ error: 'Send JSON' }, { status: 415 })
			try {
				const body = await request.json() as Record<string, unknown>
				const doc = body.doc ?? body
				if (body.apply === true) {
					const validation = validateConfigDocument(doc)
					if (!validation.valid) return Response.json({ applied: false, errors: validation.errors }, { status: 400 })
					const result = await applyImport(validation.doc, { removeExtraProjects: body.removeExtraProjects === true })
					return Response.json(result)
				}
				const preview = await previewImport(doc)
				if (!preview.valid) return Response.json(preview, { status: 400 })
				return Response.json(preview)
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 400 })
			}
		}
		if (path === '/api/config/templates') {
			return Response.json({ templates: listTemplates() }, { headers: { 'cache-control': 'no-store' } })
		}
		if (path === '/api/config/templates/apply') {
			if (request.method !== 'POST') return Response.json({ error: 'Use POST' }, { status: 405 })
			if (!isSameOriginPost(request)) return Response.json({ error: 'Cross-site not accepted' }, { status: 403 })
			if (!(request.headers.get('content-type') ?? '').includes('application/json')) return Response.json({ error: 'Send JSON' }, { status: 415 })
			try {
				const body = await request.json() as Record<string, unknown>
				const templateId = String(body.templateId ?? '')
				const template = getTemplate(templateId)
				if (!template) return Response.json({ error: 'Unknown template: ' + templateId }, { status: 404 })
				const doc = { ...template.doc, exportedAt: new Date().toISOString() }
				if (body.apply === true) {
					const result = await applyImport(doc)
					return Response.json({ ...result, templateId })
				}
				const preview = await previewImport(doc)
				return Response.json({ ...preview, templateId, template: { name: template.name, description: template.description } })
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 400 })
			}
		}
		const costApiMatch = /^\/api\/projects\/([^/]+)\/costs$/.exec(path)
		if (costApiMatch) {
			const id = decodeURIComponent(costApiMatch[1]!)
			try {
				const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
				const items = Object.values(ledger.items)
				const costs = computeProjectCosts(items, id)
				return Response.json(costs, { headers: { 'cache-control': 'no-store' } })
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 })
			}
		}
		// --- Signals routes ---
		const inboundMatch = /^\/signals\/in\/([a-z][a-z0-9_-]{1,62})$/.exec(path)
		if (inboundMatch) {
			return handleInboundSignal(request, inboundMatch[1]!)
		}
		if (path === '/signals' || path === '/signals/sources') {
			if (request.method === 'POST') return handleSignalsPost(request)
			const sources = await listSources()
			return htmlPage(renderSourcesPage({ basePath: bp, sources, flash }))
		}
		const sourceDetailMatch = /^\/signals\/sources\/([a-z][a-z0-9_-]{1,62})$/.exec(path)
		if (sourceDetailMatch) {
			const id = sourceDetailMatch[1]!
			const source = await getSource(id)
			if (!source) return htmlPage(renderSourceMissing(bp), 404)
			const recordCount = await countRecords({ sourceId: id })
			const routingConfig = await getRoutingConfig(source.projectScope[0] ?? 'default')
			return htmlPage(renderSourceDetail({ basePath: bp, source, recordCount, routingConfig, flash }))
		}
		if (path === '/signals/inbox') {
			const sourceFilter = url.searchParams.get('source') ?? ''
			const statusFilter = url.searchParams.get('status') ?? ''
			const projectFilter = url.searchParams.get('project') ?? ''
			const records = await listRecords({
				sourceId: sourceFilter || undefined,
				status: (statusFilter || undefined) as import('../signals/records/types.ts').SignalStatus | undefined,
				projectId: projectFilter || undefined,
				limit: 50,
			})
			const total = await countRecords({
				sourceId: sourceFilter || undefined,
				status: (statusFilter || undefined) as import('../signals/records/types.ts').SignalStatus | undefined,
				projectId: projectFilter || undefined,
			})
			return htmlPage(renderInboxPage({ basePath: bp, records, sourceFilter, statusFilter, projectFilter, total, flash }))
		}
		const signalDetailMatch = /^\/signals\/inbox\/([a-z0-9_]+)$/.exec(path)
		if (signalDetailMatch) {
			const record = await getRecord(signalDetailMatch[1]!)
			if (!record) return htmlPage(renderSignalMissing(bp), 404)
			return htmlPage(renderSignalDetail({ basePath: bp, record, flash }))
		}
		if (path === '/api/signals/sources') {
			const sources = await listSources()
			return Response.json(sources, { headers: { 'cache-control': 'no-store' } })
		}
		if (path === '/api/signals/records') {
			const sourceId = url.searchParams.get('source') ?? undefined
			const statusParam = url.searchParams.get('status') ?? undefined
			const projectId = url.searchParams.get('project') ?? undefined
			const records = await listRecords({ sourceId, status: statusParam as import('../signals/records/types.ts').SignalStatus | undefined, projectId, limit: 50 })
			return Response.json(records, { headers: { 'cache-control': 'no-store' } })
		}
		// --- End signals routes ---

		const projectApiMatch = /^\/api\/projects\/([^/]+)\/overview$/.exec(path)
		if (projectApiMatch) {
			const id = decodeURIComponent(projectApiMatch[1]!)
			try {
				const overview = await loadProjectOverview(id)
				if (!overview) return Response.json({ error: 'project not found' }, { status: 404 })
				return Response.json(overview, { headers: { 'cache-control': 'no-store' } })
			} catch (err) {
				return Response.json({ error: err instanceof Error ? err.message : String(err) }, { status: 500 })
			}
		}
		const projectMatch = /^\/projects\/([^/]+)\/?$/.exec(path)
		if (projectMatch) {
			return htmlPage(renderShell({ basePath: bp, view: 'project-detail', title: 'Project' }))
		}
		const legacyProjectMatch = /^\/project\/([^/]+)\/?$/.exec(path)
		if (legacyProjectMatch) {
			const id = decodeURIComponent(legacyProjectMatch[1]!)
			return new Response(null, { status: 303, headers: { Location: `${bp}/projects/${encodeURIComponent(id)}` } })
		}
		const view = VIEWS[path.replace(/\/+$/, '') || '/']
		if (view) {
			// Shell only: data loads client-side via GET /api/*.
			return htmlPage(renderShell({ basePath: bp, view: view[0], title: view[1] }))
		}
		return new Response('Not found', { status: 404 })
	},
}