repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ultra/result.ts

Raw
File outline
// ultra result formatting: eager because restored session messages render at startup.

import type { PhaseSlotResult, WorkflowResult } from "./engine.ts";

// ---------------------------------------------------------------------------
// Result message formatting
// ---------------------------------------------------------------------------

function record(value: unknown): Record<string, unknown> | undefined {
	return typeof value === "object" && value !== null && !Array.isArray(value)
		? (value as Record<string, unknown>)
		: undefined;
}

function text(value: unknown): string | undefined {
	return typeof value === "string" && value.length > 0 ? value : undefined;
}

function itemLine(value: unknown): string {
	const r = record(value);
	if (!r) return `- ${JSON.stringify(value)}`;
	const title =
		text(r.title) ??
		text(r.summary) ??
		text(r.group) ??
		text(r.name) ??
		text(r.file) ??
		text(r.status) ??
		JSON.stringify(value);
	const file = text(r.file);
	const why = text(r.why) ?? text(r.reason) ?? text(r.detail);
	return `- **${title}**${file && file !== title ? ` — \`${file}\`` : ""}${why ? `\n  ${why}` : ""}`;
}

function resultItems(value: unknown): unknown[] {
	if (Array.isArray(value)) return value;
	return value === undefined || value === null ? [] : [value];
}

interface ReviewReport {
	analysis: string;
	findings: unknown[];
	recommendations: string[];
}

interface ResearchReport {
	answerStatus: string;
	executiveSummary: string;
	analysis: string;
	findings: unknown[];
	contradictions: string[];
	gaps: string[];
	recommendations: string[];
	sources: unknown[];
}

function stringArray(value: unknown): string[] {
	return Array.isArray(value)
		? value.filter(
				(item): item is string => typeof item === "string" && item.length > 0,
			)
		: [];
}

function reviewReport(result: WorkflowResult): ReviewReport | undefined {
	if (result.workflow !== "review") return undefined;
	const items = resultItems(result.result);
	if (items.length !== 1) return undefined;
	const value = record(items[0]);
	const analysis = text(value?.analysis);
	if (!analysis || !Array.isArray(value?.findings)) return undefined;
	const recommendations = Array.isArray(value.recommendations)
		? value.recommendations.filter(
				(recommendation): recommendation is string =>
					typeof recommendation === "string" && recommendation.length > 0,
			)
		: [];
	return { analysis, findings: value.findings, recommendations };
}

function researchReport(result: WorkflowResult): ResearchReport | undefined {
	if (result.workflow !== "research") return undefined;
	const items = resultItems(result.result);
	if (items.length !== 1) return undefined;
	const value = record(items[0]);
	const answerStatus = text(value?.answer_status);
	const executiveSummary = text(value?.executive_summary);
	const analysis = text(value?.analysis);
	if (
		!answerStatus ||
		!executiveSummary ||
		!analysis ||
		!Array.isArray(value?.findings) ||
		!Array.isArray(value.sources)
	)
		return undefined;
	return {
		answerStatus,
		executiveSummary,
		analysis,
		findings: value.findings,
		contradictions: stringArray(value.contradictions),
		gaps: stringArray(value.gaps),
		recommendations: stringArray(value.recommendations),
		sources: value.sources,
	};
}

function researchFindingLine(value: unknown): string {
	const finding = record(value);
	if (!finding) return itemLine(value);
	const claim = text(finding.claim) ?? JSON.stringify(value);
	const evidence = text(finding.evidence);
	const confidence = text(finding.confidence);
	const citations = stringArray(finding.citations);
	return [
		`- **${claim}**${confidence ? ` [${confidence}]` : ""}`,
		...(evidence ? [`  ${evidence}`] : []),
		...(citations.length > 0 ? [`  Sources: ${citations.join(", ")}`] : []),
	].join("\n");
}

function researchSourceLine(value: unknown): string {
	const source = record(value);
	if (!source) return itemLine(value);
	const title = text(source.title) ?? "Untitled source";
	const url = text(source.url);
	const sourceType = text(source.source_type);
	const publishedAt = text(source.published_at);
	const metadata = [sourceType, publishedAt].filter(Boolean).join(" · ");
	return `- **${title}**${metadata ? ` (${metadata})` : ""}${url ? ` — ${url}` : ""}`;
}

function refutedSlots(result: WorkflowResult): PhaseSlotResult[] {
	return Object.values(result.phaseResults)
		.flat()
		.filter((slot) => {
			const v = record(slot.value);
			return slot.ok && v?.real === false;
		});
}

function compactFailureMessage(message: string): string {
	return message.length > 160 ? `${message.slice(0, 159)}…` : message;
}

function dropLines(result: WorkflowResult, expanded: boolean): string[] {
	const lines: string[] = [];
	for (const failures of Object.values(result.phaseFailures)) {
		for (const failure of failures) {
			const message = expanded
				? failure.message
				: compactFailureMessage(failure.message);
			lines.push(`- ${failure.agentId} [${failure.code}]: ${message}`);
			if (!expanded) continue;
			lines.push(
				`  retryable: ${failure.retryable ? "yes" : "no"}`,
				`  attempts: ${failure.attempts}`,
			);
			if (failure.model) lines.push(`  model: ${failure.model}`);
			if (failure.thinkingLevel)
				lines.push(`  thinking: ${failure.thinkingLevel}`);
			if (failure.item !== undefined)
				lines.push(`  item: ${JSON.stringify(failure.item)}`);
			if (failure.transcriptTail)
				lines.push(
					`  transcript tail: ${JSON.stringify(failure.transcriptTail)}`,
				);
		}
	}
	return lines;
}

function usageLine(result: WorkflowResult): string | undefined {
	const usage = result.tokenUsage;
	if (!usage || usage.total === 0) return undefined;
	const cost = usage.cost > 0 ? ` · $${usage.cost.toFixed(4)}` : "";
	return `Usage: ${usage.total} tokens (${usage.input} in, ${usage.output} out)${cost}`;
}

function plural(count: number, singular: string): string {
	return `${count} ${singular}${count === 1 ? "" : "s"}`;
}

function summaryLine(
	result: WorkflowResult,
	finalCount: number,
	refutedCount: number,
	droppedCount: number,
): string {
	const incomplete =
		droppedCount > 0
			? ` Review incomplete: ${plural(droppedCount, "step")} dropped.`
			: "";
	if (result.workflow === "review") {
		const findings =
			finalCount === 0
				? "No verified findings."
				: `${plural(finalCount, "verified finding")}.`;
		const refuted =
			refutedCount > 0
				? ` ${plural(refutedCount, "candidate finding")} refuted.`
				: "";
		return `${findings}${refuted}${incomplete}`;
	}
	return `${plural(finalCount, "final result")}.${incomplete}`;
}

function recommendationLines(
	result: WorkflowResult,
	finalCount: number,
	droppedCount: number,
): string[] {
	if (result.workflow === "review") {
		if (droppedCount > 0)
			return [
				"- Inspect dropped steps and rerun review before relying on the result.",
			];
		if (finalCount > 0)
			return ["- Address verified findings, then rerun review."];
		return [
			"- No code changes recommended from this review.",
			"- Continue normal project validation.",
		];
	}
	if (droppedCount > 0)
		return ["- Inspect dropped steps and rerun the workflow."];
	if (finalCount > 0) return ["- Continue with the final results above."];
	return ["- No follow-up action indicated."];
}

export function formatUltraResultMarkdown(
	result: WorkflowResult,
	expanded = false,
): string {
	const report = reviewReport(result);
	const research = researchReport(result);
	const finalItems =
		report?.findings ?? research?.findings ?? resultItems(result.result);
	const lines = [
		`# ultra ${result.workflow}${result.steered ? " (steered)" : ""}`,
	];
	lines.push("");
	lines.push(
		result.phases
			.map((p) => `${p.id}: ${p.ok}/${p.ran} ok, ${p.dropped} dropped`)
			.join(" · ") || "No phases.",
	);
	const usage = usageLine(result);
	if (usage) lines.push(usage);
	lines.push("");

	const refuted = refutedSlots(result);
	const droppedCount = result.phases.reduce(
		(total, phase) => total + phase.dropped,
		0,
	);
	if (report) lines.push("## Analysis", report.analysis, "");
	else if (research)
		lines.push(
			"## Answer",
			research.executiveSummary,
			`Status: ${research.answerStatus}`,
			"",
			"## Analysis",
			research.analysis,
			"",
		);
	else
		lines.push(
			"## Summary",
			summaryLine(result, finalItems.length, refuted.length, droppedCount),
			"",
		);

	if (finalItems.length > 0) {
		lines.push(
			result.workflow === "review"
				? "## Verified findings"
				: research
					? "## Findings"
					: "## Final results",
			...(research
				? finalItems.map(researchFindingLine)
				: finalItems.map(itemLine)),
			"",
		);
	}

	if (refuted.length > 0) {
		lines.push(
			"## Refuted findings",
			...refuted.map((s) => itemLine(s.value)),
			"",
		);
	}

	if (research?.contradictions.length)
		lines.push(
			"## Contradictions",
			...research.contradictions.map((item) => `- ${item}`),
			"",
		);
	if (research?.gaps.length)
		lines.push(
			"## Research gaps",
			...research.gaps.map((item) => `- ${item}`),
			"",
		);

	const drops = dropLines(result, expanded);
	if (drops.length > 0) lines.push("## Drops", ...drops, "");
	const dynamicExtensions = result.dynamicExtensions ?? [];
	if (dynamicExtensions.length > 0)
		lines.push(
			"## Dynamic extensions",
			...dynamicExtensions.map(
				(extension) =>
					`- **${extension.name}**: ${extension.description}\n  Source: \`${extension.sourcePath}\``,
			),
			"",
		);
	lines.push(
		"## Recommendations",
		...(report?.recommendations.length
			? report.recommendations.map((recommendation) => `- ${recommendation}`)
			: research?.recommendations.length
				? research.recommendations.map(
						(recommendation) => `- ${recommendation}`,
					)
				: recommendationLines(result, finalItems.length, droppedCount)),
		"",
	);
	if (research?.sources.length)
		lines.push("## Sources", ...research.sources.map(researchSourceLine), "");

	if (expanded)
		lines.push(
			"## Raw JSON",
			"```json",
			JSON.stringify(result, null, 2),
			"```",
		);
	return lines.join("\n").trimEnd();
}

export function formatWorkflowResultMessage(result: WorkflowResult): string {
	if (result.workflow === "review" || result.workflow === "research")
		return formatUltraResultMarkdown(result);
	return [
		`ultra workflow "${result.workflow}" result${result.steered ? " (steered)" : ""}:`,
		"```json",
		JSON.stringify(result, null, 2),
		"```",
	].join("\n");
}