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

create.ts

380 lines · 10.2 KB · TypeScript
import githubRequest from 'kody:@kody/github/request'
import { ensureRepoLabel } from './issues.ts'
import { makeMentionSafe } from './mention-safe.ts'
import { routeWake } from '../events/wake-transport.ts'

import {
	buildPatchWakePrompt,
	parseGithubRepo,
	qualifyFriction,
	type FrictionTarget,
} from './qualify.ts'
import {
	buildFrictionBody,
	frictionKindLabels,
	isSameFrictionBody,
	normalizeFrictionKind,
	normalizeFrictionTitle,
	wastefulContextLabel,
	wastefulContextLabelColor,
	wastefulContextLabelDescription,
	type FrictionKind,
} from './shared.ts'

export type { FrictionHost, FrictionTarget } from './qualify.ts'
export type { FrictionKind } from './shared.ts'

export type CreateFrictionIssueInput = {
	title: string
	body?: string
	whatHappened?: string
	whatYouWanted?: string
	howToReproduce?: string
	cost?: string
	/** Short notes on what was already looked at. Not a root cause. */
	preliminaryInvestigation?: string
	/** Optional paths that look relevant; omit when none are known. */
	relevantFiles?: Array<string>
	/**
	 * Optional: `general` (default) or `wasteful-context` (docs, skills, or
	 * comments that waste context or are inaccurate). Adds the
	 * `friction:wasteful-context` label on GitHub.
	 */
	kind?: FrictionKind
	/** Required: which repo and whether it lives on github or kody. */
	target: FrictionTarget
	dryRun?: boolean
}

export type CreateFrictionSkipped = {
	ok: true
	skipped: true
	reason: string
	title: string
	target?: FrictionTarget
}

export type CreateFrictionGithubResult = {
	ok: true
	skipped?: false
	routed?: 'github'
	dryRun?: boolean
	title: string
	body?: string
	labels: string[]
	created: boolean
	wouldReuse?: boolean
	/**
	 * Set when an open same-title issue exists: true when this papercut's body
	 * matches that issue's body exactly (nothing new to add as a comment).
	 */
	sameBodyAsExisting?: boolean
	labeled: boolean
	number?: number
	htmlUrl?: string
	target: FrictionTarget
}

export type CreateFrictionKodyResult = {
	ok: true
	skipped?: false
	routed: 'patch-wake'
	woke: boolean
	title: string
	target: FrictionTarget
	dryRun?: boolean
	timedOut?: boolean
	/** Wake request id handed to @kody/wake-relay. */
	wakeRequestId?: string
	/** Why the wake could not be requested (a wake alert was raised). */
	wakeError?: string
}

export type CreateFrictionIssueResult =
	| CreateFrictionSkipped
	| CreateFrictionGithubResult
	| CreateFrictionKodyResult

type GithubRequestResult = {
	ok?: boolean
	status?: number
	data?: unknown
	text?: string
}

type GithubIssue = {
	number?: number
	title?: string | null
	html_url?: string | null
	body?: string | null
	pull_request?: unknown
	labels?: Array<{ name?: string } | string>
}

function requireOk(result: GithubRequestResult, path: string) {
	if (result?.ok === false || (result.status && result.status >= 400)) {
		throw new Error(
			`GitHub ${path} failed (${result.status}): ${String(result.text || '').slice(0, 200)}`,
		)
	}
	return result.data
}

function issueLabels(issue: GithubIssue) {
	return (issue.labels || []).map((label) =>
		typeof label === 'string' ? label : String(label?.name || ''),
	)
}

function missingLabels(issue: GithubIssue, labels: Array<string>) {
	const have = new Set(issueLabels(issue))
	return labels.filter((label) => !have.has(label))
}

/** Create the kind label on the repo when a filing needs it (general needs none). */
async function ensureKindLabel(owner: string, repo: string, labels: Array<string>) {
	if (!labels.includes(wastefulContextLabel)) return
	await ensureRepoLabel(`${owner}/${repo}`, {
		name: wastefulContextLabel,
		color: wastefulContextLabelColor,
		description: wastefulContextLabelDescription,
	})
}

async function findOpenIssueByTitle(
	owner: string,
	repo: string,
	title: string,
	acceptTitles: Array<string> = [title],
): Promise<GithubIssue | null> {
	const query = `repo:${owner}/${repo} is:issue is:open in:title ${JSON.stringify(title)}`
	const data = requireOk(
		await githubRequest({
			path: `/search/issues?q=${encodeURIComponent(query)}&per_page=10`,
		}),
		'/search/issues',
	) as { items?: Array<GithubIssue> }
	const items = Array.isArray(data?.items) ? data.items : []
	const exact = items.find(
		(issue) =>
			!issue.pull_request &&
			acceptTitles.includes(normalizeFrictionTitle(String(issue.title || ''))),
	)
	return exact ?? null
}

async function ensureLabel(
	owner: string,
	repo: string,
	issue: GithubIssue,
	labels: Array<string>,
) {
	const number = Number(issue.number || 0)
	if (!number) return issue
	const missing = missingLabels(issue, labels)
	if (missing.length === 0) return issue
	await ensureKindLabel(owner, repo, missing)
	requireOk(
		await githubRequest({
			method: 'POST',
			path: `/repos/${owner}/${repo}/issues/${number}/labels`,
			body: { labels: missing },
			confirm: true,
		}),
		`POST /repos/${owner}/${repo}/issues/${number}/labels`,
	)
	return { ...issue, labels: [...(issue.labels || []), ...missing.map((name) => ({ name }))] }
}

async function createGithubFriction(
	input: CreateFrictionIssueInput,
	target: FrictionTarget,
): Promise<CreateFrictionGithubResult | CreateFrictionSkipped> {
	const parsed = parseGithubRepo(target.repo)
	if (!parsed) {
		return {
			ok: true,
			skipped: true,
			reason: 'target.repo must be "owner/repo" for host github',
			title: String(input.title ?? ''),
			target,
		}
	}
	const { owner, name: repo } = parsed
	const labels = frictionKindLabels(normalizeFrictionKind(input?.kind))
	// Public issue: package names go in inline code and credit mentions are
	// dropped before posting. Dedupe still matches titles filed before this pass.
	const rawTitle = normalizeFrictionTitle(input?.title)
	const title = makeMentionSafe(rawTitle)
	const rawBody = buildFrictionBody(input)
	const body = makeMentionSafe(rawBody)
	const sameBody = (existingBody: unknown) =>
		isSameFrictionBody(body, existingBody) || isSameFrictionBody(rawBody, existingBody)

	const existing = await findOpenIssueByTitle(owner, repo, rawTitle, [rawTitle, title])

	if (input?.dryRun === true) {
		if (existing) {
			return {
				ok: true,
				routed: 'github',
				dryRun: true,
				title,
				body,
				labels,
				created: false,
				wouldReuse: true,
				sameBodyAsExisting: sameBody(existing.body),
				labeled: false,
				number: Number(existing.number || 0),
				htmlUrl: String(existing.html_url || ''),
				target,
			}
		}
		return {
			ok: true,
			routed: 'github',
			dryRun: true,
			title,
			body,
			labels,
			created: false,
			wouldReuse: false,
			labeled: false,
			target,
		}
	}

	if (existing) {
		const alreadyLabeled = missingLabels(existing, labels).length === 0
		const labeled = await ensureLabel(owner, repo, existing, labels)
		return {
			ok: true,
			routed: 'github',
			created: false,
			sameBodyAsExisting: sameBody(existing.body),
			labeled: !alreadyLabeled,
			number: Number(labeled.number || 0),
			title,
			htmlUrl: String(labeled.html_url || ''),
			labels,
			target,
		}
	}

	await ensureKindLabel(owner, repo, labels)
	const created = requireOk(
		await githubRequest({
			method: 'POST',
			path: `/repos/${owner}/${repo}/issues`,
			body: {
				title,
				body,
				labels,
			},
			confirm: true,
		}),
		`POST /repos/${owner}/${repo}/issues`,
	) as GithubIssue

	return {
		ok: true,
		routed: 'github',
		created: true,
		labeled: true,
		number: Number(created.number || 0),
		title: String(created.title || title),
		htmlUrl: String(created.html_url || ''),
		labels,
		target,
	}
}

async function wakePatchForPackage(
	input: CreateFrictionIssueInput,
	target: FrictionTarget,
): Promise<CreateFrictionKodyResult> {
	const title = String(input.title ?? '').trim()
	const prompt = buildPatchWakePrompt({
		title,
		target,
		body: input.body,
		whatHappened: input.whatHappened,
		whatYouWanted: input.whatYouWanted,
		howToReproduce: input.howToReproduce,
		cost: input.cost,
		preliminaryInvestigation: input.preliminaryInvestigation,
		relevantFiles: input.relevantFiles,
		kind: normalizeFrictionKind(input.kind) ?? 'general',
	})
	const dryRun = input?.dryRun === true
	// Every wake goes through @kody/wake-relay; a dry run sends nothing.
	const result = dryRun
		? { ok: true, requestId: '' }
		: await routeWake({
				source: 'friction',
				bot: 'patch',
				prompt,
				reason: `friction filed against ${target.repo}: ${title}`,
				ref: `${target.repo}:${title}`,
			})
	const woke = !dryRun && result.ok
	return {
		ok: true,
		routed: 'patch-wake',
		woke,
		title,
		target,
		...(dryRun ? { dryRun: true } : {}),
		...(!dryRun && result.requestId ? { wakeRequestId: result.requestId } : {}),
		...(!dryRun && !result.ok ? { wakeError: (result as { detail?: string }).detail ?? 'wake request failed' } : {}),
	}
}

/**
 * File friction against an explicit target.
 *
 * - `host: 'github'` → GitHub issue labeled `friction` on `target.repo`
 *   (owner/repo), plus `friction:wasteful-context` for that kind (label
 *   created on the repo when missing). Dedupes open same-title issues. Pass
 *   `repo: 'kody-hq/kody'` when the platform repo is the intended target.
 * - `host: 'kody'` → wake Patch through `@kody/wake-relay` (no GitHub issue).
 *
 * Soft-skips (does not throw) when qualify fails  -- session-bound / missing gap
 * / missing preliminaryInvestigation on structured filings.
 *
 * @param input.title - Papercut title
 * @param input.target - Required `{ host, repo }`
 * @param input.preliminaryInvestigation - Short notes on what was already looked at (required unless `body`)
 * @param input.relevantFiles - Optional relevant paths; omit when none known
 * @param input.kind - Optional `general` (default) or `wasteful-context`
 * @param input.dryRun - Preview without posting
 */
export default async function createFrictionIssue(
	input: CreateFrictionIssueInput,
): Promise<CreateFrictionIssueResult> {
	const titleHint = String(input?.title ?? '').trim()
	const qualify = qualifyFriction(input)
	if (!qualify.ok) {
		return {
			ok: true,
			skipped: true,
			reason: qualify.reason,
			title: titleHint
				? normalizeFrictionTitle(titleHint)
				: titleHint,
			...(input?.target ? { target: input.target } : {}),
		}
	}

	const target: FrictionTarget = {
		host: input.target.host,
		repo: String(input.target.repo).trim(),
	}

	if (target.host === 'kody') {
		return wakePatchForPackage(input, target)
	}

	return createGithubFriction(input, target)
}