Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/good-job/ui.ts

Raw
import {
	DynamicBorder,
	type ExtensionContext,
	getMarkdownTheme,
	type Theme,
} from "@earendil-works/pi-coding-agent";
import {
	Container,
	type Focusable,
	Input,
	Markdown,
	matchesKey,
	Text,
	truncateToWidth,
} from "@earendil-works/pi-tui";
import {
	type GoodJobRecord,
	REMEDIATION_STATUSES,
	type Remediation,
} from "./core.js";
import { type GoodJobCounts, isRemediationDate } from "./storage.js";

function oneLine(text: string, maximum = 100): string {
	const compact = text.replace(/\s+/g, " ").trim();
	return Array.from(compact).length > maximum
		? `${Array.from(compact)
				.slice(0, maximum - 1)
				.join("")}…`
		: compact;
}

function dateLabel(timestamp: string): string {
	const date = new Date(timestamp);
	return Number.isNaN(date.valueOf())
		? "unknown date"
		: date.toISOString().slice(0, 10);
}

function projectLabel(record: GoodJobRecord): string {
	if (record.source.type === "import") return record.source.importer;
	const normalized = record.source.cwd.replaceAll("\\", "/").replace(/\/$/, "");
	return normalized.split("/").at(-1) || record.source.cwd;
}

function markdownText(text: string): string {
	return text.replace(/^([#>*+-])\s/gm, "\\$1 ");
}

function formatRemediationMarkdown(remediation: Remediation): string {
	return [
		"## Remediation",
		`Status: ${remediation.status}`,
		`Change: ${markdownText(remediation.changeRef)}`,
		...(remediation.appliedAt ? [`Applied: ${remediation.appliedAt}`] : []),
		...(remediation.verifiedAt
			? [
					`Verified: ${remediation.verifiedAt}`,
					markdownText(remediation.evidence),
				]
			: []),
		`Updated: ${remediation.updatedAt}`,
	].join("\n\n");
}

export function formatLearningMarkdown(
	record: GoodJobRecord,
	remediation?: Remediation,
): string {
	const evidence = record.learning.evidence
		.map((item) => `- ${markdownText(item)}`)
		.join("\n");
	const behaviors = record.learning.behaviors
		.map((item) => `- ${markdownText(item)}`)
		.join("\n");
	const rule = record.learning.candidateRule
		? markdownText(record.learning.candidateRule)
		: "No durable rule proposed.";
	const sourceModel =
		record.source.type === "session" && record.source.agentModel
			? `${record.source.agentModel.provider}/${record.source.agentModel.id}`
			: record.source.type === "import"
				? record.source.importer
				: "unknown agent model";
	return [
		`## ${markdownText(record.learning.slug)}`,
		markdownText(record.learning.summary),
		"",
		"## Feedback",
		markdownText(record.feedback),
		"",
		"## Evidence",
		evidence,
		"",
		"## Behaviors",
		behaviors,
		"",
		"## Candidate rule",
		rule,
		"",
		...(record.kind === "problem" && remediation
			? [formatRemediationMarkdown(remediation), ""]
			: []),
		`*${record.kind} · ${record.id} · ${dateLabel(record.completedAt)} · ${markdownText(projectLabel(record))} · ${markdownText(sourceModel)}*`,
	].join("\n");
}

function remediationLabel(
	record: GoodJobRecord,
	remediations: ReadonlyMap<string, Remediation>,
): string {
	return record.kind === "problem"
		? (remediations.get(record.id)?.status ?? "needs remediation")
		: "";
}

function needsRemediation(
	record: GoodJobRecord,
	remediations: ReadonlyMap<string, Remediation>,
): boolean {
	const status = remediations.get(record.id)?.status;
	return (
		record.kind === "problem" && status !== "applied" && status !== "verified"
	);
}

function prioritizedRecords(
	records: readonly GoodJobRecord[],
	remediations: ReadonlyMap<string, Remediation>,
): GoodJobRecord[] {
	return [...records].sort(
		(a, b) =>
			Number(needsRemediation(b, remediations)) -
				Number(needsRemediation(a, remediations)) ||
			b.completedAt.localeCompare(a.completedAt),
	);
}

function matchingRecords(
	records: readonly GoodJobRecord[],
	query: string,
	remediations: ReadonlyMap<string, Remediation>,
): GoodJobRecord[] {
	const words = query.toLowerCase().trim().split(/\s+/).filter(Boolean);
	if (words.length === 0) return [...records];
	return records.filter((record) => {
		const haystack = [
			record.kind,
			remediationLabel(record, remediations),
			record.learning.slug,
			record.feedback,
			record.learning.summary,
			record.learning.candidateRule ?? "",
			...record.learning.behaviors,
			projectLabel(record),
			record.id,
		]
			.join(" ")
			.toLowerCase();
		return words.every((word) => haystack.includes(word));
	});
}

export class LearningListComponent implements Focusable {
	private readonly records: readonly GoodJobRecord[];
	private readonly search = new Input();
	private selected = 0;
	private _focused = false;

	constructor(
		private readonly theme: Theme,
		records: readonly GoodJobRecord[],
		private readonly counts: GoodJobCounts,
		private readonly requestRender: () => void,
		private readonly done: (id: string | null) => void,
		private readonly remediations: ReadonlyMap<string, Remediation> = new Map(),
	) {
		this.records = prioritizedRecords(records, remediations);
	}

	get focused(): boolean {
		return this._focused;
	}

	set focused(value: boolean) {
		this._focused = value;
		this.search.focused = value;
	}

	handleInput(data: string): void {
		const matches = matchingRecords(
			this.records,
			this.search.getValue(),
			this.remediations,
		);
		if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
			this.done(null);
			return;
		}
		if (matchesKey(data, "up")) {
			this.selected =
				matches.length === 0
					? 0
					: (this.selected - 1 + matches.length) % matches.length;
			this.requestRender();
			return;
		}
		if (matchesKey(data, "down")) {
			this.selected =
				matches.length === 0 ? 0 : (this.selected + 1) % matches.length;
			this.requestRender();
			return;
		}
		if (matchesKey(data, "enter")) {
			this.done(matches[this.selected]?.id ?? null);
			return;
		}
		const before = this.search.getValue();
		this.search.handleInput(data);
		if (this.search.getValue() !== before) {
			this.selected = 0;
			this.requestRender();
		}
	}

	render(width: number): string[] {
		const safeWidth = Math.max(1, width);
		const matches = matchingRecords(
			this.records,
			this.search.getValue(),
			this.remediations,
		);
		this.selected = Math.min(this.selected, Math.max(0, matches.length - 1));
		const visible = windowed(matches, this.selected, 7);
		const first = matches.indexOf(visible[0] as GoodJobRecord);
		const queue = this.counts.pending + this.counts.processing;
		const unaddressed = this.records.filter((record) =>
			needsRemediation(record, this.remediations),
		).length;
		const status = [
			`${this.records.length} learnings`,
			unaddressed ? `${unaddressed} need remediation` : "",
			queue ? `${queue} queued` : "",
			this.counts.failed ? `${this.counts.failed} failed` : "",
		]
			.filter(Boolean)
			.join(" · ");
		const lines = [
			this.theme.fg("border", "─".repeat(safeWidth)),
			`${this.theme.fg("accent", this.theme.bold("GJ / WTF"))}  ${this.theme.fg(this.counts.failed ? "warning" : "dim", status)}`,
			`search  ${this.search.render(Math.max(1, safeWidth - 8))[0] ?? ""}`,
			"",
		];
		if (visible.length === 0) {
			lines.push(this.theme.fg("warning", "No matching learnings."));
		} else {
			for (const [offset, record] of visible.entries()) {
				const selected = first + offset === this.selected;
				const marker = selected ? "▸" : " ";
				const label = remediationLabel(record, this.remediations);
				const summary = `${marker} ${record.learning.slug} · ${oneLine(record.learning.summary, 100)}`;
				lines.push(
					selected ? this.theme.fg("accent", summary) : summary,
					this.theme.fg(
						"dim",
						`  ${record.id}${label ? ` · ${label}` : ""} · ${dateLabel(record.completedAt)} · ${projectLabel(record)}`,
					),
				);
			}
		}
		lines.push(
			"",
			this.theme.fg(
				"dim",
				"type to filter · ↑↓ navigate · enter show · esc close",
			),
			this.theme.fg("border", "─".repeat(safeWidth)),
		);
		return lines.map((line) => truncateToWidth(line, safeWidth));
	}

	invalidate(): void {
		this.search.invalidate();
	}
}

function windowed<T>(
	items: readonly T[],
	selected: number,
	maximum: number,
): T[] {
	if (items.length <= maximum) return [...items];
	const half = Math.floor(maximum / 2);
	const start = Math.min(
		Math.max(0, selected - half),
		Math.max(0, items.length - maximum),
	);
	return items.slice(start, start + maximum);
}

export async function showLearningList(
	ctx: ExtensionContext,
	records: readonly GoodJobRecord[],
	counts: GoodJobCounts,
	remediations: ReadonlyMap<string, Remediation> = new Map(),
): Promise<string | null> {
	if (ctx.mode !== "tui") {
		const ordered = prioritizedRecords(records, remediations);
		const choices = ordered.map(
			(record) =>
				`${record.id} · ${record.learning.slug}${record.kind === "problem" ? ` · ${remediationLabel(record, remediations)}` : ""}`,
		);
		if (ctx.hasUI) {
			const selected = await ctx.ui.select(
				"GJ / WTF · select a learning",
				choices,
			);
			return selected === undefined
				? null
				: (ordered[choices.indexOf(selected)]?.id ?? null);
		}
		ctx.ui.notify(
			ordered
				.slice(0, 10)
				.map(
					(record) =>
						`${record.id}  ${record.learning.slug}  ${remediationLabel(record, remediations)}  ${oneLine(record.learning.summary)}`,
				)
				.join("\n"),
			"info",
		);
		return null;
	}
	return ctx.ui.custom<string | null>(
		(tui, theme, _keybindings, done) =>
			new LearningListComponent(
				theme,
				records,
				counts,
				() => tui.requestRender(),
				done,
				remediations,
			),
		{ blocked: { kind: "question", message: "Choose a learning" } },
	);
}

export async function editRemediation(
	ctx: ExtensionContext,
	record: GoodJobRecord,
	current?: Remediation,
): Promise<Remediation | undefined> {
	const statuses = [...REMEDIATION_STATUSES];
	if (current)
		statuses.sort(
			(a, b) => Number(b === current.status) - Number(a === current.status),
		);
	const selected = await ctx.ui.select(
		`${record.learning.slug} (${record.id}) · remediation`,
		statuses,
	);
	const status = REMEDIATION_STATUSES.find(
		(candidate) => candidate === selected,
	);
	if (!status) return undefined;
	const readText = async (
		label: string,
		initial: string,
		maximum: number,
	): Promise<string | undefined> => {
		let text = initial;
		for (;;) {
			const input = await ctx.ui.editor(
				`${label} (1–${maximum} characters)`,
				text,
			);
			if (input === undefined) return undefined;
			text = input.trim();
			if (text.length > 0 && text.length <= maximum) return text;
			ctx.ui.notify(
				`Enter 1–${maximum} characters; escape cancels without saving`,
				"warning",
			);
		}
	};
	const changeRef = await readText(
		"Change reference: commit, file/section, URL, or action",
		current?.changeRef ?? "",
		1000,
	);
	if (changeRef === undefined) return undefined;
	const today = new Date().toISOString().slice(0, 10);
	const readDate = async (
		label: string,
		initial: string,
		minimum?: string,
	): Promise<string | undefined> => {
		for (;;) {
			const input = await ctx.ui.input(
				`${label} (YYYY-MM-DD; empty keeps ${initial})`,
				initial,
			);
			if (input === undefined) return undefined;
			const date = input.trim() || initial;
			if (isRemediationDate(date) && (!minimum || date >= minimum)) return date;
			ctx.ui.notify(
				`Enter a valid calendar date: YYYY-MM-DD${minimum ? `, no earlier than ${minimum}` : ""}`,
				"warning",
			);
		}
	};
	let appliedAt: string | null = null;
	let verifiedAt: string | null = null;
	let evidence = "";
	if (status !== "proposed") {
		const date = await readDate("Applied", current?.appliedAt ?? today);
		if (date === undefined) return undefined;
		appliedAt = date;
	}
	if (status === "verified") {
		const date = await readDate(
			"Verified",
			current?.verifiedAt ?? today,
			appliedAt ?? undefined,
		);
		if (date === undefined) return undefined;
		verifiedAt = date;
		const text = await readText(
			"Verification evidence: observed check, outcome, scope",
			current?.evidence ?? "",
			4000,
		);
		if (text === undefined) return undefined;
		evidence = text.trim();
	}
	const remediation: Remediation = {
		version: 1,
		recordId: record.id,
		status,
		changeRef: changeRef.trim(),
		appliedAt,
		verifiedAt,
		evidence,
		updatedAt: new Date().toISOString(),
	};
	return (await ctx.ui.confirm(
		"Save remediation?",
		`${record.learning.slug} (${record.id})\n${formatRemediationMarkdown(remediation)}\nOriginal learning stays unchanged.`,
	))
		? remediation
		: undefined;
}

export async function showLearningDetail(
	ctx: ExtensionContext,
	record: GoodJobRecord,
	remediation?: Remediation,
): Promise<boolean> {
	const markdown = formatLearningMarkdown(record, remediation);
	if (ctx.mode !== "tui") {
		ctx.ui.notify(markdown, "info");
		return (
			record.kind === "problem" &&
			ctx.hasUI &&
			(await ctx.ui.select("Learning actions", ["Remediate", "Close"])) ===
				"Remediate"
		);
	}
	return ctx.ui.custom<boolean>(
		(_tui, theme, _keybindings, done) => {
			const container = new Container();
			const border = () =>
				new DynamicBorder((text: string) => theme.fg("accent", text));
			container.addChild(border());
			container.addChild(
				new Text(theme.fg("accent", theme.bold("GJ / WTF")), 1, 0),
			);
			container.addChild(new Markdown(markdown, 1, 1, getMarkdownTheme()));
			container.addChild(
				new Text(
					theme.fg(
						"dim",
						record.kind === "problem"
							? "r remediate · enter/esc/q close"
							: "enter/esc/q close",
					),
					1,
					0,
				),
			);
			container.addChild(border());
			return {
				render: (width: number) =>
					container.render(width).map((line) => truncateToWidth(line, width)),
				handleInput: (data: string) => {
					if (record.kind === "problem" && matchesKey(data, "r")) {
						done(true);
						return;
					}
					if (
						matchesKey(data, "enter") ||
						matchesKey(data, "escape") ||
						matchesKey(data, "q")
					)
						done(false);
				},
				invalidate: () => container.invalidate(),
			};
		},
		{ blocked: { kind: "question", message: "Review learning" } },
	);
}