Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/the-system/board-runtime.ts

Raw
import path from "node:path";
import {
	defineTool,
	keyHint,
	type ToolDefinition,
	withFileMutationQueue,
} from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
import { Type } from "typebox";
import { BOARD_NOTE_LIMIT, BOARD_PATH } from "./board-constants.ts";
import type { BoardProposal } from "./board-state.ts";
import type { BoardExec, BookServer } from "./book-server.ts";
import {
	loadBoardState,
	loadBookServer,
	loadOpenBrowser,
	loadProjectIndex,
	loadSystemRenderer,
} from "./loaders.js";
import { requireProjectRoot } from "./project-root.ts";
import { expandableFallback } from "./tool-rendering.ts";

const STATES = ["todo", "done", "open", "dropped"] as const;
const proposalParameters = Type.Object({
	items: Type.Array(
		Type.Object({
			id: Type.String({ description: "Existing spec, plan, or issue ID." }),
			state: Type.Enum(STATES, {
				type: "string",
				description: "Proposed board state for the item type.",
			}),
			rationale: Type.String({
				minLength: 1,
				maxLength: 1000,
				description: "Terse evidence supporting this proposed state.",
			}),
		}),
		{ minItems: 0, maxItems: 100 },
	),
});
const updateParameters = Type.Object({
	items: Type.Array(
		Type.Object({
			id: Type.String({ description: "Existing spec, plan, or issue ID." }),
			state: Type.Enum(STATES, {
				type: "string",
				description: "Board state for the item type.",
			}),
			note: Type.String({
				minLength: 1,
				maxLength: BOARD_NOTE_LIMIT,
				description: "Terse verified evidence stored with the board entry.",
			}),
		}),
		{ minItems: 0, maxItems: 100 },
	),
});

interface CallTheme {
	fg(style: string, text: string): string;
	bold(text: string): string;
}

function renderBoardItems(
	name: string,
	args: { items?: unknown },
	theme: CallTheme,
	context: {
		expanded: boolean;
		lastComponent?: unknown;
		keyHint?: typeof keyHint;
	},
): Text {
	const text =
		(context.lastComponent as Text | undefined) ?? new Text("", 0, 0);
	const items = Array.isArray(args.items)
		? (args.items as Record<string, unknown>[])
		: [];
	const count = items.length;
	let output = `${theme.fg("toolTitle", theme.bold(name))} ${theme.fg("toolOutput", `${count} item${count === 1 ? "" : "s"}`)}`;
	if (!context.expanded && count > 0) {
		output += theme.fg(
			"dim",
			` (${(context.keyHint ?? keyHint)("app.tools.expand", "to expand")})`,
		);
	} else {
		for (const item of items) {
			output += `\n${theme.fg("accent", String(item["state"]).toUpperCase())} ${theme.fg("toolOutput", String(item["id"]))}`;
			const evidence = item["rationale"] ?? item["note"];
			if (evidence) output += `\n${theme.fg("dim", String(evidence))}`;
		}
	}
	text.setText(output);
	return text;
}

const renderBoardToolResult = (
	result: Readonly<{
		content: Parameters<typeof expandableFallback>[0];
		details?: unknown;
	}>,
	expanded: boolean,
	theme: CallTheme,
	isError: boolean,
	lastComponent: unknown,
	messages: Readonly<{ empty: string; summary: (count: number) => string }>,
	hint?: typeof keyHint,
): Text => {
	const text = (lastComponent as Text | undefined) ?? new Text("", 0, 0);
	const items = (result.details as { items?: BoardProposal[] } | undefined)
		?.items;
	if (!items) {
		text.setText(
			expandableFallback(
				result.content,
				expanded,
				theme,
				isError ? "error" : "muted",
				hint,
			),
		);
		return text;
	}
	text.setText(
		theme.fg(
			"success",
			items.length === 0 ? messages.empty : messages.summary(items.length),
		),
	);
	return text;
};

export interface BoardRuntime {
	tool: ToolDefinition;
	updateTool: ToolDefinition;
	open(cwd: string, onExec?: BoardExec, page?: string): Promise<string>;
	shutdown(): void;
}

export function createBoardRuntime(): BoardRuntime {
	const proposals = new Map<string, Map<string, BoardProposal>>();
	const servers = new Map<string, Promise<BookServer>>();
	let generation = 0;
	const executors = new Map<string, BoardExec>();
	const loadBoard = async (cwd: string) => {
		const root = requireProjectRoot(cwd);
		const [projectIndex, boardState] = await Promise.all([
			loadProjectIndex(),
			loadBoardState(),
		]);
		const index = projectIndex.loadProjectIndex(root);
		const state = boardState.readBoardState(root, index.prefix);
		return { boardState, index, root, state };
	};
	const tool = defineTool({
		name: "system_board_propose",
		annotations: { readOnlyHint: false },
		exposure: "deferred",
		label: "system_board_propose",
		description:
			"Propose board state changes for review; no direct .system/board.json write.",
		promptSnippet: "Propose System board states for human review",
		promptGuidelines: [
			"During /system assess, call system_board_propose exactly once with evidence-backed state changes; use an empty items list when no changes are justified.",
		],
		parameters: proposalParameters,
		renderCall(args, theme, context) {
			return renderBoardItems("system_board_propose", args, theme, context);
		},
		renderResult(result, { expanded }, theme, context) {
			return renderBoardToolResult(
				result,
				expanded,
				theme,
				Boolean(context.isError),
				context.lastComponent,
				{
					empty: "✓ no changes proposed",
					summary: (count) =>
						`✓ ${count} change${count === 1 ? "" : "s"} proposed`,
				},
				context.keyHint ?? keyHint,
			);
		},
		async execute(_toolCallId, params, signal, _onUpdate, ctx) {
			const root = requireProjectRoot(ctx.cwd);
			return withFileMutationQueue(path.resolve(root, BOARD_PATH), async () => {
				if (signal?.aborted) throw new Error("Board proposal cancelled");
				const { boardState, index } = await loadBoard(root);
				if (signal?.aborted) throw new Error("Board proposal cancelled");
				const byId = new Map(
					index.documents.map((document) => [document.metadata.id, document]),
				);
				const proposed = new Map<string, BoardProposal>();
				for (const raw of params.items) {
					const document = byId.get(raw.id);
					if (!document) throw new Error(`No System board item: ${raw.id}`);
					const valid = boardState.isValidBoardState(
						document.metadata.type,
						raw.state,
					);
					if (!valid)
						throw new Error(
							`Invalid ${document.metadata.type} board state ${raw.state}: ${raw.id}`,
						);
					proposed.set(raw.id, {
						id: raw.id,
						state: raw.state,
						rationale: raw.rationale.trim(),
					});
				}
				const current = proposals.get(root) ?? new Map();
				current.clear();
				for (const [id, proposal] of proposed) current.set(id, proposal);
				proposals.set(root, current);
				const items = [...proposed.values()].sort((left, right) =>
					left.id.localeCompare(right.id),
				);
				return {
					content: [
						{
							type: "text" as const,
							text: `${params.items.length} board state proposal(s) recorded for human review. Run /system board to inspect and apply them.`,
						},
					],
					details: { items },
				};
			});
		},
	});

	const updateTool = defineTool({
		name: "system_board_update",
		annotations: { readOnlyHint: false },
		exposure: "deferred",
		label: "system_board_update",
		description:
			"Apply verified board states to .system/board.json as agent; reject invalid states.",
		promptSnippet: "Update System board states from verified work",
		promptGuidelines: [
			"After fresh verification in /system exec, call system_board_update exactly once with the states your work proves; use an empty items list when no change is justified.",
		],
		parameters: updateParameters,
		renderCall(args, theme, context) {
			return renderBoardItems("system_board_update", args, theme, context);
		},
		renderResult(result, { expanded }, theme, context) {
			return renderBoardToolResult(
				result,
				expanded,
				theme,
				Boolean(context.isError),
				context.lastComponent,
				{
					empty: "✓ no board changes",
					summary: (count) =>
						`✓ ${count} board change${count === 1 ? "" : "s"} applied`,
				},
				context.keyHint ?? keyHint,
			);
		},
		async execute(_toolCallId, params, signal, _onUpdate, ctx) {
			const root = requireProjectRoot(ctx.cwd);
			return withFileMutationQueue(path.resolve(root, BOARD_PATH), async () => {
				signal?.throwIfAborted();
				const loaded = await loadBoard(root);
				signal?.throwIfAborted();
				let state = loaded.state;
				const updatedAt = new Date().toISOString();
				const applied: BoardProposal[] = [];
				for (const raw of params.items) {
					state = loaded.boardState.updateBoardState(
						state,
						loaded.index.documents,
						raw.id,
						raw.state,
						"agent",
						updatedAt,
						raw.note,
					);
					applied.push({
						id: raw.id,
						state: raw.state,
						rationale: raw.note.trim(),
					});
				}
				if (applied.length > 0)
					loaded.boardState.writeBoardState(loaded.root, state);
				const items = [...applied].sort((left, right) =>
					left.id.localeCompare(right.id),
				);
				return {
					content: [
						{
							type: "text" as const,
							text:
								applied.length === 0
									? "No board states changed."
									: `${applied.length} board state(s) applied. Run /system board to review or override them.`,
						},
					],
					details: { items },
				};
			});
		},
	});

	return {
		tool,
		updateTool,
		async open(
			cwd: string,
			onExec?: BoardExec,
			page = "/board.html",
		): Promise<string> {
			const ticket = generation;
			const { index } = await loadBoard(cwd);
			if (ticket !== generation)
				throw new Error("System book opening cancelled");
			if (onExec) executors.set(index.root, onExec);
			let pending = servers.get(index.root);
			if (!pending) {
				pending = (async () => {
					const [{ renderSystemBookSite }, { startBookServer }] =
						await Promise.all([loadSystemRenderer(), loadBookServer()]);
					const current = proposals.get(index.root) ?? new Map();
					proposals.set(index.root, current);
					return startBookServer(
						index.root,
						current,
						renderSystemBookSite,
						async (id) => {
							const execute = executors.get(index.root);
							if (!execute) throw new Error("System execution is unavailable");
							await execute(id);
						},
					);
				})();
				servers.set(index.root, pending);
			}
			let server: BookServer;
			try {
				server = await pending;
			} catch (error) {
				if (servers.get(index.root) === pending) servers.delete(index.root);
				throw error;
			}
			if (ticket !== generation) {
				server.close();
				throw new Error("System book opening cancelled");
			}
			const url = new URL(page, server.url);
			url.searchParams.set(
				"k",
				new URL(server.url).searchParams.get("k") ?? "",
			);
			const { openUrl } = await loadOpenBrowser();
			const opened = await openUrl(url.href);
			const label = page === "/board.html" ? "System board" : "System book";
			return opened.ok
				? `${label} opened: ${url.href}\nBrowser: ${opened.command}`
				: `${label} running: ${url.href}\nBrowser: ${opened.error}`;
		},
		shutdown() {
			generation++;
			proposals.clear();
			for (const server of servers.values())
				void server.then(
					(value) => value.close(),
					() => {},
				);
			servers.clear();
			executors.clear();
		},
	};
}