diff --git a/agent/extensions/work/index.ts b/agent/extensions/work/index.ts index c1bb035..1784370 100644 --- a/agent/extensions/work/index.ts +++ b/agent/extensions/work/index.ts @@ -1,15 +1,17 @@ import { join, resolve } from "node:path"; import { stripVTControlCharacters } from "node:util"; import { + generateDiffString, getAgentDir, + renderDiff, type ExtensionAPI, type ExtensionContext, type SessionManager, type Theme, type ToolRenderers, } from "@earendil-works/pi-coding-agent"; -import { Text, TruncatedText } from "@earendil-works/pi-tui"; -import { Type } from "typebox"; +import { Text, TruncatedText, type Component } from "@earendil-works/pi-tui"; +import { Type, type Static } from "typebox"; import { Check } from "typebox/value"; import { CreateSchema, @@ -26,7 +28,7 @@ import { type ReadResult, } from "./schema.ts"; import { classifyWork } from "./classifier.ts"; -import { findPage, WorkStore } from "./store.ts"; +import { findPage, WorkStore, type EntryChange } from "./store.ts"; import type { WorkViewer } from "./viewer.ts"; import { LinkSettingsSchema } from "./references.ts"; @@ -98,126 +100,159 @@ function singleLine(text: string): string { return terminalText(text).replace(/\s+/g, " "); } -function callLine(name: string, detail: string, theme: Theme) { - return new TruncatedText( - `${theme.fg("toolTitle", theme.bold(name))} ${theme.fg("accent", singleLine(detail))}`, - 0, - 0, +const RowState = Type.Object({ + id: Type.Optional(Type.String()), + title: Type.Optional(Type.String()), +}); +type RowState = Static; +const RecordDetails = Type.Object({ + id: Type.String(), + title: Type.String(), + changes: Type.Optional( + Type.Array( + Type.Object({ + id: Type.String(), + title: Type.String(), + diff: Type.Optional(Type.String()), + }), + ), + ), +}); +type RecordDetails = Static; +type RenderContext = Parameters>[3]; + +function rowState(context: RenderContext): RowState { + return Check(RowState, context.state) ? context.state : {}; +} + +/** Draws when rendered, so the call line can show the record title that the result renderer stores. */ +function callLine(name: string, detail: () => string, theme: Theme): Component { + return { + render: (width) => + new TruncatedText( + `${theme.fg("toolTitle", theme.bold(name))} ${detail()}`, + 0, + 0, + ).render(width), + invalidate() {}, + }; +} + +function recordLabel(state: RowState, id: string | undefined, theme: Theme): string { + return state.title && state.id + ? `${theme.fg("accent", singleLine(state.title))} ${theme.fg("dim", state.id.slice(0, 8))}` + : theme.fg("accent", singleLine(id?.slice(0, 8) ?? "selected")); +} + +function contentText(content: Entry["content"]): string { + return terminalText( + Object.entries(content) + .filter(([field]) => field !== "kind") + .map(([field, value]) => `${field}: ${Array.isArray(value) ? value.join(", ") : value}`) + .join("\n"), ); } -function entryText(entry: Entry): string { - const content = entry.content; - const status = "status" in content ? content.status : content.authority; - const body = - content.kind === "brief" - ? [ - content.objective, - content.scope, - content.constraints, - content.approach, - `Projects: ${content.projects.join(", ")}`, - ] - : [content.body]; - const links = - content.kind === "brief" - ? content.related - : content.kind === "task" - ? content.evidence - : content.sources; - return [ - `${entry.id} · r${entry.revision} · ${content.kind} · ${singleLine(content.title)} · ${status}`, - ...body, - links?.length ? `References: ${links.join(", ")}` : undefined, - entry.superseded_by ? `Superseded by: ${entry.superseded_by}` : undefined, - ] - .filter(Boolean) - .join("\n"); +function changeDetails({ + entry, + previous, +}: EntryChange): NonNullable[number] { + const diff = previous + ? generateDiffString(contentText(previous.content), contentText(entry.content)).diff + : ""; + return { + id: entry.id, + title: entry.content.title, + diff: diff || undefined, + }; +} + +function statusResult( + result: Parameters>[0], + isPartial: boolean, + theme: Theme, + context: RenderContext, +): Component | undefined { + if (context.isError || result.isError) { + const text = result.content + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n"); + return new Text(theme.fg("error", terminalText(text)), 0, 0); + } + if (isPartial) { + return new Text(theme.fg("muted", "Working…"), 0, 0); + } + return undefined; } -const renderWorkResult: NonNullable = ( +const renderFindResult: NonNullable = ( result, { expanded, isPartial }, theme, context, ) => { - const raw = () => - terminalText( - result.content - .filter((part) => part.type === "text") - .map((part) => part.text) - .join("\n"), - ); - if (context.isError || result.isError) { - return new Text(theme.fg("error", raw()), 0, 0); - } - if (isPartial) { - return new Text(theme.fg("muted", "Working…"), 0, 0); + const status = statusResult(result, isPartial, theme, context); + if (status) { + return status; } const data = result.details; - const lines: string[] = []; - if (Check(FindOutput, data)) { - lines.push(`Records: ${data.records.length}`); - for (const record of data.records.slice(0, expanded ? undefined : 3)) { - lines.push( - `${singleLine(record.title)} · ${record.status} · ${expanded ? record.id : record.id.slice(0, 8)}`, - ); - if (expanded) { - lines.push( - record.objective, - `Projects: ${record.projects.join(", ")} · r${record.revision}`, - ); - } - } - if (!expanded && data.records.length > 3) { - lines.push(`… ${data.records.length - 3} more records`); - } - if (data.next_offset !== undefined) { - lines.push(`More records · next offset: ${data.next_offset}`); - } - } else if (Check(ReadOutput, data)) { + if (!Check(FindOutput, data)) { + return new Text("", 0, 0); + } + const lines = [`Records: ${data.records.length}`]; + for (const record of data.records.slice(0, expanded ? undefined : 3)) { lines.push( - `Record ${expanded ? data.id : data.id.slice(0, 8)} · r${data.revision} · ${data.view} · entries: ${data.entries.length}`, + `${singleLine(record.title)} · ${record.status} ${theme.fg("dim", expanded ? record.id : record.id.slice(0, 8))}`, ); - for (const entry of data.entries.slice(0, expanded ? undefined : 3)) { - lines.push( - expanded ? entryText(entry) : `${entry.id} · ${singleLine(entry.content.title)}`, - ); - } - if (!expanded && data.entries.length > 3) { - lines.push(`… ${data.entries.length - 3} more entries`); - } - for (const entry of data.index.slice(0, expanded ? undefined : 3)) { + if (expanded) { lines.push( - `${entry.parent ? " " : ""}${entry.id} · ${singleLine(entry.title)} · ${entry.status ?? entry.authority ?? entry.kind}`, + terminalText(record.objective), + `Projects: ${terminalText(record.projects.join(", "))} · r${record.revision}`, ); } - if (!expanded && data.index.length > 3) { - lines.push(`… ${data.index.length - 3} more index entries`); - } - if (data.omitted) { - lines.push(`Omitted entries: ${data.omitted}`); - } - if (data.next_revision !== undefined) { - lines.push(`More entries · after revision: ${data.next_revision}`); - } - } else if (Check(MutationOutput, data)) { - lines.push( - `Record ${expanded ? data.id : data.id.slice(0, 8)} · r${data.revision} · changed: ${data.changed.length}`, - ); - if (expanded) { - lines.push(...data.changed.map((entry) => `${entry.id} · r${entry.revision}`)); - } - } else { - lines.push(raw()); } - return new Text(theme.fg("toolOutput", terminalText(lines.join("\n"))), 0, 0); + if (!expanded && data.records.length > 3) { + lines.push(`… ${data.records.length - 3} more records`); + } + if (data.next_offset !== undefined) { + lines.push(`More records · next offset: ${data.next_offset}`); + } + return new Text(theme.fg("toolOutput", lines.join("\n")), 0, 0); }; -function toolResult(data: T) { +const renderRecordResult: NonNullable = ( + result, + { expanded, isPartial }, + theme, + context, +) => { + const status = statusResult(result, isPartial, theme, context); + if (status) { + return status; + } + const details = result.details; + if (!Check(RecordDetails, details)) { + return new Text("", 0, 0); + } + Object.assign(context.state, { id: details.id, title: details.title }); + if (!expanded || !details.changes) { + return new Text("", 0, 0); + } + const lines = details.changes.flatMap(({ id, title, diff }) => [ + `${theme.fg("accent", singleLine(id))} ${theme.fg("toolOutput", singleLine(title))}`, + ...(diff ? [renderDiff(diff)] : []), + ]); + return new Text(lines.join("\n"), 0, 0); +}; + +function toolResult( + data: T, + details: FindResult | ReadResult | MutationResult | RecordDetails = data, +) { return { content: [{ type: "text" as const, text: JSON.stringify(data) }], - details: data, + details, structuredContent: data, }; } @@ -475,19 +510,16 @@ export function createWorkExtension( parameters: FindSchema, outputSchema: FindOutput, renderCall(args, theme) { - return callLine( - "work_find", - [ - args.query ?? (args.change ? `change ${args.change}` : "list"), - args.all_projects ? "all projects" : args.project, - args.status, - ] - .filter(Boolean) - .join(" · "), - theme, - ); + const detail = [ + args.query ?? (args.change ? `change ${args.change}` : "list"), + args.all_projects ? "all projects" : args.project, + args.status, + ] + .filter(Boolean) + .join(" · "); + return callLine("work_find", () => theme.fg("accent", singleLine(detail)), theme); }, - renderResult: renderWorkResult, + renderResult: renderFindResult, async execute(_call, input, signal, _update, ctx) { signal?.throwIfAborted(); const project = projectIdentity(pi, ctx.cwd); @@ -540,10 +572,17 @@ export function createWorkExtension( }, parameters: CreateSchema, outputSchema: MutationOutput, - renderCall(args, theme) { - return callLine("work_create", args.title ?? "…", theme); + renderCall(args, theme, context) { + return callLine( + "work_create", + () => { + const { id } = rowState(context); + return `${theme.fg("accent", singleLine(args.title ?? "…"))}${id ? ` ${theme.fg("dim", id.slice(0, 8))}` : ""}`; + }, + theme, + ); }, - renderResult: renderWorkResult, + renderResult: renderRecordResult, executionMode: "sequential", async execute(_call, input, signal, _update, ctx) { signal?.throwIfAborted(); @@ -552,7 +591,7 @@ export function createWorkExtension( const result = store.create(input, project, author(ctx)); select(result.id); needsRead = false; - return toolResult(result); + return toolResult(result, { id: result.id, title: input.title }); }, }); @@ -576,27 +615,26 @@ export function createWorkExtension( }, parameters: ReadSchema, outputSchema: ReadOutput, - renderCall(args, theme) { + renderCall(args, theme, context) { const view = (Array.isArray(args.entry_ids) ? args.entry_ids.join(", ") : undefined) ?? - (args.since_revision !== undefined - ? `since r${args.since_revision}` - : (args.query ?? "current")); + (args.since_revision !== undefined ? `since r${args.since_revision}` : args.query); + const detail = [ + view, + args.history ? "history" : undefined, + args.attach ? "attach" : undefined, + args.after_revision !== undefined ? `after r${args.after_revision}` : undefined, + ] + .filter(Boolean) + .join(" · "); return callLine( "work_read", - [ - args.id?.slice(0, 8) ?? "selected", - view, - args.history ? "history" : undefined, - args.attach ? "attach" : undefined, - args.after_revision !== undefined ? `after r${args.after_revision}` : undefined, - ] - .filter(Boolean) - .join(" · "), + () => + `${recordLabel(rowState(context), args.id, theme)} ${theme.fg("muted", singleLine(detail))}`, theme, ); }, - renderResult: renderWorkResult, + renderResult: renderRecordResult, executionMode: "sequential", async execute(_call, input, signal) { signal?.throwIfAborted(); @@ -608,7 +646,7 @@ export function createWorkExtension( if (selected === id && result.view === "current") { needsRead = false; } - return toolResult(result); + return toolResult(result, { id, title: store.title(id) }); }, }); @@ -638,22 +676,25 @@ export function createWorkExtension( { additionalProperties: false }, ), outputSchema: MutationOutput, - renderCall(args, theme) { + renderCall(args, theme, context) { const operations = Array.isArray(args.operations) ? args.operations : []; - const summary = operations.map((operation) => - operation?.action === "add" - ? `add ${operation.entry?.kind ?? "entry"}: ${operation.entry?.title ?? "…"}` - : operation?.action === "set_brief" - ? "update brief" - : `update ${operation?.id ?? "task"}`, - ); + const summary = operations + .map((operation) => + operation?.action === "add" + ? `add ${operation.entry?.kind ?? "entry"}: ${operation.entry?.title ?? "…"}` + : operation?.action === "set_brief" + ? "update brief" + : `update ${operation?.id ?? "task"}`, + ) + .join(", "); return callLine( "work_update", - `${args.id?.slice(0, 8) ?? "selected"} · ${operations.length} changes · ${summary.join(", ")}`, + () => + `${recordLabel(rowState(context), args.id, theme)} ${theme.fg("muted", singleLine(summary))}`, theme, ); }, - renderResult: renderWorkResult, + renderResult: renderRecordResult, async execute(_call, input, signal, _update, ctx) { signal?.throwIfAborted(); const branch = ctx.sessionManager.getBranch(); @@ -678,7 +719,13 @@ export function createWorkExtension( } return { ...operation, entry: { ...decision, user_entry: source.id } }; }); - return toolResult(store.update(workId(input.id), operations, author(ctx))); + const id = workId(input.id); + const result = store.update(id, operations, author(ctx)); + return toolResult(result, { + id, + title: store.title(id), + changes: store.changes(id, result.changed).map(changeDetails), + }); }, }); } diff --git a/agent/extensions/work/store.ts b/agent/extensions/work/store.ts index 59c7078..afde29b 100644 --- a/agent/extensions/work/store.ts +++ b/agent/extensions/work/store.ts @@ -76,6 +76,11 @@ export interface WorkCandidate { entries?: EntryMatch[]; } +export interface EntryChange { + entry: Entry; + previous?: Entry; +} + export interface WorkSnapshot { id: string; revision: number; @@ -568,6 +573,28 @@ export class WorkStore { }); } + title(id: string): string { + return this.transaction(false, (db) => briefContent(getEntry(db, id, "brief")).title); + } + + /** Each changed entry at its revision, with the version before it. */ + changes(id: string, changed: MutationResult["changed"]): EntryChange[] { + return this.transaction(false, (db) => + changed.map(({ id: entryId, revision }) => { + const [entry, previous] = db + .prepare( + "SELECT payload FROM versions WHERE work_id = ? AND entry_id = ? AND revision <= ? ORDER BY revision DESC LIMIT 2", + ) + .all(id, entryId, revision) + .map(decodeEntry); + if (!entry) { + throw new Error("Work entry was not found"); + } + return { entry, previous }; + }), + ); + } + snapshot(id: string): WorkSnapshot | undefined { return this.transaction(false, (db) => { const entries = db diff --git a/agent/extensions/work/test/extension.test.ts b/agent/extensions/work/test/extension.test.ts index be334ed..7198c91 100644 --- a/agent/extensions/work/test/extension.test.ts +++ b/agent/extensions/work/test/extension.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import test, { type TestContext } from "node:test"; import { createEventBus, + initTheme, SessionManager, type ToolRenderers, } from "@earendil-works/pi-coding-agent"; @@ -97,7 +98,7 @@ interface CapturedTool extends ToolRenderers { ctx: FixtureContext, ): Promise<{ content: Array<{ type: "text"; text: string }>; - details?: unknown; + details: unknown; structuredContent?: unknown; usage?: Usage; isError?: boolean; @@ -258,7 +259,7 @@ function renderContext(isError = false): RenderContext { outputPad: 0, }; } -function assertTerminalSafe(component: Component, width = 40): void { +function assertTerminalSafe(component: Component, width = 40): string[] { const lines = component.render(width); assert.ok(lines.every((line) => visibleWidth(line) <= width)); // Truncation adds its own SGR resets, so check only the controls that the fixtures inject. @@ -270,6 +271,7 @@ function assertTerminalSafe(component: Component, width = 40): void { ), false, ); + return lines; } const classifierUsage: Usage = { input: 100, @@ -463,10 +465,16 @@ test("invalid configuration and classifier failures never become successful empt assert.match(failed.content[0].text, /timed out/); }); -test("work renderers tolerate partial arguments and strip terminal controls", async (t) => { +test("work renderers show record titles and text diffs and strip terminal controls", async (t) => { + initTheme("dark"); const { extension } = await fixture(t); await create(extension); - await call(extension, "work_update", { + const tool = (name: string) => { + const found = extension.tools.get(name); + assert.ok(found?.renderCall && found.renderResult); + return { ...found, renderCall: found.renderCall, renderResult: found.renderResult }; + }; + const updateArgs = { operations: [ { action: "add", @@ -477,28 +485,72 @@ test("work renderers tolerate partial arguments and strip terminal controls", as status: "hypothesis", }, }, + { + action: "set_brief", + expected_revision: 1, + patch: { objective: "Reduce cold startup time" }, + }, ], - }); - const read = await call(extension, "work_read", { since_revision: 0 }); - assert.ok(Check(ReadOutput, read)); - for (const tool of extension.tools.values()) { - assert.ok(tool.renderCall && tool.renderResult); + } satisfies Input; + const execute = async (name: string, input: Input) => { + const { content, details } = await tool(name).execute( + "call", + input, + undefined, + undefined, + extension.ctx, + ); + return { content, details }; + }; + const update = await execute("work_update", updateArgs); + const read = await execute("work_read", { since_revision: 0 }); + const rows = { work_update: [updateArgs, update], work_read: [{}, read] } as const; + for (const [name, [args, result]] of Object.entries(rows)) { + const context = renderContext(); + const resultLines = assertTerminalSafe( + tool(name).renderResult( + result, + { expanded: true, isPartial: false }, + renderTheme, + context, + ), + 80, + ).join("\n"); + const callLine = assertTerminalSafe(tool(name).renderCall(args, renderTheme, context), 200); + assert.equal(callLine.length, 1); + assert.match(callLine[0], /Improve startup/); + if (name === "work_read") { + assert.equal(resultLines, ""); + } else { + assert.match(callLine[0], /add finding: Measured.*cost, update brief/); + assert.match(resultLines, /F2 Measured.*cost/); + assert.match(resultLines, /brief Improve startup/); + assert.match(resultLines, /-\d+ objective: Reduce startup time/); + assert.match(resultLines, /\+\d+ objective: Reduce cold startup time/); + } + } + for (const found of extension.tools.values()) { + assert.ok(found.renderCall && found.renderResult); for (const args of [ {}, { query: "\u001b[2J漢😀\n".repeat(200) }, { entry_ids: {} }, { operations: [null, {}] }, ]) { - assertTerminalSafe(tool.renderCall(args, renderTheme, renderContext())); + assertTerminalSafe(found.renderCall(args, renderTheme, renderContext())); } - for (const [data, isError] of [ + const failed = { + content: [{ type: "text" as const, text: "\u001b[31mSearch\u0007 failed\b" }], + details: undefined, + }; + for (const [result, isError] of [ + [update, false], [read, false], - [undefined, true], + [failed, true], ] as const) { - const text = data ? JSON.stringify(data) : "\u001b[31mSearch\u0007 failed\b"; assertTerminalSafe( - tool.renderResult( - { content: [{ type: "text", text }], details: data }, + found.renderResult( + result, { expanded: true, isPartial: false }, renderTheme, renderContext(isError), diff --git a/agent/extensions/work/test/runtime.test.ts b/agent/extensions/work/test/runtime.test.ts index f133827..edd7da9 100644 --- a/agent/extensions/work/test/runtime.test.ts +++ b/agent/extensions/work/test/runtime.test.ts @@ -178,6 +178,9 @@ test("nested tool calls return schema-valid data and selection survives a compac ); assert.ok(result?.type === "message" && result.message.role === "toolResult"); assert.equal(result.message.isError, false); - assert.ok(Check(ReadOutput, result.message.details)); - assert.equal(result.message.details.id, workId); + const [content] = result.message.content; + assert.equal(content?.type, "text"); + const read: unknown = JSON.parse(content.text); + assert.ok(Check(ReadOutput, read)); + assert.equal(read.id, workId); });