/** * The `board` tool: the shared feature list for one repository. * * One action-shaped tool, because every action is work on the same record and a * model that has read the board should not have to learn a second surface to change * it. The tool owns nothing but the dispatch: the workspace comes from * `lib/workflow/session.ts`, the transition from `lib/workflow/rules.ts`, the bytes from * `lib/workflow/store.ts`, and the words from `format.ts` and `result.ts`. What a `list` answers is * `listing.ts`, reached with `import()` on the call that lists. * * A refusal is a failed result that still carries the card, so the next call starts * from the truth — and it is the same refusal the page shows, because both go * through `applyOp`. */ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { resolve } from "node:path"; import { planForContract } from "../../lib/workflow/artifact.ts"; import { type Card, cardArg, cardRefOf, normalizeCardId } from "../../lib/workflow/card.ts"; import { type Lane, movableLanes } from "../../lib/workflow/lanes.ts"; import type { LandingVerdict } from "../../lib/workflow/landing.ts"; import type { Verification } from "../../lib/workflow/contract.ts"; import { signMark } from "../../lib/workflow/signs.ts"; import type { VerifyRun } from "../../lib/workflow/verify.ts"; import type { CardOp } from "../../lib/workflow/rules.ts"; import type { BoardStore, MutateResult } from "../../lib/workflow/store.ts"; import { attempt, messageOf } from "../../lib/errors.ts"; import { listOf } from "../../lib/format.ts"; import { strayField } from "../../lib/stray-fields.ts"; import { resolveEffectiveCwd } from "../../lib/env.ts"; import { textResult } from "../../lib/tool-result.ts"; import { reuseText, toolDetails } from "../../lib/tui/chrome.ts"; import { callLine, detailsOrLine, isTailResult, TailResult } from "../../lib/tui/tool.ts"; import { CLAIM_NEXT, formatCard } from "./format.ts"; import { createDeliver, createTeamJoin, type TeamJoin } from "../../lib/session-tool.ts"; import { collapsedLine, refusal, resultInput } from "./result.ts"; import { dropCard, holderFact, mutate, reclaimOp } from "./write.ts"; import type { Deliver } from "../../lib/session-tool.ts"; import type { BoardSession } from "../../lib/workflow/session.ts"; import { type BoardArgs, BoardParams } from "./schema.ts"; import { ACTION_FIELDS, BOARD_ACTION_DOCS, BOARD_ACTIONS, BOARD_TOOL, type BoardAction, type BoardDetails, normalizeBoardAction, } from "./types.ts"; /** The verbs as one sentence, in `BOARD_ACTIONS` order; the table owns the words. */ function verbHelp(): string { return `${BOARD_ACTIONS.map((action) => `\`${action}\` ${BOARD_ACTION_DOCS[action]}`).join("; ")}.`; } /** * The tool's description: what the board is, and the actions it takes. * * Exported, with {@link BOARD_GUIDELINES}, so the surface budget in * `test/prompt-budget.test.ts` measures the text that is really registered instead of a * second copy of it. The actions are stated once, in `BOARD_ACTION_DOCS`. */ export const BOARD_DESCRIPTION = "The shared feature list for this repository: one card per feature, which any session reads and writes. " + `${verbHelp()} A card's steps do not belong on the board - they belong in the plan and in \`todo\`.`; /** * The workflow itself: the order a card moves in, the lane count, and the handoff. * * No action doc can say the order, because each one owns a single verb — the gates are what a * session gets wrong on its own, and a checklist that stops at `execute` leaves `review` to a * paragraph a model reads only when it reaches `done`. Everything a fourth bullet used to say is * stated once by the field or the action it is about — a `blocked` card's resume is the * `blocker` parameter's sentence, `dependsOn`'s refusal is its own parameter's, "steps belong in * `todo`" closes the description, and "`paths` are hints, not claims" closes the `paths` * parameter. Repeating one here costs every request for nothing, which is what the ceiling in * `test/prompt-budget.test.ts` is for: one idea per bullet, and none of them already said. */ export const BOARD_GUIDELINES = [ "Claim a card, design it in plan mode, record the contract, then `execute`: `approve` gates that, `review` gates `done`, and both signs are the lead's.", "Note each phase, and release or reclaim a card you stop holding, so the lane count means what it says.", "A `handoff` in your inbox is work you now own: read it with `session inbox`, record the plan, and start it.", ]; /** The one line in the system prompt's tool list: the actions, and nothing they do. */ export const BOARD_SNIPPET = `The shared feature list for this repository: ${BOARD_ACTIONS.join(", ")}.`; /** The parameters as the schema validates them. */ /** * The call line's subject: the verb and what it acts on. * * `add` shows the title because the title is the identity of the thing being * created; every other action names the card it touches, which is what a reader * scanning the transcript is looking for. */ function callSubject(action: BoardAction, args: Record): string { const card = cardRefOf(args.card); if (action === "add") { const title = typeof args.title === "string" ? args.title.trim() : ""; return title === "" ? "add" : `add ${title}`; } if (action === "list") { const parts = ["list"]; if (args.round === true) parts.push("round"); if (typeof args.lane === "string") parts.push(args.lane); if (typeof args.query === "string" && args.query.trim() !== "") parts.push(`"${args.query.trim()}"`); if (card !== "") parts.push(card); return parts.join(" "); } if (card === "") return action; const lane = typeof args.lane === "string" ? ` ${args.lane}` : ""; return `${action} ${card}${lane}`; } /** * The instruction a close may carry, or the reason it is refused. * * Here rather than in `steps.ts` because the write must import no landing module: the decision is * made where the chain was read (the lazily loaded `proof.ts`) and this is its other half — the one * fact `proof.ts` cannot know, which is who is asking. */ async function closingInstruction( store: BoardStore, rawCard: string | undefined, raw: string, actor: BoardDetails["me"], lane: Lane, verdict: LandingVerdict | undefined, ): Promise<{ text: string } | { error: string } | undefined> { const { instructionFor } = await import("../../lib/workflow/landing.ts"); const arg = cardArg(rawCard); const card = "error" in arg ? undefined : await store.read(arg.id); if (card === undefined) return undefined; return instructionFor({ card, raw, actor, lead: store.config().lead, target: lane, ...(verdict === undefined ? {} : { verdict }), }); } export function registerTools( pi: ExtensionAPI, runtime: BoardSession, deps: { team?: TeamJoin; notify?: Deliver; verify?: VerifyRun } = {}, ): void { const team = deps.team ?? createTeamJoin(pi); /** * The run a spot-check records, loaded at the first one: a board that never signs a card pays * nothing for the process seam it would need, and the registration graph stays where it is. */ let verifyModule: Promise | undefined; // Loaded at the first sign, not at registration: a board that never signs pays nothing for the // message, and the registration graph stays the size it was. let notices: Promise | undefined; // The same rule for the plan proof: `contract`, `move` and `approve` each ask for one, and a // session that only lists cards pays nothing for the module that reads the plan store. let proofModule: Promise | undefined; pi.registerTool({ name: BOARD_TOOL, label: "Board", description: BOARD_DESCRIPTION, promptSnippet: BOARD_SNIPPET, promptGuidelines: BOARD_GUIDELINES, parameters: BoardParams, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }, executionMode: "sequential", async execute(_toolCallId, params, _signal, _onUpdate, ctx) { const args = params as BoardArgs; const action = normalizeBoardAction(args.action); if (!action) { return refusal( "list", { label: "board" }, `unknown action "${String(args.action)}"; use ${BOARD_ACTIONS.join(", ")}.`, ); } // The actor names every refusal below, and reading it fails like anything else can: a // failure is a refusal carrying the tool's own name, not a call the transcript cannot draw. const known = await attempt(runtime.who(ctx, ctx.cwd)); if ("error" in known) return refusal(action, { label: BOARD_TOOL }, known.error); const me = known.value; /** What `store.mutate` should be told about the card's plan, proved the way the tool proves it. */ const proofOf = (store: BoardStore, rawCard: string | undefined, lane?: Lane) => (proofModule ??= import("./proof.ts")).then((m) => m.moveProofs(runtime, ctx.cwd, store, rawCard, lane, pi)); /** The crossing this call can make, bound to its context once. */ const cross = (result: MutateResult) => runtime.cross(ctx, result).catch(() => undefined); /** * The run a spot-check records, when the card's contract names a command. * * The board executes nothing of its own: this call is the run, and the record it hands the * store is evidence rather than an instruction. A card whose contract names nothing costs * no process at all — the read is the same one `mutate` is about to make. */ const verifiedFor = async ( store: BoardStore, rawCard: string | undefined, override: string | undefined, root: string | undefined, ): Promise<{ verified: Verification } | { error: string } | undefined> => { const id = rawCard === undefined ? undefined : normalizeCardId(rawCard); if (id === undefined) return undefined; const card = await store.read(id).catch(() => undefined); if (card === undefined) return undefined; // The gate, the override and the run are `lib/workflow/verify.ts`'s, so this door and the // person's ask one body where the command may start — the tree it runs in and the seams // it uses are the only things each knows. const module = await (verifyModule ??= import("../../lib/workflow/verify.ts")); return module.spotCheck({ card, actor: me, lead: store.config().lead, override, // The note the sign will carry: the gate refuses one the card cannot keep before the // command starts, so a too-long note costs no run. note: args.text, // The tree the review names, or the session's own: `root` is the card's worktree (or a checkout // at its commit) when the signer is not in it. It is read now rather than taken from the store: a // store opened before `worktree enter` keeps the checkout it was opened on, so its root is the // wrong answer exactly when the reviewer has moved — `ctx.cwd` never moves at all. cwd: root === undefined ? resolveEffectiveCwd(ctx.cwd) : resolve(resolveEffectiveCwd(ctx.cwd), root), run: deps.verify ?? module.defaultVerifyRun(), now: () => runtime.now(), tree: module.treeOf(pi), }); }; try { // Before the join and before a card is read: a refused call has written nothing, so it // cannot have enlisted this session as a teammate on its way to the refusal. const stray = strayField(action, args, ACTION_FIELDS); if (stray !== undefined) return refusal(action, me, stray); const store = await runtime.store(ctx.cwd); const now = runtime.now(); switch (action) { case "list": { // The four answers live with the reads behind them, loaded on the call that asks for one. // The roster is passed rather than read there: a rename is a fact about the bus, so the // listing asks it once, and the rows carry the live name while the rollup folds the rest. const { read } = await import("./listing.ts"); return await read(store, action, me, args, now, () => runtime.roster(ctx.cwd)); } case "add": return await add(store, me, args, now); case "claim": // Taking a card is what makes this session a teammate. It is the one action here worth // being addressed about, and the board is the user's surface for the team, so nobody has // to know the bus exists. A refused claim wrote nothing and enlists nobody, so the join is // the write's successor — and a join that did not land is a line on the result, because the // card it came after is already true. return await mutate( store, action, me, now, args, { kind: "claim" }, { next: CLAIM_NEXT, // Loaded here, not at registration: the join is the claim's side effect, so a session that // never claims pays nothing for it. joined: async () => { const { joinFailureLine, joinTeam } = await import("../../lib/workflow/join.ts"); return joinFailureLine(await joinTeam(runtime, team, ctx, me.label)); }, }, ); case "release": return await mutate(store, action, me, now, args, { kind: "release" }, { cross }); case "reclaim": // The op carries what the bus says about the holder: the rule lets a peer take a card back // only from a session that has stopped, and the lead from anybody. A reclaim that takes the // card from somebody owes them a sentence, and it describes the card as it was. return await mutate(store, action, me, now, args, await reclaimOp(runtime, store, args.card, ctx.cwd), { cross, notice: async (card: Card, result) => { const { deliverNotice } = await (notices ??= import("./notices.ts")); const previous = result.ok && result.previous !== undefined ? result.previous : card; return await deliverNotice({ kind: "reclaim", card: previous, lead: store.config().lead, by: me.label, ctx, deliver: deps.notify ?? createDeliver(pi), audience: { roster: () => runtime.roster(ctx.cwd), now: () => runtime.now() }, }); }, }); case "move": { const arg = cardArg(args.card); if ("error" in arg) return refusal(action, me, arg.error); // The proof and the holder fact take the caller's own spelling by name and normalize // inside, so this guard words the refusal and nothing is re-spelled here. const lane = args.lane; if (lane === undefined) { return refusal(action, me, `move needs a target lane: ${listOf(movableLanes())}.`); } const { artifact: proved, landed } = lane === "execute" || lane === "done" ? await proofOf(store, args.card, lane) : {}; // Decided here, not in `applyOp`: the write must not import the landing module, so the // instruction arrives as an answer beside the verdict it answers for. const instruction = args.override === undefined ? undefined : await closingInstruction(store, args.card, args.override, me, lane, landed); const op: CardOp = { kind: "move", lane, ...(args.blockedBy === undefined ? {} : { blockedBy: args.blockedBy }), ...(args.blocker === undefined ? {} : { blocker: args.blocker }), ...(proved === undefined ? {} : { artifact: proved }), ...(landed === undefined ? {} : { landed }), ...(instruction === undefined ? {} : { instruction }), // A close is where a signed card went, and the lead may make it for a holder the bus // has lost: the one fact that door needs, read only for a `done`. ...(lane === "done" ? await holderFact(runtime, store, args.card, ctx.cwd) : {}), }; return await mutate(store, action, me, now, args, op, { cross }); } case "note": return await mutate(store, action, me, now, args, { kind: "note", text: args.text }); case "contract": { // The store is resolved here, and the path proved where the rule asks: only a caller holding the // working directory can say where the plan store is, and only the locked pass can say whether // the file is still there when the write lands. const file = args.path; const planDir = file === undefined ? undefined : await runtime.planDir(ctx.cwd); const plan = planDir === undefined || file === undefined ? undefined : () => planForContract(planDir, file); // The peer is the one session that knows its wording is ready, so the same write tells the lead: // resolved through the roster like a sign's addressee, and caught there, so a bus that cannot answer // costs a clause and never the contract it came after. const notice = async (card: Card): Promise<{ line?: string }> => { const { deliverNotice } = await (notices ??= import("./notices.ts")); return await deliverNotice({ kind: "ready", card, lead: store.config().lead, ctx, deliver: deps.notify ?? createDeliver(pi), audience: { roster: () => runtime.roster(ctx.cwd), now: () => runtime.now() }, }); }; return await mutate( store, action, me, now, args, { kind: "contract", ...(plan === undefined ? {} : { artifact: plan }), goal: args.goal, acceptance: args.acceptance, scopeOut: args.scopeOut, verify: args.verify, }, { notice }, ); } case "approve": case "review": { const { settleNotice } = await (notices ??= import("./notices.ts")); // The name the sign will record, so the owner is told who signed rather than the // label the writing actor is called by. const signer = signMark(me, store.config().lead).by; // An approval covers the plan the card names as well as its wording, so it carries // the same proof a move does. A spot-check is about work already done, and the // `done` move proves the plan then, so it pays for nothing here. const artifact = action === "approve" ? (await proofOf(store, args.card)).artifact : undefined; // A spot-check of a card whose contract names a command is that command's run: // a refusal here writes nothing, which is what keeps a red check from signing. const evidence = action === "review" ? await verifiedFor(store, args.card, args.override, args.root) : undefined; if (evidence !== undefined && "error" in evidence) return refusal(action, me, evidence.error); // The one moment this sign is recorded at, read here and not at the top of the call: a // spot-check's command has a ten-minute bound, so a reading taken before it would stamp the // sign before its own evidence. One reading, because the message below writes the other half // of the same fact — `signStale` compares the later of the two, and a stale half would still // make a sign the work outgrew read as current. const at = runtime.now(); // The store's `notice` is what says a message is owed — a fresh stamp, or a repeat sign // whose card still reads as never told. The roster is read here rather than up front so // a call the store refused pays nothing for it. const notice = async (card: Card): Promise<{ card?: Card; line?: string }> => { const settled = await settleNotice({ store, card, kind: action, lead: store.config().lead, by: signer, actor: me, ctx, deliver: deps.notify ?? createDeliver(pi), at, audience: { roster: () => runtime.roster(ctx.cwd), now: () => runtime.now() }, }); return { card: settled.card, line: settled.line }; }; const op = action === "review" ? { kind: "review" as const, text: args.text, override: args.override, ...(evidence === undefined ? {} : { verified: evidence.verified }), } : { kind: "approve" as const, text: args.text, ...(artifact === undefined ? {} : { artifact }) }; return await mutate(store, action, me, at, args, op, { notice }); } case "edit": { if ( args.title === undefined && args.paths === undefined && args.type === undefined && args.breaking === undefined && args.priority === undefined && args.dependsOn === undefined ) { return refusal(action, me, "edit needs a title, paths, type, breaking, priority, or dependsOn."); } return await mutate( store, action, me, now, args, { kind: "edit", title: args.title, paths: args.paths, type: args.type, breaking: args.breaking, priority: args.priority, dependsOn: args.dependsOn, }, // An edit that changes an `execute` card's paths changes what it holds: the diff // claims what it added and releases what it removed. { cross }, ); } case "drop": return await dropCard(store, me, args, now, cross); case "archive": // The archive action lives with the sweep it runs, loaded when it is called. const { archiveCards } = await import("./archive.ts"); return await archiveCards(store, me, args, now); } } catch (error) { return refusal(action, me, messageOf(error)); } }, renderCall(args, theme, context) { const action = normalizeBoardAction(args.action) ?? "list"; return callLine(theme, context.lastComponent, BOARD_TOOL, callSubject(action, args as Record)); }, renderResult(result, options, theme, context) { const text = reuseText(context?.lastComponent); const details = toolDetails(result.details); const outcome = detailsOrLine(theme, result, options.expanded, details); if ("line" in outcome) { text.setText(outcome.line); return text; } // A `list` is the one action with rows, so a collapsed block is the line that counts // them: the rows are what expanding adds, not a second copy of the line's answer. const input = options.expanded ? resultInput(outcome.details) : undefined; if (!input) { text.setText(collapsedLine(theme, outcome.details)); return text; } const previous = context?.lastComponent; const view = isTailResult(previous) ? previous : new TailResult(input, theme); view.setInput(input, theme); return view; }, }); } /** `add`: the only action that creates a card. */ async function add( store: BoardStore, me: BoardDetails["me"], args: BoardArgs, now: number, ): Promise>> { // Loaded here rather than at registration: `add` is the only caller, and a session that // never adds a card pays nothing for the argument boundary. const { createInput } = await import("./input.ts"); const parsed = createInput({ title: args.title, paths: args.paths, type: args.type, breaking: args.breaking, priority: args.priority, note: args.note, }); if ("error" in parsed) return refusal("add", me, parsed.error); const card = await store.create(parsed.input, me, now); return textResult(formatCard(card), { action: "add", me, card }); }