repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

feat(the-system): approve existing core mutations once

4592030e6e57003fd35a5b47a72bdbd8c80bd901

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (8)

extensions/the-system/CHANGELOG.md

Modified
15 15 - Align mockup, artifact-slot, and board-proposal prompt metadata and tool rendering with Pi defaults.
16 16 - Keep board proposals and repeatable artifact slots available across clarification turns and compaction.
17 17 - Add a generally invocable vertical-slicing skill and require it for `/system exec`.
18 +- Replace unconditional core-document blocking with validated one-shot human approval.
19 20 ## 0.0.3

extensions/the-system/README.md

Modified
61 61 Issues intentionally have no status field.
62 62 Phases are project-wide operating epochs, not spec decomposition.
63 63 The optional config `currentPhase` selects one phase for prompt injection and the Pi footer.
64 -Existing phase amendments and current-phase transitions require human approval.
64 +Existing core documents and spec or phase files require one-shot human approval.
65 +Current-phase transitions require human approval.
65 66 Approved plans are immutable.
66 67 Create a new plan instead.
67 68 The config schema version is `0`; a mismatch fails with instructions to run `/system init`.

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

Modified
58 58 expect(t.session.systemPrompt).not.toContain("- system_slot:");
61 - it("shows humans a terse block while giving the agent the full proposal", async () => {
61 + it("requests one-shot approval for an existing core mutation", async () => {
62 62 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
63 63 t = await createTestSession({ extensions: [extensionPath] });
64 64 mkdirSync(path.join(t.cwd, ".git"));
65 65 mkdirSync(path.join(t.cwd, ".system"));
66 66 writeFileSync(path.join(t.cwd, ".system", "SYSTEM.md"), "Approved.\n");
68 - const toolCallId = "blocked-core-edit";
69 68 const blocked = await t.session.extensionRunner.emitToolCall({
70 69 type: "tool_call",
71 70 toolName: "edit",
72 - toolCallId,
71 + toolCallId: "blocked-core-edit",
73 72 input: {
74 73 path: ".system/SYSTEM.md",
75 74 edits: [{ oldText: "Approved.", newText: "Human-approved." }],
78 - expect(blocked).toEqual({
79 - block: true,
80 - reason:
81 - "The System blocked mutation of human-owned core .system/SYSTEM.md.",
82 - });
84 - const context = await t.session.extensionRunner.emitContext([
85 - {
86 - role: "toolResult",
87 - toolCallId,
88 - toolName: "edit",
89 - content: [{ type: "text", text: blocked?.reason }],
90 - isError: true,
91 - timestamp: Date.now(),
92 - },
77 + expect(blocked).toBeUndefined();
78 + const [approval] = t.events.uiCallsFor("select");
79 + expect(approval?.args).toEqual([
80 + "The System ownership approval",
81 + [
82 + "Approve once: edit .system/SYSTEM.md",
83 + "Deny: keep .system/SYSTEM.md unchanged",
84 + ],
94 - expect(context[0].content[0].text).toContain(
95 - "Report this to the human at the end of the task",
96 - );
97 - expect(context[0].content[0].text).toContain(
98 - "```text\nHuman-approved.\n```",
99 - );

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 () => {
155 + it("requires one-shot approval for each existing core mutation", async () => {
156 156 const project = root();
157 - const result = await preflightFileMutation(
157 + const input = {
158 + path: "./.system/SYSTEM.md",
159 + edits: [{ oldText: "Approved.", newText: "Human-approved." }],
160 + };
161 + let approvals = 0;
162 + const ui = {
163 + hasUI: true,
164 + select: async (title: string, items: string[]) => {
165 + approvals += 1;
166 + assert.equal(title, "The System ownership approval");
167 + assert.deepEqual(items, [
168 + "Approve once: edit .system/SYSTEM.md",
169 + "Deny: keep .system/SYSTEM.md unchanged",
170 + ]);
171 + return items[0];
172 + },
173 + };
174 + assert.equal(
175 + await preflightFileMutation(project, "edit", input, ui),
176 + undefined,
177 + );
178 + assert.equal(
179 + await preflightFileMutation(project, "edit", input, ui),
180 + undefined,
181 + );
182 + assert.equal(approvals, 2);
184 + for (const [decision, message] of [
185 + ["deny", /denied/],
186 + ["cancel", /cancelled/],
187 + ] as const) {
188 + const result = await preflightFileMutation(project, "edit", input, {
189 + hasUI: true,
190 + select: async (_title, items) =>
191 + decision === "deny" ? items[1] : undefined,
192 + });
193 + assert.equal(result?.block, true);
194 + assert.match(result?.reason ?? "", message);
196 + const unavailable = await preflightFileMutation(
158 197 project,
159 198 "edit",
199 + input,
200 + approval(false),
201 + );
202 + assert.equal(unavailable?.block, true);
203 + assert.match(unavailable?.reason ?? "", /interactive UI/);
205 + const oversized = await preflightFileMutation(
206 + project,
207 + "write",
208 + { path: ".system/SYSTEM.md", content: "x".repeat(CORE_BYTE_LIMIT + 1) },
161 - path: "./.system/SYSTEM.md",
162 - edits: [{ oldText: "Approved.", newText: "Human-approved." }],
210 + hasUI: true,
211 + select: async () => {
212 + throw new Error("unexpected approval");
213 + },
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/,
216 + assert.equal(oversized?.block, true);
217 + assert.match(oversized?.reason ?? "", /core limit/);
194 220 it("activates an existing phase only after confirmation", async () => {

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

Modified
118 118 assert.match(prompt, /migrate existing bundles to schema 0/);
121 + it("keeps MISSION outside phase authoring", () => {
122 + assert.match(systemPromptFor("phase", ""), /Do not mutate MISSION/);
123 + });
121 125 it("requires exec to deliver complete vertical slices", () => {
122 126 const prompt = systemPromptFor("exec", "");
123 127 assert.match(prompt, /Load the vertical-slices skill/);

extensions/the-system/index.ts

Modified
19 19 export default function registerTheSystem(pi: ExtensionAPI): void {
20 20 let generation = 0;
21 21 let warningNotified = false;
22 - const agentBlockReasons = new Map<string, string>();
23 22 let artifactSlotRunActive = false;
24 23 let artifactSlotUsed = false;
25 24 let boardAssessmentRunActive = false;
112 111 deactivateArtifactSlot();
113 112 deactivateBoardAssessment();
114 113 bundleMigrationRunActive = false;
115 - agentBlockReasons.clear();
116 114 const ticket = ++generation;
117 115 warningNotified = false;
118 116 mockup.remember(ctx);
127 125 pi.on("session_shutdown", (_event, ctx) => {
128 126 generation++;
129 127 warningNotified = false;
130 - agentBlockReasons.clear();
131 128 artifactSlotRunActive = false;
132 129 artifactSlotUsed = false;
133 130 boardAssessmentRunActive = false;
153 150 void syncRuntimeIndicator(ctx, generation).catch((error) =>
154 151 console.error("The System status refresh failed:", error),
156 - agentBlockReasons.clear();
157 153 mockup.agentSettled(ctx);
158 154 if (artifactSlotRunActive && artifactSlotUsed) deactivateArtifactSlot();
159 155 if (boardAssessmentRunActive && board.assessmentComplete())
160 156 deactivateBoardAssessment();
161 157 bundleMigrationRunActive = false;
163 - pi.on("context", (event) => {
164 - let changed = false;
165 - const messages = event.messages.map((message) => {
166 - if (message.role !== "toolResult") return message;
167 - const reason = agentBlockReasons.get(message.toolCallId);
168 - if (!reason) return message;
169 - changed = true;
170 - return {
171 - ...message,
172 - content: [{ type: "text" as const, text: reason }],
173 - };
174 - });
175 - return changed ? { messages } : undefined;
176 - });
177 159 pi.on("tool_call", async (event, ctx) => {
179 161 !isToolCallEventType("write", event) &&
189 171 const result = isToolCallEventType("write", event)
190 172 ? await preflightFileMutation(ctx.cwd, "write", event.input, ui, options)
191 173 : await preflightFileMutation(ctx.cwd, "edit", event.input, ui, options);
192 - if (result?.agentReason)
193 - agentBlockReasons.set(event.toolCallId, result.agentReason);
194 174 return result ? { block: true, reason: result.reason } : undefined;

extensions/the-system/system-prompts.ts

Modified
30 30 Plans reference one spec and may depend on earlier plans for the same spec.
31 31 Issues may reference zero or more specs and have no status field.
32 32 Approved plans are immutable outside an explicitly approved /system init bundle migration; otherwise create a new artifact.
33 -Mutating existing files in phase and spec bundles requires human approval.
33 +Mutating existing core files or files in phase and spec bundles requires one-shot human approval.
34 34 The optional config currentPhase ID selects the project-wide operating phase.
35 35 Changing currentPhase requires explicit human confirmation.
36 36 Keep prose terse, minimal, and essential.

extensions/the-system/system.ts

Modified
130 130 type MutationKind = "write" | "edit";
131 131 type MutationInput = WriteToolInput | EditToolInput;
132 -type GateResult =
133 - | Readonly<{ block: true; reason: string; agentReason?: string }>
134 - | undefined;
132 +type GateResult = Readonly<{ block: true; reason: string }> | undefined;
135 133 export type GovernanceUI = Readonly<{
136 134 hasUI: boolean;
137 135 select(title: string, items: string[]): Promise<string | undefined>;
145 143 const posixRelative = (root: string, target: string) =>
146 144 path.relative(root, target).split(path.sep).join("/");
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}`;
159 -};
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 - ]),
181 - ]
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");
195 -};
145 +const blocked = (reason: string): GateResult => ({ block: true, reason });
196 146 const diagnosticsReason = (diagnostics: readonly Diagnostic[]) => {
197 147 const shown = diagnostics
198 148 .slice(0, 3)
237 187 (input as EditToolInput).edits,
190 +const approveOwnedMutation = async (
191 + relative: string,
192 + kind: MutationKind,
193 + ui: GovernanceUI,
194 +): Promise<GateResult> => {
195 + if (!ui.hasUI)
196 + return blocked(
197 + `The System blocked existing human-owned ${relative}: interactive UI is unavailable.`,
198 + );
199 + const approve = `Approve once: ${kind} ${relative}`;
200 + const deny = `Deny: keep ${relative} unchanged`;
201 + const decision = await ui.select("The System ownership approval", [
202 + approve,
203 + deny,
204 + ]);
205 + if (decision === approve) return undefined;
206 + return blocked(
207 + decision === deny
208 + ? `The System ownership approval was denied for ${relative}.`
209 + : `The System ownership approval was cancelled for ${relative}.`,
210 + );
240 212 const projectPrefix = (root: string) =>
241 213 parseSystemConfig(readFileSync(path.join(root, CONFIG_PATH), "utf8")).prefix;
462 434 if (relative === CONFIG_PATH)
463 435 return preflightCurrentPhase(root, target, kind, input, ui);
464 436 if (CORE_PATHS.has(relative)) {
465 - if (targetStats) {
466 - const reason = `The System blocked mutation of human-owned core ${relative}.`;
467 - return blocked(reason, coreMutationReason(relative, kind, input));
468 - }
469 - if (kind === "edit")
437 + if (targetStats && !targetStats.isFile())
438 + return blocked(`The System expected a regular owned file at ${relative}.`);
439 + let content: string;
440 + try {
441 + content = candidateContent(target, kind, input);
442 + } catch (error) {
470 443 return blocked(
471 - `The System requires write, not edit, to create missing core ${relative}.`,
444 + `The System candidate validation failed: ${error instanceof Error ? error.message : String(error)}`,
473 - return undefined;
447 + if (Buffer.byteLength(content, "utf8") > CORE_BYTE_LIMIT)
448 + return blocked(
449 + `The System candidate validation failed: ${relative} exceeds the ${CORE_BYTE_LIMIT}-byte core limit.`,
450 + );
451 + return targetStats
452 + ? approveOwnedMutation(relative, kind, ui)
453 + : undefined;
475 455 const location = governedDocumentPath(relative);
476 456 if (!location)
563 543 if (resolved.metadata.type !== "spec" && resolved.metadata.type !== "phase")
564 544 return undefined;
565 - if (!ui.hasUI)
566 - return blocked(
567 - `The System blocked existing human-owned ${relative}: interactive UI is unavailable.`,
568 - );
569 - const approve = `Approve once: ${kind} ${relative}`;
570 - const deny = `Deny: keep ${relative} unchanged`;
571 - const decision = await ui.select("The System ownership approval", [
572 - approve,
573 - deny,
574 - ]);
575 - if (decision === approve) return undefined;
576 - return blocked(
577 - decision === deny
578 - ? `The System ownership approval was denied for ${relative}.`
579 - : `The System ownership approval was cancelled for ${relative}.`,
580 - );
545 + return approveOwnedMutation(relative, kind, ui);