repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

fix(the-system): separate blocked edit reporting

e08c6a67825b66dbbf1e95739592fca15d420d0b

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (5)

CHANGELOG.md

Modified
68 68 - Make `/system init` deterministic with confirmation; it creates schema 0 config, board state, plural artifact directories, and core files directly
69 69 - Add an optional project title to The System config; `/system init` writes it from the project directory name and rendered books use it
70 70 - Remove The System advisory shell mutation guard; governed confirmation remains on `write` and `edit`
71 +- Show humans a terse error for blocked System core mutations while giving the agent the full copyable edit proposal
71 72 - Seed `/system init` core files with concise SYSTEM, MISSION, and RULES role guidance while preserving existing core content on rerun
72 73 - Fix `/system init` so rerunning in an initialized project reuses the existing prefix instead of asking again
73 74 - Fix exact `/system` subcommands such as `doctor` and `book` so autocomplete does not consume Enter

extensions/the-system/__tests__/harness.test.ts

Modified
1 +import { mkdirSync, writeFileSync } from "node:fs";
1 2 import path from "node:path";
2 3 import { afterEach, describe, expect, it, vi } from "vitest";
3 4 import { createTestSession, type TestSession } from "../../../test/harness";
49 50 expect(t.session.getActiveToolNames()).not.toContain("system_slot");
50 51 expect(t.session.systemPrompt).not.toContain("- system_slot:");
54 + it("shows humans a terse block while giving the agent the full proposal", async () => {
55 + const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
56 + t = await createTestSession({ extensions: [extensionPath] });
57 + mkdirSync(path.join(t.cwd, ".git"));
58 + mkdirSync(path.join(t.cwd, ".system"));
59 + writeFileSync(path.join(t.cwd, ".system", "SYSTEM.md"), "Approved.\n");
61 + const toolCallId = "blocked-core-edit";
62 + const blocked = await t.session.extensionRunner.emitToolCall({
63 + type: "tool_call",
64 + toolName: "edit",
65 + toolCallId,
66 + input: {
67 + path: ".system/SYSTEM.md",
68 + edits: [{ oldText: "Approved.", newText: "Human-approved." }],
69 + },
70 + });
71 + expect(blocked).toEqual({
72 + block: true,
73 + reason:
74 + "The System blocked mutation of human-owned core .system/SYSTEM.md.",
75 + });
77 + const context = await t.session.extensionRunner.emitContext([
78 + {
79 + role: "toolResult",
80 + toolCallId,
81 + toolName: "edit",
82 + content: [{ type: "text", text: blocked?.reason }],
83 + isError: true,
84 + timestamp: Date.now(),
85 + },
86 + ]);
87 + expect(context[0].content[0].text).toContain(
88 + "Report this to the human at the end of the task",
89 + );
90 + expect(context[0].content[0].text).toContain(
91 + "```text\nHuman-approved.\n```",
92 + );
93 + });

extensions/the-system/__tests__/system.test.ts

Modified
154 154 describe("runtime bundle governance", () => {
155 + it("reports a copyable proposal for blocked core edits", async () => {
156 + const project = root();
157 + const result = await preflightFileMutation(
158 + project,
159 + "edit",
161 + path: "./.system/SYSTEM.md",
162 + edits: [{ oldText: "Approved.", newText: "Human-approved." }],
163 + },
164 + approval(),
165 + );
166 + assert.equal(result?.block, true);
167 + assert.equal(
168 + result?.reason,
169 + "The System blocked mutation of human-owned core .system/SYSTEM.md.",
170 + );
171 + assert.match(
172 + result?.agentReason ?? "",
173 + /Report this to the human at the end of the task/,
174 + );
175 + assert.match(
176 + result?.agentReason ?? "",
177 + /Show the human this proposal and ask them to apply it themselves/,
178 + );
179 + assert.ok(
180 + result?.agentReason?.includes("### Proposed edit: .system/SYSTEM.md"),
181 + );
182 + assert.ok(
183 + result?.agentReason?.includes("Replace:\n\n```text\nApproved.\n```"),
184 + );
185 + assert.ok(
186 + result?.agentReason?.includes("With:\n\n```text\nHuman-approved.\n```"),
187 + );
188 + assert.doesNotMatch(
189 + result?.agentReason ?? "",
190 + /HUMAN ACTION PROPOSAL|BEGIN|END/,
191 + );
192 + });
155 194 it("activates an existing phase only after confirmation", async () => {
156 195 const project = root();
157 196 write(

extensions/the-system/index.ts

Modified
18 18 export default function registerTheSystem(pi: ExtensionAPI): void {
19 19 let generation = 0;
20 20 let warningNotified = false;
21 + const agentBlockReasons = new Map<string, string>();
21 22 const mockup = createMockupRuntime();
22 23 const artifactSlot = createArtifactSlotTool();
23 24 const board = createBoardRuntime();
88 89 deactivateArtifactSlot();
89 90 deactivateBoardAssessment();
90 91 bundleMigrationRunActive = false;
92 + agentBlockReasons.clear();
91 93 const ticket = ++generation;
92 94 warningNotified = false;
93 95 mockup.remember(ctx);
102 104 pi.on("session_shutdown", (_event, ctx) => {
103 105 generation++;
104 106 warningNotified = false;
107 + agentBlockReasons.clear();
105 108 artifactSlotRunActive = false;
106 109 boardAssessmentRunActive = false;
107 110 bundleMigrationRunActive = false;
126 129 void syncRuntimeIndicator(ctx, generation).catch((error) =>
127 130 console.error("The System status refresh failed:", error),
132 + agentBlockReasons.clear();
129 133 mockup.agentSettled(ctx);
130 134 if (artifactSlotRunActive) deactivateArtifactSlot();
131 135 if (boardAssessmentRunActive) deactivateBoardAssessment();
132 136 bundleMigrationRunActive = false;
138 + pi.on("context", (event) => {
139 + let changed = false;
140 + const messages = event.messages.map((message) => {
141 + if (message.role !== "toolResult") return message;
142 + const reason = agentBlockReasons.get(message.toolCallId);
143 + if (!reason) return message;
144 + changed = true;
145 + return {
146 + ...message,
147 + content: [{ type: "text" as const, text: reason }],
148 + };
149 + });
150 + return changed ? { messages } : undefined;
151 + });
134 152 pi.on("tool_call", async (event, ctx) => {
136 154 !isToolCallEventType("write", event) &&
142 160 hasUI: ctx.hasUI,
143 161 select: (title: string, items: string[]) => ctx.ui.select(title, items),
145 - if (isToolCallEventType("write", event))
146 - return preflightFileMutation(ctx.cwd, "write", event.input, ui, {
147 - bundleMigration: bundleMigrationRunActive,
148 - });
149 - if (isToolCallEventType("edit", event))
150 - return preflightFileMutation(ctx.cwd, "edit", event.input, ui, {
151 - bundleMigration: bundleMigrationRunActive,
152 - });
163 + const options = { bundleMigration: bundleMigrationRunActive };
164 + const result = isToolCallEventType("write", event)
165 + ? await preflightFileMutation(ctx.cwd, "write", event.input, ui, options)
166 + : await preflightFileMutation(ctx.cwd, "edit", event.input, ui, options);
167 + if (result?.agentReason)
168 + agentBlockReasons.set(event.toolCallId, result.agentReason);
169 + return result ? { block: true, reason: result.reason } : undefined;
155 172 pi.registerTool(mockup.tool);

extensions/the-system/system.ts

Modified
130 130 type MutationKind = "write" | "edit";
131 131 type MutationInput = WriteToolInput | EditToolInput;
132 -type GateResult = Readonly<{ block: true; reason: string }> | undefined;
132 +type GateResult =
133 + | Readonly<{ block: true; reason: string; agentReason?: string }>
134 + | undefined;
133 135 export type GovernanceUI = Readonly<{
134 136 hasUI: boolean;
135 137 select(title: string, items: string[]): Promise<string | undefined>;
143 145 const posixRelative = (root: string, target: string) =>
144 146 path.relative(root, target).split(path.sep).join("/");
145 -const blocked = (reason: string): GateResult => ({ block: true, reason });
147 +const blocked = (reason: string, agentReason?: string): GateResult => ({
148 + block: true,
149 + reason,
150 + agentReason,
151 +});
152 +const markdownCodeBlock = (text: string): string => {
153 + const longestBacktickRun = Math.max(
154 + 0,
155 + ...(text.match(/`+/g) ?? []).map((run) => run.length),
156 + );
157 + const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
158 + return `${fence}text\n${text}${text.endsWith("\n") ? "" : "\n"}${fence}`;
160 +const coreMutationReason = (
161 + relative: string,
162 + kind: MutationKind,
163 + input: MutationInput,
164 +): string => {
165 + const proposal =
166 + kind === "edit"
167 + ? [
168 + `### Proposed edit: ${relative}`,
169 + "",
170 + ...(input as EditToolInput).edits.flatMap((edit, index, edits) => [
171 + ...(edits.length > 1 ? [`#### Edit ${index + 1}`, ""] : []),
172 + "Replace:",
173 + "",
174 + markdownCodeBlock(edit.oldText),
175 + "",
176 + "With:",
177 + "",
178 + markdownCodeBlock(edit.newText),
179 + ...(index < edits.length - 1 ? ["", "---", ""] : []),
180 + ]),
182 + : [
183 + `### Proposed write: ${relative}`,
184 + "",
185 + markdownCodeBlock((input as WriteToolInput).content),
186 + ];
187 + return [
188 + `The System blocked mutation of human-owned core ${relative}.`,
189 + "",
190 + "Report this to the human at the end of the task instead of retrying it.",
191 + "Show the human this proposal and ask them to apply it themselves:",
192 + "",
193 + ...proposal,
194 + ].join("\n");
146 196 const diagnosticsReason = (diagnostics: readonly Diagnostic[]) => {
147 197 const shown = diagnostics
148 198 .slice(0, 3)
412 462 if (relative === CONFIG_PATH)
413 463 return preflightCurrentPhase(root, target, kind, input, ui);
414 464 if (CORE_PATHS.has(relative)) {
415 - if (targetStats)
416 - return blocked(
417 - `The System blocked mutation of human-owned core ${relative}.`,
418 - );
465 + if (targetStats) {
466 + const reason = `The System blocked mutation of human-owned core ${relative}.`;
467 + return blocked(reason, coreMutationReason(relative, kind, input));
419 469 if (kind === "edit")
420 470 return blocked(
421 471 `The System requires write, not edit, to create missing core ${relative}.`,