repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

fix(the-system): load mockup guidance on demand and scope scripts

7e1f70cdae02102e36b50b3601bb4937e28f44c0

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (10)

extensions/the-system/README.md

Modified
77 77 Projects initialized during a live session require `/reload` before those format skills become available.
79 79 The generic `mockup` tool remains available.
80 +Its active prompt metadata requires loading the tool-owned [mockup HTML guidance](guidance/mockup-html/SKILL.md) before creating or revising fragments.
81 +The guidance stays outside automatic skill discovery and documents the ShadowRoot runtime, interaction support, target fidelity, accessibility, and network assumptions.

extensions/the-system/__e2e__/mockup.spec.ts

Modified
1 +import { readFileSync } from "node:fs";
1 2 import { expect, test } from "@playwright/test";
2 3 import {
3 4 type MockupResult,
8 9 let server: MockupServer | undefined;
11 +const interactiveFragment = readFileSync(
12 + new URL("../guidance/mockup-html/SKILL.md", import.meta.url),
13 + "utf8",
14 +).match(/```html\n([\s\S]*?)```/)?.[1];
15 +if (!interactiveFragment)
16 + throw new Error("Missing interactive mockup skill example");
10 18 test.afterEach(() => {
11 19 if (!server) return;
12 20 server.result.catch(() => undefined);
27 35 id: "dense",
28 36 label: "Dense",
29 37 description: "Compact layout",
30 - html: '<section><button id="fragment-action">Dense content</button></section>',
38 + html: `${interactiveFragment}<script type="application/json">{"count":0}</script>`,
33 41 id: "calm",
34 42 label: "Calm",
35 - html: "<section>Calm content</section>",
43 + html: interactiveFragment,
52 60 ).toBeVisible();
53 61 await expect(page.getByText("Which layout works?")).toBeVisible();
54 62 await expect(page.locator(".option-card")).toHaveCount(2);
55 - await expect(page.getByText("Dense content")).toBeVisible();
63 + const denseCounter = page.locator('[data-fragment="dense"]');
64 + await expect(
65 + denseCounter.locator('script[type="application/json"]'),
66 + ).toHaveJSProperty("textContent", '{"count":0}');
67 + const output = denseCounter.locator("output");
68 + await expect(output).toHaveText("0");
69 + await denseCounter.getByRole("button", { name: "Increment" }).click();
70 + await expect(output).toHaveText("1");
71 + await expect(page.locator('[data-fragment="calm"] output')).toHaveText("0");
72 + expect(
73 + await page.evaluate(() =>
74 + [...document.scripts].some((script) =>
75 + Object.hasOwn(script, "mockupRoot"),
76 + ),
77 + ),
78 + ).toBe(false);
79 + await expect
80 + .poll(() =>
81 + denseCounter.locator(".counter").evaluate((element) => ({
82 + shadow: element.getRootNode() instanceof ShadowRoot,
83 + reviewFrameControls:
84 + document.querySelectorAll("#accept, #iterate").length,
85 + })),
86 + )
87 + .toEqual({ shadow: true, reviewFrameControls: 2 });
57 89 await page.locator('[data-select-option="dense"]').check();
58 90 await page.locator("#global-notes").fill("keep dense");
119 151 id: "dense-v2",
120 152 label: "Dense revision",
121 - html: "<section>Revised dense content</section>",
153 + html: interactiveFragment,
126 158 page.getByRole("heading", { name: "Layout revision" }),
127 159 ).toBeVisible();
128 160 expect(page.url()).toBe(stableUrl);
129 - await expect(page.getByText("Revised dense content")).toBeVisible();
161 + const revised = page.locator('[data-fragment="dense-v2"]');
162 + await revised.getByRole("button", { name: "Increment" }).click();
163 + await expect(revised.locator("output")).toHaveText("1");
131 165 await page.locator("#accept").click();
132 166 await expect(page.locator("#progress-title")).toHaveText(
135 169 const second = await secondSubmission;
136 170 expect(second).toMatchObject({
137 171 action: "accept",
138 - selected: [],
172 + selected: ["dense-v2"],
139 173 notes: "",
140 174 annotations: [],

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

Modified
19 19 expect(t.session.extensionRunner.extensions).toHaveLength(1);
20 20 expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
21 + const guidancePath = path.resolve(
22 + import.meta.dirname,
23 + "../guidance/mockup-html/SKILL.md",
24 + );
25 + expect(t.session.systemPrompt).toContain(
26 + `Before creating or revising mockups, read \`${guidancePath}\`.`,
27 + );
28 + expect(
29 + t.session.resourceLoader
30 + .getSkills()
31 + .skills.some((skill) => skill.name === "mockup-html"),
32 + ).toBe(false);
33 + expect(t.session.systemPrompt).not.toContain(
34 + "Rich interactions, scripts, and animations are allowed",
35 + );
36 + t.session.setActiveToolsByName(
37 + t.session.getActiveToolNames().filter((name) => name !== "mockup"),
38 + );
39 + expect(t.session.systemPrompt).not.toContain(guidancePath);
23 42 it("keeps system_slot through clarification and cancels it on the next lifecycle", async () => {

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

Modified
100 100 describe("mockup tool contract", () => {
101 - it("uses concise prompt metadata without duplicating its description", () => {
101 + it("activates concise prompt metadata and tool-owned guidance", async () => {
102 102 const tool = createMockupRuntime({ openBrowser: false }).tool;
103 + const guidancePath = path.resolve(
104 + import.meta.dirname,
105 + "../guidance/mockup-html/SKILL.md",
106 + );
104 108 assert.strictEqual(tool.label, "mockup");
105 109 assert.strictEqual(tool.promptSnippet, "Review HTML mockups in a browser");
106 110 assert.notStrictEqual(tool.promptSnippet, tool.description);
107 111 assert.deepStrictEqual(tool.promptGuidelines, [
108 112 "Use mockup when visual comparison beats prose for UI, layout, styling, or interaction decisions.",
109 - "Pass HTML fragments only; never include <!doctype>, <html>, <head>, or <body>.",
110 - "Provide 1-4 options; one option is valid when reviewing a single design.",
111 - "The tool owns browser review and feedback. Do not ask the user to repeat its result in chat.",
112 - "On iterate, revise the fragments and call mockup again. On accept, continue the design unless feedback requires another iteration.",
113 + `Before creating or revising mockups, read \`${guidancePath}\`.`,
115 + assert.match(await readFile(guidancePath, "utf8"), /name: mockup-html/);
116 + assert.strictEqual(tool.parameters.properties.options.minItems, 1);
117 + assert.strictEqual(tool.parameters.properties.options.maxItems, 4);
118 + assert.strictEqual(
119 + tool.parameters.properties.options.items.properties.html.description,
120 + "HTML fragment; scripts are allowed.",
121 + );
116 124 it("renders a compact call and reserves option details for expansion", () => {

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

Modified
54 54 assert.match(skill, /name: vertical-slices/);
55 55 assert.match(
56 56 skill,
57 - /vertical slices, vertical slicing, a walking skeleton/,
57 + /description: "Use when planning or implementing vertical slices, walking skeletons, or thin end-to-end increments\."/,
59 59 assert.match(
60 60 skill,
61 - /complete observable increments across required layers/,
61 + /A slice is complete only when its behavior is integrated, observable, tested, and freshly verified/,
63 63 assert.doesNotMatch(skill, /The System|\.system/);
66 + it("keeps valid mockup guidance outside automatic skill discovery", () => {
67 + const guidance = readFileSync(
68 + path.join(root, "guidance", "mockup-html", "SKILL.md"),
69 + "utf8",
70 + );
71 + const frontmatter = guidance.split("---", 3)[1] ?? "";
72 + assert.match(frontmatter, /\nname: mockup-html\n/);
73 + assert.match(
74 + frontmatter,
75 + /description: "Use before creating or revising HTML fragments for the mockup tool's browser review\."/,
76 + );
77 + assert.match(
78 + guidance,
79 + /Each option is rendered in its own open `ShadowRoot`/,
80 + );
81 + assert.match(guidance, /document\.currentScript\.mockupRoot/);
82 + assert.match(
83 + guidance,
84 + /Rich interactions, scripts, and animations are allowed/,
85 + );
86 + assert.match(guidance, /runtime does not claim to sandbox or block/);
87 + assert.match(
88 + readFileSync(path.join(root, "README.md"), "utf8"),
89 + /\[mockup HTML guidance\]\(guidance\/mockup-html\/SKILL\.md\)/,
90 + );
91 + assert.ok(!packageJson().pi?.skills);
92 + });
66 94 it("keeps System instructions internal to the /system command", () => {
67 95 const prompts = readFileSync(path.join(root, "system-prompts.ts"), "utf8");
68 96 assert.match(prompts, /The System document contract/);

extensions/the-system/guidance/mockup-html/SKILL.md

Added
new file mode 100644
1 +---
2 +name: mockup-html
3 +description: "Use before creating or revising HTML fragments for the mockup tool's browser review."
4 +---
6 +# Mockup HTML
8 +Create decision-focused fragments that make the current visual or interaction question cheap to answer.
9 +Prefer one representative state with realistic content over a broad product tour.
10 +State the target platform, viewport, input assumptions, and any intentional fidelity limits in the option description or visible mockup.
12 +## Authoring contract
14 +- Return an HTML fragment, never `<!doctype>`, `<html>`, `<head>`, or `<body>`.
15 +- Supply one to four options with stable IDs.
16 +- One option is enough to review a single design; use multiple options only when comparison helps the decision.
17 +- Preserve the review frame's selection, notes, annotation, iterate, accept, and stop controls; the fragment supplies only the design under review.
18 +- Use realistic labels, data, lengths, empty/error states, and constraints relevant to the decision.
19 +- Rich interactions, scripts, and animations are allowed when they help answer the question.
20 +- Avoid frameworks and large boilerplate by default, not useful interaction.
21 +- Prefer self-contained HTML, CSS, assets, and data.
22 + Do not call external services unless the human approved that dependency.
23 + The runtime does not claim to sandbox or block fragment network access.
24 +- Preserve semantic controls, labels, keyboard focus, readable contrast, and zoom.
25 + When animation exists, provide a useful `prefers-reduced-motion: reduce` state.
27 +## Runtime boundary
29 +Each option is rendered in its own open `ShadowRoot`, not an iframe.
30 +Scope styles to the fragment and use `:host` for root defaults; document-level selectors such as `html`, `body`, and `:root` do not describe the fragment host.
31 +Do not query the review page globally.
32 +Use classic inline scripts and wrap each script in an IIFE.
33 +The runtime executes revived scripts in the page with a per-script `mockupRoot` reference to their fragment's ShadowRoot.
34 +Capture `document.currentScript.mockupRoot` synchronously before callbacks, then query only within that root.
35 +This avoids relying on `document.currentScript` inside a shadow tree, where it is null.
36 +Scripts are revived after insertion, including scripts added during revisions.
38 +```html
39 +<section class="counter">
40 + <style>
41 + :host { color-scheme: light dark; font: 14px/1.4 system-ui, sans-serif; }
42 + .counter { display: flex; align-items: center; gap: 0.75rem; }
43 + button:focus-visible { outline: 3px solid currentColor; outline-offset: 2px; }
44 + </style>
45 + <button type="button">Increment</button>
46 + <output aria-live="polite">0</output>
47 + <script>
48 + (() => {
49 + const root = document.currentScript.mockupRoot;
50 + const button = root.querySelector("button");
51 + const output = root.querySelector("output");
52 + button.addEventListener("click", () => {
53 + output.value = String(Number(output.value) + 1);
54 + });
55 + })();
56 + </script>
57 +</section>
58 +```
60 +## Target fidelity
62 +For other targets, identify actual display, input, and layout constraints first.
63 +HTML is the presentation medium, not permission to invent unsupported behavior.
65 +### Terminal and TUI
67 +Model cells and columns rather than browser pixels.
68 +Use monospace metrics, realistic terminal widths, keyboard navigation, and only colors and glyphs supported by the target terminal.
69 +Do not imply blur, freeform overlap, pointer-only controls, proportional typography, or other effects the terminal cannot render.
71 +### Web
73 +Use responsive layout at representative narrow and wide widths.
74 +Keep semantic HTML, native controls, keyboard operation, and content reflow visible in the fragment.
75 +Do not fake platform behavior that the intended browser cannot provide.
77 +### Mobile
79 +Review at a named narrow viewport and account for touch targets, safe areas, software-keyboard pressure, and one-handed reach where relevant.
80 +Do not rely on hover.
81 +Test long content and compact widths without silently converting the design into a desktop page.
83 +### Desktop
85 +Name the target operating system and representative window size.
86 +Follow its window, menu, dialog, shortcut, focus, keyboard, and pointer conventions.
87 +Show resize behavior when it affects the decision.
89 +## Review loop
91 +Ask one exact visual or interaction question.
92 +On `iterate`, apply the selected option, notes, and annotations without discarding useful behavior or target assumptions, then submit revised fragments.
93 +On `accept`, continue with the accepted direction unless the feedback explicitly requires another review.
94 +Do not ask the human to repeat feedback already captured by the review frame.

extensions/the-system/index.ts

Modified
63 63 if (artifactSlotRunActive) deactivateArtifactSlot();
64 64 if (boardProposalRunActive) deactivateBoardProposal();
66 + const notifyFailure = (
67 + ctx: ExtensionContext,
68 + label: string,
69 + error: unknown,
70 + ) => {
71 + if (ctx.hasUI)
72 + ctx.ui.notify(
73 + `${label}: ${error instanceof Error ? error.message : String(error)}`,
74 + "warning",
75 + );
76 + };
67 78 const syncRuntimeIndicator = async (
68 79 ctx: ExtensionContext,
117 128 const timer = setTimeout(() => {
118 129 if (ticket === generation)
119 130 void syncRuntimeIndicator(ctx, ticket).catch((error) =>
120 - console.error("The System startup check failed:", error),
131 + notifyFailure(ctx, "The System startup check failed", error),
122 133 }, 0);
123 134 timer.unref?.();
135 146 pi.on("before_agent_start", async (event, ctx) => {
136 147 void syncRuntimeIndicator(ctx, generation).catch((error) =>
137 - console.error("The System startup check failed:", error),
148 + notifyFailure(ctx, "The System startup check failed", error),
139 150 mockup.agentWorking(ctx);
140 151 const { composeSystemPrompt } = await import("./system.js");
149 160 pi.on("agent_settled", (_event, ctx) => {
150 161 void syncRuntimeIndicator(ctx, generation).catch((error) =>
151 - console.error("The System status refresh failed:", error),
162 + notifyFailure(ctx, "The System status refresh failed", error),
153 164 mockup.agentSettled(ctx);
154 165 if (artifactSlotRunActive && artifactSlotUsed) deactivateArtifactSlot();

extensions/the-system/mockup-tool.ts

Modified
28 28 const DESCRIPTION =
29 29 "Show HTML-fragment mockups in a browser for visual review. Returns accept or iterate, selected option IDs, notes, and annotations.";
30 +const MOCKUP_GUIDANCE_PATH = path.join(
31 + import.meta.dirname,
32 + "guidance",
33 + "mockup-html",
34 + "SKILL.md",
35 +);
30 36 const CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
31 37 const CACHE_LIMIT_BYTES = 256 * 1024 * 1024;
52 58 html: Type.String({
53 - description:
54 - "HTML fragment for this mockup option. Do not include <!doctype>, <html>, <head>, or <body>. Scripts are allowed.",
59 + description: "HTML fragment; scripts are allowed.",
58 63 minItems: 1,
59 64 maxItems: 4,
60 - description:
61 - "One to four mockup options. One option is valid for reviewing a single screen.",
64 67 multi: Type.Optional(
123 126 const schedulePrune = (protectedSessionId?: string): void => {
124 127 const timer = setTimeout(() => {
125 - void pruneMockupCache(cacheRoot, protectedSessionId).catch((error) =>
126 - console.error("Mockup cache cleanup failed:", error),
127 - );
128 + void pruneMockupCache(cacheRoot, protectedSessionId).catch((error) => {
129 + const ctx = protectedSessionId
130 + ? contexts.get(protectedSessionId)
131 + : undefined;
132 + if (ctx?.hasUI)
133 + ctx.ui.notify(
134 + `Mockup cache cleanup failed: ${error instanceof Error ? error.message : String(error)}`,
135 + "warning",
136 + );
137 + });
128 138 }, 0);
129 139 timer.unref?.();
136 146 promptSnippet: "Review HTML mockups in a browser",
137 147 promptGuidelines: [
138 148 "Use mockup when visual comparison beats prose for UI, layout, styling, or interaction decisions.",
139 - "Pass HTML fragments only; never include <!doctype>, <html>, <head>, or <body>.",
140 - "Provide 1-4 options; one option is valid when reviewing a single design.",
141 - "The tool owns browser review and feedback. Do not ask the user to repeat its result in chat.",
142 - "On iterate, revise the fragments and call mockup again. On accept, continue the design unless feedback requires another iteration.",
149 + `Before creating or revising mockups, read \`${MOCKUP_GUIDANCE_PATH}\`.`,
144 151 parameters,
145 152 renderCall(args, theme, context) {

extensions/the-system/mockup.ts

Modified
642 642 const script = document.createElement('script');
643 643 [...old.attributes].forEach(attr => script.setAttribute(attr.name, attr.value));
644 644 script.textContent = old.textContent;
645 - old.replaceWith(script);
645 + // Shadow-tree scripts have no currentScript; expose their root on the executing script.
646 + Object.defineProperty(script, 'mockupRoot', { value:root });
647 + const pending = Boolean(script.src) || script.type === 'module';
648 + if (pending) {
649 + script.addEventListener('load', () => script.remove(), { once:true });
650 + script.addEventListener('error', () => script.remove(), { once:true });
652 + // Retain inert originals so fragment-local data scripts remain readable.
653 + document.head.append(script);
654 + if (!pending) script.remove();
647 656 data.remove();

extensions/the-system/skills/vertical-slices/SKILL.md

Modified
2 2 name: vertical-slices
3 -description: "Use when a task calls for vertical slices, vertical slicing, a walking skeleton, or thin end-to-end delivery; implements complete observable increments across required layers instead of horizontal component batches."
3 +description: "Use when planning or implementing vertical slices, walking skeletons, or thin end-to-end increments."
6 6 # Vertical Slices