diff --git a/README.md b/README.md index db83083d..b58e1929 100644 --- a/README.md +++ b/README.md @@ -434,7 +434,10 @@ bun run src/index.ts install ./plugins/methodsmith --to pi --pi-home "$HOME/.pi/ Restart Pi, open the project, then invoke `method-setup` with Pi's normal skill interface. `pi-subagents` is required for Methodsmith review/workflow delegation; -`pi-ask-user` enables the short setup confirmation UI. +`pi-ask-user` enables the short setup confirmation UI. The generated install also +includes `methodsmith-ask-user-guard.ts`: it removes empty/default batch padding +and blocks repeated failed question calls. It preserves question choices and +all approval safeguards. Use `/reload` or restart Pi after updating. ### Use the plugin after installation diff --git a/docs/setup.md b/docs/setup.md index fa3c0f5f..ce65a39e 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -185,13 +185,21 @@ Restart Pi, open the project, and invoke `method-setup` using Pi's normal skill interface. `pi-subagents` is required for Methodsmith subagent workflows; `pi-ask-user` is recommended for the compact setup confirmation. +The generated install includes `methodsmith-ask-user-guard.ts`. For batched +questions, it removes only blank context, empty options and neutral top-level +flags; each question's own content and flags stay unchanged. Meaningful +conflicting fields are blocked, not discarded. Repeating the same failed call +is blocked until a new user turn; the agent must correct the call or ask in chat +and wait. Tool errors and cancellations never count as approval. Use `/reload` +or restart Pi to load an updated guard. + ### What the easy installer does | Target | Installer action | Required finish | |---|---|---| | Claude Code | Adds the GitHub marketplace (or this checkout with `--source`), installs `methodsmith`, turns on auto-update, and optionally creates managed bare `/method-*` aliases | Restart Claude Code, open the project or study directory, then run `/methodsmith:method-setup` or the optional `/method-setup` alias | | Codex | Adds the GitHub marketplace (or this checkout with `--source`) so `codex plugin marketplace upgrade` works and, when Bun is available, writes the generated agent bridge into the selected `CODEX_HOME` | Restart Codex, open `/plugins`, install **Methodsmith**, restart again, then start a new task in the target project | -| Pi | Writes generated Methodsmith skills and agents under the selected Pi home, plus a managed block in that root's `AGENTS.md` | Install `pi-subagents`, restart Pi, open the target project, then invoke `method-setup` | +| Pi | Writes generated Methodsmith skills, agents and the question-call guard under the selected Pi home, plus a managed block in that root's `AGENTS.md` | Install `pi-subagents`, restart Pi, open the target project, then invoke `method-setup` | The installer does not configure every research project globally. The `method-setup` skill creates project-local configuration after the plugin is loaded. diff --git a/plugins/methodsmith/README.md b/plugins/methodsmith/README.md index 952156e3..0f65b113 100644 --- a/plugins/methodsmith/README.md +++ b/plugins/methodsmith/README.md @@ -247,7 +247,10 @@ bun run src/index.ts install ./plugins/methodsmith --to pi --pi-home "$HOME/.pi/ Restart Pi, open the target project, and invoke `method-setup` using Pi's skill interface. `pi-subagents` is required for Methodsmith delegation; `pi-ask-user` enables -the compact confirmation interaction. +the compact confirmation interaction. Generated Pi installs include +`methodsmith-ask-user-guard.ts` to remove empty/default batch padding and block +unchanged failed-call loops. Question choices and approval safeguards remain +intact. Use `/reload` or restart Pi after updating. ### Keep Methodsmith updated diff --git a/src/converters/claude-to-pi.ts b/src/converters/claude-to-pi.ts index be0b9c4f..afcb3723 100644 --- a/src/converters/claude-to-pi.ts +++ b/src/converters/claude-to-pi.ts @@ -8,6 +8,7 @@ import type { } from "../types/pi" import type { ClaudeToOpenCodeOptions } from "./claude-to-opencode" import { isReservedPathRoot } from "../utils/slash-command" +import { piAskUserGuard } from "./pi-ask-user-guard" export type ClaudeToPiOptions = ClaudeToOpenCodeOptions @@ -41,7 +42,7 @@ export function convertClaudeToPi( })), generatedSkills: [], agents, - extensions: [], + extensions: plugin.manifest.name === "methodsmith" ? [piAskUserGuard()] : [], mcporterConfig: plugin.mcpServers ? convertMcpToMcporter(plugin.mcpServers) : undefined, } } diff --git a/src/converters/pi-ask-user-guard.ts b/src/converters/pi-ask-user-guard.ts new file mode 100644 index 00000000..47725192 --- /dev/null +++ b/src/converters/pi-ask-user-guard.ts @@ -0,0 +1,96 @@ +import type { PiExtensionFile } from "../types/pi" + +/** Standalone runtime adapter: keep the community UI and its approval semantics. */ +export function piAskUserGuard(): PiExtensionFile { + return { name: "methodsmith-ask-user-guard.ts", content: PI_ASK_USER_GUARD } +} + +// No host-package imports: this file also loads on older Pi versions. It does +// not inspect credentials, answers, patient files, or settings. Only transient +// hashes of failed ask arguments are retained, never their contents. +const PI_ASK_USER_GUARD = String.raw`import { createHash } from "node:crypto"; + +type Params = Record; +type Event = { + toolName?: string; + toolCallId?: string; + input?: Params; + args?: unknown; + isError?: boolean; +}; +type Block = { block: true; reason: string; terminate: true }; +type Context = { abort(): void }; +type Pi = { on(name: string, handler: (event: Event, ctx?: Context) => Block | void): unknown }; + +const ENTRY_FIELDS = ["context", "options", "allowMultiple", "allowFreeform"] as const; +const FALLBACK = " Ask one focused question in chat and wait for the user's answer. No approval is inferred; keep all safeguards in place."; + +export function normalizeBatchPadding(params: Params): void { + // Invalid arrays stay invalid. Do not invent a batch or move question data. + if (!Array.isArray(params.questions) || params.questions.length < 2 || params.questions.length > 4) return; + if (typeof params.context === "string" && params.context.trim() === "") delete params.context; + if (Array.isArray(params.options) && params.options.length === 0) delete params.options; + // These are the tool's documented neutral defaults, not permission choices. + // Every entry's own flags remain untouched, including non-default flags. + if (params.allowMultiple === false) delete params.allowMultiple; + if (params.allowFreeform === true) delete params.allowFreeform; + const conflicts = ENTRY_FIELDS.filter((field) => params[field] != null); + if (conflicts.length) { + throw new Error("ask_user batch has meaningful or invalid top-level fields: " + conflicts.join(", ") + + ". Put these fields on each questions entry; do not discard their meaning." + FALLBACK); + } +} + +function canonical(value: unknown): unknown { + if (Array.isArray(value)) return value.map(canonical); + if (value !== null && typeof value === "object") { + return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)) + .map(([key, child]) => [key, canonical(child)])); + } + return value; +} + +function fingerprint(value: unknown): string { + return createHash("sha256").update(JSON.stringify(canonical(value)) ?? "undefined").digest("hex"); +} + +export default function(pi: Pi): void { + const calls = new Map(); + const failed = new Set(); + const remember = (digest: string) => { + failed.add(digest); + if (failed.size > 32) failed.delete(failed.values().next().value!); + }; + const reset = () => { calls.clear(); failed.clear(); }; + pi.on("session_start", reset); + pi.on("input", reset); + pi.on("tool_call", (event) => { + if (event.toolName !== "ask_user" || !event.input) return; + try { + normalizeBatchPadding(event.input); + } catch (error) { + remember(fingerprint(event.input)); + return { block: true, terminate: true, reason: (error as Error).message }; + } + const digest = fingerprint(event.input); + if (failed.has(digest)) { + return { block: true, terminate: true, + reason: "Do not repeat the same failed ask_user call. Correct its arguments once or use the chat fallback." + FALLBACK }; + } + if (event.toolCallId) calls.set(event.toolCallId, digest); + }); + pi.on("tool_execution_end", (event, ctx) => { + if (event.toolName !== "ask_user") return; + const digest = event.toolCallId ? calls.get(event.toolCallId) : undefined; + if (event.isError) { + const key = digest ?? fingerprint(event.args); + const repeated = failed.has(key); + remember(key); + // Schema failures skip tool_call. Stop their second identical failure + // here so they cannot spin forever outside the normalizing hook. + if (repeated) ctx?.abort(); + } + if (event.toolCallId) calls.delete(event.toolCallId); + }); +} +` diff --git a/src/targets/pi.ts b/src/targets/pi.ts index 14f85c6b..f2af7ee4 100644 --- a/src/targets/pi.ts +++ b/src/targets/pi.ts @@ -34,6 +34,17 @@ const PI_AGENTS_BLOCK_BODY = `## Methodsmith (Pi compatibility) This block is managed by methodsmith. +Send minimal \`ask_user\` arguments: omit unused optional fields rather than +filling them with empty strings, arrays, or default flags. For multiple questions, +put \`context\`, \`options\`, \`allowMultiple\`, and \`allowFreeform\` inside each question +entry. Do not also pass those fields at the top level. + +If \`ask_user\` fails, correct the arguments once; never repeat the unchanged +failed call. If it still fails, ask one focused question in chat and wait for the +reply. A tool error or cancellation is not approval; keep all safeguards in place. +The installed \`methodsmith-ask-user-guard.ts\` removes harmless batch padding +and blocks unchanged failed-call loops without replacing the community UI. + Pi extensions used by this plugin: - Required: \`pi-subagents\` (by nicobailon) provides the \`subagent\` tool used by skills that dispatch parallel agents - Recommended: \`pi-ask-user\` (by edlsh) provides the \`ask_user\` tool; skills fall back to numbered options in chat when it is missing diff --git a/tests/cli.test.ts b/tests/cli.test.ts index b4a09044..1dd3ef24 100644 --- a/tests/cli.test.ts +++ b/tests/cli.test.ts @@ -205,6 +205,8 @@ describe("CLI", () => { const agents = await fs.readFile(path.join(piHome, "AGENTS.md"), "utf8") expect(agents).toContain("pi-subagents") expect(agents).toContain("pi-ask-user") + expect(agents).toContain("never repeat the unchanged") + expect(await exists(path.join(piHome, "extensions", "methodsmith-ask-user-guard.ts"))).toBe(true) }) test("install rejects native marketplace-only plugin targets", async () => { diff --git a/tests/pi-ask-user-guard.test.ts b/tests/pi-ask-user-guard.test.ts new file mode 100644 index 00000000..75a96d79 --- /dev/null +++ b/tests/pi-ask-user-guard.test.ts @@ -0,0 +1,222 @@ +import { describe, expect, test } from "bun:test" +import { promises as fs } from "node:fs" +import path from "node:path" +import os from "node:os" +import { convertClaudeToPi } from "../src/converters/claude-to-pi" +import type { ClaudePlugin } from "../src/types/claude" + +type Params = Record +type Event = { toolName?: string; toolCallId?: string; input?: Params; args?: unknown; isError?: boolean } +type Block = { block: boolean; reason: string; terminate?: boolean } | undefined +type Handler = (event: Event, ctx?: { abort(): void }) => Block | void + +const plugin: ClaudePlugin = { + root: "/tmp/synthetic-plugin", + manifest: { name: "methodsmith", version: "1.0.0" }, + agents: [], commands: [], skills: [], hooks: undefined, mcpServers: undefined, +} +const options = { agentMode: "subagent", inferTemperature: false, permissions: "none" } as const +const questions = () => [ + { question: "Synthetic decision A?", context: "Context A", options: [{ title: "A" }], allowMultiple: false, allowFreeform: true }, + { question: "Synthetic decision B?", context: "Context B", options: [{ title: "B" }], allowMultiple: true, allowFreeform: false }, +] +const padded = (): Params => ({ + question: "Synthetic batch", questions: questions(), context: "", options: [], + allowMultiple: false, allowFreeform: true, timeout: 0, displayMode: "inline", +}) + +// pi-ask-user 0.17 rejects ANY non-null entry-only field at batch top level. +// The actual installed normalizer was also reproduced outside CI; this contract +// needs no external package, model, credentials, or interactive user prompt. +function upstreamBatchCheck(params: Params) { + for (const field of ["context", "options", "allowMultiple", "allowFreeform"]) { + if (params[field] != null) throw new Error("Entry-only field at batch top level: " + field) + } + return params.questions +} + +async function guard() { + const bundle = convertClaudeToPi(plugin, options) + const extension = bundle.extensions.find((entry) => entry.name === "methodsmith-ask-user-guard.ts") + expect(extension).toBeDefined() + // Load the written TypeScript file as Pi does. Bun 1.3 rejects long data URLs. + const runtimeRoot = await fs.mkdtemp(path.join(os.tmpdir(), "pi-ask-user-guard-runtime-")) + const runtimePath = path.join(runtimeRoot, extension!.name) + await fs.writeFile(runtimePath, extension!.content) + const module = await import(runtimePath) + const handlers = new Map() + module.default({ on: (name: string, handler: Handler) => handlers.set(name, handler) }) + const call = (input: Params, id = "synthetic-call", toolName = "ask_user") => + handlers.get("tool_call")!({ toolName, toolCallId: id, input }) + const aborts = { count: 0 } + const end = (args: Params, isError: boolean, id = "synthetic-call") => + handlers.get("tool_execution_end")!({ toolName: "ask_user", toolCallId: id, args, isError }, + { abort: () => { aborts.count++ } }) + return { call, end, handlers, aborts } +} + +describe("Methodsmith Pi ask_user guard", () => { + test("ships only for Methodsmith, not unrelated converted plugins", () => { + expect(convertClaudeToPi(plugin, options).extensions.map((entry) => entry.name)) + .toContain("methodsmith-ask-user-guard.ts") + expect(convertClaudeToPi({ ...plugin, manifest: { ...plugin.manifest, name: "other-plugin" } }, options).extensions) + .toEqual([]) + }) + + test("reproduces the rejected padding, then preserves and unblocks the batch", async () => { + const input = padded() + expect(() => upstreamBatchCheck(input)).toThrow("Entry-only field") + const before = structuredClone(input.questions) + const g = await guard() + expect(g.call(input)).toBeUndefined() + expect(() => upstreamBatchCheck(input)).not.toThrow() + expect(input.questions).toEqual(before) + expect(input.question).toBe("Synthetic batch") + expect(input.timeout).toBe(0) + expect(input.displayMode).toBe("inline") + }) + + test("removes whitespace-only context and empty options", async () => { + const g = await guard() + const input = { ...padded(), context: " \n\t " } + expect(g.call(input)).toBeUndefined() + expect(input).not.toHaveProperty("context") + expect(input).not.toHaveProperty("options") + }) + + test("never changes per-question flags, options, context, or question text", async () => { + const g = await guard() + const input = padded() + const before = JSON.stringify(input.questions) + g.call(input) + expect(JSON.stringify(input.questions)).toBe(before) + }) + + for (const [field, value] of [ + ["context", "Meaningful shared context"], + ["options", [{ title: "Meaningful choice" }]], + ["allowMultiple", true], + ["allowFreeform", false], + ["context", 1], + ["options", "invalid"], + ] as const) { + test("blocks meaningful/invalid top-level " + field + " rather than discarding it", async () => { + const g = await guard() + const input = { ...padded(), [field]: value } + const result = g.call(input) as Block + expect(result?.block).toBe(true) + expect(result?.terminate).toBe(true) + expect(input[field]).toEqual(value) + expect(result?.reason).not.toContain("Meaningful shared context") + expect(result?.reason).not.toContain("Meaningful choice") + }) + } + + test("does not fill omitted entry flags or copy unsupported batch defaults into entries", async () => { + const g = await guard() + const input = { ...padded(), questions: [{ question: "A?" }, { question: "B?" }] } + expect(g.call(input)).toBeUndefined() + expect(input.questions).toEqual([{ question: "A?" }, { question: "B?" }]) + }) + + test("single-question parameters are untouched", async () => { + const g = await guard() + const input = { question: "A?", context: "Context", options: [{ title: "A" }], allowMultiple: true, allowFreeform: false } + const before = structuredClone(input) + expect(g.call(input)).toBeUndefined() + expect(input).toEqual(before) + }) + + test("other tools are untouched", async () => { + const g = await guard() + const input = padded() + const before = structuredClone(input) + expect(g.call(input, "other", "bash")).toBeUndefined() + expect(input).toEqual(before) + }) + + test("does not manufacture a batch from invalid question arrays", async () => { + const g = await guard() + for (const value of [[], [{ question: "A?" }], "bad", null]) { + const input = { questions: value, context: "Context" } + const before = structuredClone(input) + g.call(input, "invalid") + expect(input).toEqual(before) + } + }) + + test("blocks an unchanged failed ask_user retry, even after key order changes", async () => { + const g = await guard() + const input = padded() + expect(g.call(input)).toBeUndefined() + g.end(input, true) + const reordered = Object.fromEntries(Object.entries(structuredClone(input)).reverse()) + const result = g.call(reordered, "retry") as Block + expect(result?.block).toBe(true) + expect(result?.reason).toContain("Do not repeat") + expect(result?.reason).toContain("wait") + expect(result?.terminate).toBe(true) + }) + + test("permits a corrected failed call", async () => { + const g = await guard() + const input = padded() + g.call(input); g.end(input, true) + expect(g.call({ ...input, question: "Corrected synthetic batch" }, "corrected")).toBeUndefined() + }) + + test("cancellation/non-error results do not suppress later questions", async () => { + const g = await guard() + const input = padded() + g.call(input); g.end(input, false) + expect(g.call(structuredClone(input), "retry")).toBeUndefined() + }) + + test("fresh user input resets failed-call tracking", async () => { + const g = await guard() + const input = padded() + g.call(input); g.end(input, true) + g.handlers.get("input")!({}) + expect(g.call(structuredClone(input), "new-user-turn")).toBeUndefined() + }) + + test("session replacement resets failed-call tracking", async () => { + const g = await guard() + const input = padded() + g.call(input); g.end(input, true) + g.handlers.get("session_start")!({}) + expect(g.call(structuredClone(input), "new-session")).toBeUndefined() + }) + + test("stops repeated schema failures that never reach tool_call", async () => { + const g = await guard() + const invalid = { questions: [] } + g.end(invalid, true, "schema-failed-1") + expect(g.aborts.count).toBe(0) + g.end(structuredClone(invalid), true, "schema-failed-2") + expect(g.aborts.count).toBe(1) + }) + + test("distinct schema failures do not abort a corrected attempt", async () => { + const g = await guard() + g.end({ questions: [] }, true, "schema-failed-1") + g.end({ questions: [{ question: "A?" }] }, true, "schema-failed-2") + expect(g.aborts.count).toBe(0) + }) + + test("fresh input resets schema-failure repetition", async () => { + const g = await guard() + g.end({ questions: [] }, true, "schema-failed-1") + g.handlers.get("input")!({}) + g.end({ questions: [] }, true, "schema-failed-2") + expect(g.aborts.count).toBe(0) + }) + + test("records pre-execution validation failures without a preceding tool_call", async () => { + const g = await guard() + const input = { question: "Synthetic single question?" } + g.end(input, true, "preflight-failed") + const result = g.call(input, "retry") as Block + expect(result?.block).toBe(true) + }) +}) diff --git a/tests/pi-converter.test.ts b/tests/pi-converter.test.ts index 9333f817..aac12660 100644 --- a/tests/pi-converter.test.ts +++ b/tests/pi-converter.test.ts @@ -8,7 +8,7 @@ import type { ClaudePlugin } from "../src/types/claude" const fixtureRoot = path.join(import.meta.dir, "fixtures", "sample-plugin") describe("convertClaudeToPi", () => { - test("converts commands, skills, agents, and MCP servers without shipping a Pi extension", async () => { + test("converts Methodsmith commands, skills, agents, and MCP servers with the question-call guard", async () => { const plugin = await loadClaudePlugin(fixtureRoot) const bundle = convertClaudeToPi(plugin, { agentMode: "subagent", @@ -37,10 +37,11 @@ describe("convertClaudeToPi", () => { // commands-as-skills on other targets; Pi keeps it empty. expect(bundle.generatedSkills).toEqual([]) - // Pi installs now depend on the community pi-subagents and pi-ask-user extensions, - // so the converter emits no bundled extension. Legacy cleanup in the Pi writer - // removes any prior compound-engineering-compat.ts on upgrade. - expect(bundle.extensions).toEqual([]) + // Community extensions still own delegation and question UI. Methodsmith's + // narrow guard only normalizes harmless padding and stops failed-call loops; + // it does not revive the old tool-replacement compat extension. + expect(bundle.extensions.map((extension) => extension.name)).toEqual(["methodsmith-ask-user-guard.ts"]) + expect(bundle.extensions[0].content).toContain("normalizeBatchPadding") // MCP servers declared in plugin.json are translated to Pi's mcporter.json // shape so plugins with MCP wiring keep their backends after conversion. diff --git a/tests/pi-writer.test.ts b/tests/pi-writer.test.ts index 846f951a..78a8649a 100644 --- a/tests/pi-writer.test.ts +++ b/tests/pi-writer.test.ts @@ -98,6 +98,29 @@ describe("writePiBundle", () => { expect(agentsContent).toContain("BEGIN METHODSMITH PI TOOL MAP") expect(agentsContent).toContain("pi-subagents") expect(agentsContent).toContain("pi-ask-user") + expect(agentsContent).toContain("inside each question") + expect(agentsContent).toContain("Do not also pass those fields at the top level") + expect(agentsContent).toContain("never repeat the unchanged") + expect(agentsContent).toContain("A tool error or cancellation is not approval") + }) + + test("installs the Methodsmith question guard repeatably and preserves user extensions", async () => { + const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "pi-question-guard-")) + const outputRoot = path.join(tempRoot, "agent") + const userPath = path.join(outputRoot, "extensions", "user-extension.ts") + await fs.mkdir(path.dirname(userPath), { recursive: true }) + await fs.writeFile(userPath, "export default function userExtension() {}\n") + const plugin = await loadClaudePlugin(path.join(import.meta.dir, "..", "plugins", "methodsmith")) + const bundle = convertClaudeToPi(plugin, { agentMode: "subagent", inferTemperature: false, permissions: "none" }) + for (const _ of [1, 2]) await writePiBundle(outputRoot, bundle) + const guardPath = path.join(outputRoot, "extensions", "methodsmith-ask-user-guard.ts") + expect(await fs.readFile(guardPath, "utf8")).toContain("normalizeBatchPadding") + expect(await fs.readFile(userPath, "utf8")).toBe("export default function userExtension() {}\n") + const manifest = JSON.parse(await fs.readFile(path.join(outputRoot, "methodsmith", "install-manifest.json"), "utf8")) + expect(manifest.extensions).toContain("methodsmith-ask-user-guard.ts") + const ledger = JSON.parse(await fs.readFile(path.join(outputRoot, "methodsmith", "owned-files.json"), "utf8")) + expect(ledger.files["extensions/methodsmith-ask-user-guard.ts"]).toMatch(/^[0-9a-f]{64}$/) + expect(ledger.files["extensions/user-extension.ts"]).toBeUndefined() }) test("transforms Task calls in copied SKILL.md files", async () => {