import { StringEnum } from "@earendil-works/pi-ai"; import { defineTool, keyHint } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; import type { BoardServer } from "./board-server.ts"; import { type BoardProposal, readBoardState } from "./board-state.ts"; import { discoverProjectRoot } from "./documents.ts"; import { loadProjectIndex } from "./project-index.ts"; const STATES = ["todo", "done", "open"] as const; const proposalParameters = Type.Object({ items: Type.Array( Type.Object({ id: Type.String({ description: "Existing spec, plan, or issue ID." }), state: StringEnum(STATES, { 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 }, ), }); export function createBoardRuntime() { let proposalRoot: string | undefined; let proposalFinished = false; const proposals = new Map>(); const servers = new Set(); const tool = defineTool({ name: "system_board_propose", label: "system_board_propose", description: "Record evidence-backed proposed board states for human review. Accepts existing spec, plan, or issue IDs and does not modify .system/board.json.", promptSnippet: "Propose System board states for human review", promptGuidelines: [ "During /system assess or after completing /system exec, 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) { const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0); const items = Array.isArray(args.items) ? args.items : []; const count = items.length; let output = `${theme.fg("toolTitle", theme.bold("system_board_propose"))} ${theme.fg("toolOutput", `${count} item${count === 1 ? "" : "s"}`)}`; if (!context.expanded && count > 0) { output += theme.fg( "dim", ` (${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))}`; if (item.rationale) output += `\n${theme.fg("dim", String(item.rationale))}`; } } text.setText(output); return text; }, renderResult(result, _options, theme, context) { const text = (context.lastComponent as Text | undefined) ?? new Text("", 0, 0); const items = (result.details as { items?: BoardProposal[] } | undefined) ?.items; if (!items) { const output = result.content .filter( (item): item is { type: "text"; text: string } => item.type === "text", ) .map((item) => item.text) .join("\n"); text.setText(theme.fg(context.isError ? "error" : "muted", output)); return text; } const count = items.length; text.setText( theme.fg( "success", count === 0 ? "✓ no changes proposed" : `✓ ${count} change${count === 1 ? "" : "s"} proposed`, ), ); return text; }, async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const root = discoverProjectRoot(ctx.cwd); if (root !== proposalRoot) throw new Error( "system_board_propose is only available during /system assess or /system exec", ); const index = loadProjectIndex(root); const byId = new Map( index.documents.map((document) => [document.metadata.id, document]), ); const proposed = proposals.get(root) ?? new Map(); 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 = document.metadata.type === "issue" ? raw.state === "open" || raw.state === "done" : (document.metadata.type === "spec" || document.metadata.type === "plan") && (raw.state === "todo" || raw.state === "done"); 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(), }); } proposals.set(root, proposed); proposalFinished = true; 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 }, }; }, }); return { tool, beginProposal(cwd: string) { const root = discoverProjectRoot(cwd); const index = loadProjectIndex(root); readBoardState(root, index.prefix); proposalRoot = root; proposalFinished = false; proposals.set(root, new Map()); }, proposalComplete() { return proposalRoot !== undefined && proposalFinished; }, endProposal() { proposalRoot = undefined; proposalFinished = false; }, async open(cwd: string): Promise { const index = loadProjectIndex(cwd); const state = readBoardState(index.root, index.prefix); const current = [...(proposals.get(index.root)?.values() ?? [])]; const [{ renderSystemBoardSite }, { startBoardServer }, { openUrl }] = await Promise.all([ import("./system-renderer.ts"), import("./board-server.ts"), import("./open-browser.ts"), ]); const output = renderSystemBoardSite(index, state, current); const server = await startBoardServer( output.directory, index, proposals.get(index.root) ?? new Map(), ); servers.add(server); const opened = await openUrl(server.url); return opened.ok ? `System board opened: ${server.url}\nBrowser: ${opened.command}` : `System board running: ${server.url}\nBrowser: ${opened.error}`; }, shutdown() { proposalRoot = undefined; proposalFinished = false; for (const server of servers) server.close(); servers.clear(); }, }; }