repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Merge remote-tracking branch 'origin/trunk' into sync-vcs-local

a29c82e49b9418c5de111de552bd6e7f35bb17b0

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

# Conflicts:
#	CHANGELOG.md

Changed files (14)

.gitignore

Modified
5 5 **/test-results/
6 6 **/playwright-report/
7 7 *.tgz
8 -.DS_Store
10 -skills/*/_research/

.pi/pulse.json

Deleted
deleted file mode 100644
1 -{
2 - "documents": [
3 - {
4 - "path": "CHANGELOG.md"
5 - }
6 - ]
7 -}

.pi/settings.json

Added
new file mode 100644
1 +{
2 + "pulse": {
3 + "documents": [
4 + {
5 + "path": "CHANGELOG.md",
6 + "instruction": "only add changes of interest to users, use user language"
7 + }
8 + ]
9 + }

CHANGELOG.md

Modified
59 59 current SDK: `pi.setModel` and `pi.setThinkingLevel` rewrite the user's
60 60 default model and thinking in settings, and only the `mode` extension's
61 61 baseline capture and restore-on-off / restore-on-shutdown mitigates the bleed
62 +- Split Vitest projects so only web fetch tests run isolated, restoring fast
63 + non-isolated test runs for the rest of the suite
62 64 - Convert extension drivers, helper scripts, and skill scripts from Python to MJS,
63 65 remove the Python/ruff project setup, and rename the goal pexpect test task
64 66 - Remove stale Python usage docs and the dead `requirements.txt` from the
142 144 - Add Pi skill-writing guidance to keep skill descriptions focused on discovery
143 145 triggers instead of summarizing full workflows
144 146 - Delete stale diff-review browser SPA source after the SSR rewrite
147 +- Move pulse settings under the `pulse` key in Pi settings; global defaults
148 + come from `~/.pi/agent/settings.json` and project overrides from
149 + `.pi/settings.json`. The legacy `.pi/pulse.json` config file is no longer
150 + read.
146 152 ## 0.0.3

extensions/pulse/README.md

Modified
28 28 - `/pulse force`
29 29 - `/pulse pause`
30 30 - `/pulse resume`
31 -- `/pulse config`
33 32 Completions:
43 42 Hooks:
45 44 - `session_start`:
46 - loads config, restores last run state, starts config watcher, starts timer
47 - when docs exist.
45 + loads settings, restores last run state, starts timer when docs exist.
48 46 - `session_shutdown`:
49 - stops watcher and timer.
47 + stops timer.
50 48 - `agent_start`:
51 49 refreshes status when tracking and not paused.
52 50 - `tool_execution_end`:
55 53 - `agent_end`:
56 54 runs an automatic check when tracking is active and ready.
58 -Settings live in `.pi/pulse.json`:
56 +Settings live under the `pulse` key in Pi settings.
57 +Global defaults use `~/.pi/agent/settings.json`; project overrides use `.pi/settings.json`.
60 59 ```json
62 - "documents": [{ "path": "README.md" }],
63 - "interval": 10,
64 - "apply": "auto"
61 + "pulse": {
62 + "documents": [{ "path": "README.md" }],
63 + "model": "minimax/MiniMax-M3",
64 + "interval": 10,
65 + "apply": "auto"
66 + }
100 102 ## Behavior
102 -- `/pulse init` creates `.pi/pulse.json`; it tracks root `README*` files and
103 - `AGENTS.md` when present.
104 +- `/pulse init` creates `.pi/settings.json` with a `pulse` section; it tracks
105 + root `README*` files and `AGENTS.md` when present.
104 106 - `/pulse add` requires an existing file.
105 107 - `/pulse add-dir` requires an existing directory and explicit glob.
106 108 - `/pulse add-glob` stores an explicit glob pattern.
108 110 - `/pulse force` runs a manual check unless paused.
109 111 - `/pulse pause` stops timer-driven checks.
110 112 `/pulse resume` restarts them.
111 -- `/pulse config` opens `.pi/pulse.json` in an editor.
112 113 - Absolute paths and `..` path escapes are rejected.
113 114 Existing symlinks resolving outside the workspace are rejected or skipped.
114 115 - Invalid config fields make the config unloadable.
115 - Invalid persisted document specs are dropped while loading config.
116 + Invalid document specs make the config unloadable.
116 117 - Dir and glob specs expand to sorted files; duplicate paths are ignored.
117 118 - Automatic checks wait for Pi idle, a 60 second quiet window after mutations,
118 119 and a 5 minute cooldown after the last update.
131 132 `confirm` asks before writing.
132 133 `review` opens each proposed file in an editor before writing.
133 134 - Writes are refused if a tracked file changed between load and apply.
134 -- `.pi/pulse.json` is watched and reloaded after changes.
135 135 - Last run state is stored in the session as `pulse-state`.

extensions/pulse/__tests__/harness.test.ts

Modified
24 24 return t?.session.extensionRunner.createCommandContext();
27 -function configPath(): string {
28 - return path.join(t?.cwd, ".pi/pulse.json");
27 +function settingsPath(): string {
28 + return path.join(t?.cwd, ".pi/settings.json");
31 31 function writeConfig(config: unknown): void {
32 - mkdirSync(path.dirname(configPath()), { recursive: true });
33 - writeFileSync(configPath(), JSON.stringify(config, null, 2), "utf8");
32 + mkdirSync(path.dirname(settingsPath()), { recursive: true });
33 + writeFileSync(
34 + settingsPath(),
35 + JSON.stringify({ pulse: config }, null, 2),
36 + "utf8",
37 + );
40 +function readConfig(): any {
41 + return JSON.parse(readFileSync(settingsPath(), "utf8")).pulse;
36 44 function notifyText(): string[] {
67 75 writeFileSync(path.join(t.cwd, "README.md"), "# Test\n", "utf8");
69 77 await pulseCommand().handler("init", ctx());
70 - expect(existsSync(configPath())).toBe(true);
71 - expect(JSON.parse(readFileSync(configPath(), "utf8")).documents).toEqual([
72 - { path: "README.md" },
73 - ]);
78 + expect(existsSync(settingsPath())).toBe(true);
79 + expect(readConfig().documents).toEqual([{ path: "README.md" }]);
75 81 await pulseCommand().handler("help", ctx());
76 82 await pulseCommand().handler("list", ctx());
77 83 await pulseCommand().handler("status", ctx());
78 84 await pulseCommand().handler("pause", ctx());
79 85 await pulseCommand().handler("resume", ctx());
80 - await pulseCommand().handler("config", ctx());
82 87 expect(notifyText()).toContain("Pulse: initialized 1 doc(s)");
83 88 expect(
90 95 expect(notifyText()).toContain("Pulse: paused");
91 96 expect(notifyText()).toContain("Pulse: resumed");
92 97 expect(statusText().some((s) => s === "󰐰 paused")).toBe(true);
93 - expect(
94 - t.events.uiCallsFor("editor").some((c) => c.args[0] === "pulse-config"),
95 - ).toBe(true);
98 + expect(pulseCommand().getArgumentCompletions("con") ?? []).toEqual([]);
98 101 it("handles add/add-dir/add-glob/remove completions with real runtime", async () => {
108 111 await pulseCommand().handler('add "my file.md" note here', ctx());
109 112 await pulseCommand().handler("add-dir docs **/*.md docs note", ctx());
110 113 await pulseCommand().handler("add-glob adr/**/*.md adr note", ctx());
111 - expect(JSON.parse(readFileSync(configPath(), "utf8")).documents).toEqual([
114 + expect(readConfig().documents).toEqual([
112 115 { path: "my file.md", instruction: "note here" },
113 116 { path: "docs", type: "dir", glob: "**/*.md", instruction: "docs note" },
114 117 { path: "adr/**/*.md", type: "glob", instruction: "adr note" },
129 132 await pulseCommand().handler('remove "my file.md"', ctx());
130 - expect(
131 - JSON.parse(readFileSync(configPath(), "utf8")).documents.map(
132 - (d: { path: string }) => d.path,
133 - ),
134 - ).toEqual(["docs", "adr/**/*.md"]);
133 + expect(readConfig().documents.map((d: { path: string }) => d.path)).toEqual(
134 + ["docs", "adr/**/*.md"],
135 + );
137 138 it("starts cleanly on session_start without notification spam and reports status", async () => {

extensions/pulse/__tests__/index.test.ts

Modified
31 31 let tmp = "";
32 32 const supportsControlCharPaths = process.platform !== "win32";
34 +const oldAgentDir = process.env.PI_CODING_AGENT_DIR;
34 36 function cwd(): string {
35 37 tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pulse-index-"));
38 + process.env.PI_CODING_AGENT_DIR = path.join(tmp, "agent");
36 39 return tmp;
45 48 function writeConfig(root: string, config: unknown): void {
46 - write(root, ".pi/pulse.json", JSON.stringify(config, null, 2));
49 + write(root, ".pi/settings.json", JSON.stringify({ pulse: config }, null, 2));
52 +function readConfig(root: string): any {
53 + return JSON.parse(
54 + fs.readFileSync(path.join(root, ".pi/settings.json"), "utf8"),
55 + ).pulse;
58 +function writeGlobalConfig(root: string, config: unknown): void {
59 + write(
60 + path.join(root, "agent"),
61 + "settings.json",
62 + JSON.stringify({ pulse: config }, null, 2),
63 + );
49 66 function harness(root: string) {
142 159 }) as never,
143 160 getModel: ((provider: string, id: string) => ({ provider, id })) as never,
162 + if (oldAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
163 + else process.env.PI_CODING_AGENT_DIR = oldAgentDir;
145 164 if (tmp) fs.rmSync(tmp, { recursive: true, force: true });
146 165 tmp = "";
172 191 await h.commands
173 192 .get("pulse")
174 193 .handler('add "my file.md" keep concise', h.ctx);
175 - expect(
176 - JSON.parse(fs.readFileSync(path.join(root, ".pi/pulse.json"), "utf8"))
177 - .documents,
178 - ).toEqual([{ path: "my file.md", instruction: "keep concise" }]);
194 + expect(readConfig(root).documents).toEqual([
195 + { path: "my file.md", instruction: "keep concise" },
196 + ]);
180 198 await h.commands.get("pulse").handler('remove "my file.md"', h.ctx);
199 + expect(readConfig(root).documents).toEqual([]);
200 + });
202 + it("rejects the removed config subcommand", async () => {
203 + const root = cwd();
204 + const h = harness(root);
206 + expect(h.commands.get("pulse").getArgumentCompletions("con") ?? []).toEqual(
207 + [],
208 + );
209 + await h.commands.get("pulse").handler("config", h.ctx);
211 + expect(h.notifications).toContainEqual({
212 + message: "Pulse: unknown command config",
213 + level: "warning",
214 + });
215 + });
217 + it("reports invalid settings instead of silently dropping docs", async () => {
218 + const root = cwd();
219 + writeConfig(root, { documents: [{ path: "README.md", model: "bad" }] });
220 + const h = harness(root);
222 + await h.commands.get("pulse").handler("status", h.ctx);
224 + expect(h.notifications).toContainEqual({
225 + message: "Pulse: invalid config: documents[0].model must be provider/id",
226 + level: "warning",
227 + });
228 + });
230 + it("merges global and project pulse settings", async () => {
231 + const root = cwd();
232 + write(root, "README.md", "doc");
233 + writeGlobalConfig(root, { model: "global/model", interval: 0 });
234 + writeConfig(root, { documents: [{ path: "README.md" }] });
235 + const h = harness(root);
237 + await h.commands.get("pulse").handler("status", h.ctx);
181 239 expect(
182 - JSON.parse(fs.readFileSync(path.join(root, ".pi/pulse.json"), "utf8"))
183 - .documents,
184 - ).toEqual([]);
240 + h.notifications.some((n) => n.message.includes("model: global/model")),
241 + ).toBe(true);
242 + expect(
243 + h.notifications.some((n) => n.message.includes("periodic: off")),
244 + ).toBe(true);
245 + });
247 + it("ignores legacy .pi/pulse.json", async () => {
248 + const root = cwd();
249 + write(root, "README.md", "doc");
250 + write(
251 + root,
252 + ".pi/pulse.json",
253 + JSON.stringify({ documents: [{ path: "README.md" }] }),
254 + );
255 + const h = harness(root);
257 + await h.commands.get("pulse").handler("status", h.ctx);
259 + expect(h.notifications).toContainEqual({
260 + message: "Pulse: not initialized",
261 + level: "info",
262 + });
187 265 it("reports missing auth instead of saying nothing to update", async () => {

extensions/pulse/index.ts

Modified
20 20 } from "@earendil-works/pi-coding-agent";
21 21 import {
22 22 convertToLlm,
23 + getAgentDir,
23 24 serializeConversation,
24 25 } from "@earendil-works/pi-coding-agent";
25 26 import {
35 36 stripUnsafeText,
36 37 } from "./core.ts";
38 -const PULSE_CONFIG = ".pi/pulse.json";
39 +const PULSE_SETTINGS = ".pi/settings.json";
40 +const PULSE_SETTINGS_KEY = "pulse";
39 41 const PULSE_STATE_ENTRY = "pulse-state";
40 42 const DEFAULT_INTERVAL_MIN = 10;
41 43 const COOLDOWN_MS = 5 * 60 * 1000;
44 46 // Magic numbers
45 47 const TIMER_TICK_MS = 30_000;
46 -const CONFIG_WATCHER_DEBOUNCE_MS = 200;
47 48 const RECENT_MESSAGES_LIMIT = 50;
48 49 const MAX_JSON_RETRIES = 2;
49 50 const MAX_SUMMARY_CHARS = 240;
71 72 "force",
72 73 "pause",
73 74 "resume",
74 - "config",
75 75 ] as const;
77 77 type Subcommand = (typeof SUBCOMMANDS)[number];
79 -function assert(
80 - condition: boolean,
81 - message = "assertion failed",
82 -): asserts condition {
83 - if (!condition) throw new Error(`[assert] ${message}`);
86 -function invariant(
87 - condition: boolean,
88 - message = "invariant violated",
89 -): asserts condition {
90 - if (!condition) throw new Error(`[invariant] ${message}`);
93 -function assertArray(
94 - val: unknown,
95 - message = "expected array",
96 -): asserts val is unknown[] {
97 - if (!Array.isArray(val)) throw new Error(`[assert] ${message}`);
100 79 // ============================================================================
101 80 // CONFIG FILE OPERATIONS
102 81 // ============================================================================
104 -function loadConfig(cwd: string): PulseConfig | null {
105 - const configPath = path.join(cwd, PULSE_CONFIG);
83 +type ConfigLoadResult =
84 + | { config: PulseConfig | null; error?: undefined }
85 + | { config: null; error: string };
87 +function isRecord(value: unknown): value is Record<string, unknown> {
88 + return typeof value === "object" && value !== null && !Array.isArray(value);
91 +function readJsonObject(filePath: string): Record<string, unknown> | null {
107 - const content = fs.readFileSync(configPath, "utf-8");
108 - const raw = JSON.parse(content);
109 - assert(
110 - typeof raw === "object" && raw !== null,
111 - "pulse config should be object",
112 - );
113 - const parsed = raw as PulseConfig;
114 - if (!parsed.documents || !Array.isArray(parsed.documents)) return null;
115 - assertArray(parsed.documents, "pulse documents should be array");
93 + const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
94 + return isRecord(parsed) ? parsed : null;
95 + } catch {
96 + return null;
97 + }
100 +function readPulseSettings(filePath: string): unknown {
101 + const parsed = readJsonObject(filePath);
102 + return parsed?.[PULSE_SETTINGS_KEY];
105 +function mergeRawConfig(globalRaw: unknown, projectRaw: unknown): unknown {
106 + if (globalRaw === undefined) return projectRaw;
107 + if (projectRaw === undefined) return globalRaw;
108 + if (isRecord(globalRaw) && isRecord(projectRaw))
109 + return { ...globalRaw, ...projectRaw };
110 + return projectRaw;
113 +function validateConfig(cwd: string, raw: unknown): PulseConfig {
114 + if (!isRecord(raw)) throw new Error("config must be object");
115 + const documentsRaw = raw.documents ?? [];
116 + if (!Array.isArray(documentsRaw)) throw new Error("documents must be array");
117 + if (
118 + raw.interval !== undefined &&
119 + (typeof raw.interval !== "number" || raw.interval < 0)
121 + throw new Error("interval must be a non-negative number");
122 + if (
123 + raw.apply !== undefined &&
124 + raw.apply !== "auto" &&
125 + raw.apply !== "confirm" &&
126 + raw.apply !== "review"
128 + throw new Error("apply must be auto, confirm, or review");
129 + if (
130 + raw.model !== undefined &&
131 + (typeof raw.model !== "string" || !isModelSpec(raw.model))
133 + throw new Error("model must be provider/id");
135 + const documents = documentsRaw.map((entry, index) => {
136 + if (!isRecord(entry)) throw new Error(`documents[${index}] must be object`);
137 + if (typeof entry.path !== "string")
138 + throw new Error(`documents[${index}].path must be string`);
117 - parsed.interval !== undefined &&
118 - (typeof parsed.interval !== "number" || parsed.interval < 0)
140 + entry.type !== undefined &&
141 + entry.type !== "file" &&
142 + entry.type !== "dir" &&
143 + entry.type !== "glob"
120 - return null;
145 + throw new Error(`documents[${index}].type must be file, dir, or glob`);
146 + if (entry.glob !== undefined && typeof entry.glob !== "string")
147 + throw new Error(`documents[${index}].glob must be string`);
122 - parsed.apply !== undefined &&
123 - parsed.apply !== "auto" &&
124 - parsed.apply !== "confirm" &&
125 - parsed.apply !== "review"
149 + entry.instruction !== undefined &&
150 + typeof entry.instruction !== "string"
127 - return null;
152 + throw new Error(`documents[${index}].instruction must be string`);
129 - parsed.model !== undefined &&
130 - (typeof parsed.model !== "string" || !isModelSpec(parsed.model))
154 + entry.model !== undefined &&
155 + (typeof entry.model !== "string" || !isModelSpec(entry.model))
132 - return null;
133 - parsed.documents = parsed.documents
134 - .map((d) => normalizeDoc(cwd, d))
135 - .filter((d): d is PulseDoc => d !== null);
136 - return parsed;
157 + throw new Error(`documents[${index}].model must be provider/id`);
158 + const normalized = normalizeDoc(cwd, entry as unknown as PulseDoc);
159 + if (!normalized) throw new Error(`documents[${index}] is invalid`);
160 + return normalized;
161 + });
163 + const config: PulseConfig = { documents };
164 + if (typeof raw.model === "string") config.model = raw.model;
165 + if (typeof raw.interval === "number") config.interval = raw.interval;
166 + if (raw.apply === "auto" || raw.apply === "confirm" || raw.apply === "review")
167 + config.apply = raw.apply;
168 + return config;
171 +function loadConfigResult(cwd: string): ConfigLoadResult {
172 + const globalRaw = readPulseSettings(
173 + path.join(getAgentDir(), "settings.json"),
174 + );
175 + const projectRaw = readPulseSettings(path.join(cwd, PULSE_SETTINGS));
176 + const raw = mergeRawConfig(globalRaw, projectRaw);
177 + if (raw === undefined) return { config: null };
178 + try {
179 + return { config: validateConfig(cwd, raw) };
180 + } catch (e) {
181 + return {
182 + config: null,
183 + error: e instanceof Error ? e.message : "invalid config",
184 + };
188 +function loadConfig(cwd: string): PulseConfig | null {
189 + return loadConfigResult(cwd).config;
192 +function readProjectConfig(cwd: string): PulseConfig | null {
193 + const raw = readPulseSettings(path.join(cwd, PULSE_SETTINGS));
194 + if (raw === undefined) return null;
195 + try {
196 + return validateConfig(cwd, raw);
137 197 } catch {
138 198 return null;
142 202 function saveConfig(cwd: string, config: PulseConfig): void {
143 - const configPath = path.join(cwd, PULSE_CONFIG);
144 - fs.mkdirSync(path.dirname(configPath), { recursive: true });
145 - fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
203 + const settingsPath = path.join(cwd, PULSE_SETTINGS);
204 + const settings = readJsonObject(settingsPath) ?? {};
205 + const projectConfig = readProjectConfig(cwd) ?? { documents: [] };
206 + settings[PULSE_SETTINGS_KEY] = {
207 + ...projectConfig,
208 + documents: config.documents,
209 + };
210 + fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
211 + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
148 214 function configExists(cwd: string): boolean {
149 - return fs.existsSync(path.join(cwd, PULSE_CONFIG));
215 + return readPulseSettings(path.join(cwd, PULSE_SETTINGS)) !== undefined;
152 218 function getCwd(pi: ExtensionAPI, ctx?: ExtensionCommandContext): string {
588 654 lastRunReason: string;
589 655 lastResult: string;
590 656 timerHandle: ReturnType<typeof setInterval> | null;
591 - configWatcher: ReturnType<typeof fs.watch> | null;
592 - configWatcherCwd: string;
595 659 // ============================================================================
614 678 lastRunReason: "",
615 679 lastResult: "never",
616 680 timerHandle: null,
617 - configWatcher: null,
618 - configWatcherCwd: "",
621 683 // ------------------------------------------------------------------------
655 - // ------------------------------------------------------------------------
656 - // Config watcher
657 - // ------------------------------------------------------------------------
659 - let watcherDebounce: ReturnType<typeof setTimeout> | null = null;
661 - function startConfigWatcher(ctx: ExtensionCommandContext): void {
662 - stopConfigWatcher();
663 - const ticket = generation;
664 - const configPath = path.join(state.cwd, PULSE_CONFIG);
665 - if (!fs.existsSync(configPath)) return;
666 - state.configWatcherCwd = state.cwd;
667 - try {
668 - state.configWatcher = fs.watch(configPath, (eventType) => {
669 - if (eventType !== "change") return;
670 - if (watcherDebounce) clearTimeout(watcherDebounce);
671 - watcherDebounce = setTimeout(() => {
672 - watcherDebounce = null;
673 - if (ticket !== generation) return;
674 - if (state.cwd !== state.configWatcherCwd) return;
675 - const reloaded = loadConfig(state.cwd);
676 - if (!reloaded) return;
677 - state.config = reloaded;
678 - state.isTracking = state.config.documents.length > 0;
679 - // Captured ctx from the watcher closure can be
680 - // invalidated by ctx.reload() between ticket check and use;
681 - // session_start reinstalls the watcher with a fresh ctx.
682 - try {
683 - setStatus(ctx);
684 - } catch {}
685 - }, CONFIG_WATCHER_DEBOUNCE_MS);
686 - });
687 - state.configWatcher.on("error", () => {
688 - state.configWatcher?.close();
689 - state.configWatcher = null;
690 - state.configWatcherCwd = "";
691 - });
692 - } catch {}
695 - function stopConfigWatcher(): void {
696 - if (watcherDebounce) {
697 - clearTimeout(watcherDebounce);
698 - watcherDebounce = null;
700 - if (state.configWatcher) {
701 - state.configWatcher.close();
702 - state.configWatcher = null;
704 - state.configWatcherCwd = "";
707 717 // ------------------------------------------------------------------------
708 718 // Dirty state
709 719 // ------------------------------------------------------------------------
1069 1079 " /pulse add-dir <dir> <glob> [note]",
1070 1080 " /pulse add-glob <glob> [note]",
1071 1081 " /pulse remove <path|index>",
1072 - " /pulse list | status | force | pause | resume | config",
1082 + " /pulse list | status | force | pause | resume",
1074 - `Config: ${PULSE_CONFIG}`,
1084 + `Config: ${PULSE_SETTINGS} key "${PULSE_SETTINGS_KEY}"`,
1075 1085 "Fields: documents[], model, interval, apply",
1076 1086 "Doc fields: path, type, glob, instruction, model",
1077 1087 ].join("\n");
1116 1126 if (state.isTracking) {
1117 - startConfigWatcher(ctx);
1118 1127 ensureTimer(ctx);
1119 1128 setStatus(ctx);
1359 1368 setStatus(ctx);
1362 - function handleConfig(ctx: ExtensionCommandContext): void {
1363 - const configPath = path.join(state.cwd, PULSE_CONFIG);
1364 - if (!fs.existsSync(configPath)) {
1365 - ctx.ui.notify("Pulse: not initialized", "warning");
1366 - return;
1368 - const content = fs.readFileSync(configPath, "utf-8");
1369 - (ctx.ui.editor as any)("pulse-config", content, (newContent: string) => {
1370 - try {
1371 - const parsed = JSON.parse(newContent);
1372 - invariant(
1373 - typeof parsed === "object" && parsed !== null,
1374 - "config should be object",
1375 - );
1376 - if (parsed.interval !== undefined) {
1377 - assert(
1378 - typeof parsed.interval === "number" && parsed.interval >= 0,
1379 - "interval must be >= 0",
1380 - );
1382 - if (parsed.apply !== undefined) {
1383 - assert(
1384 - parsed.apply === "auto" ||
1385 - parsed.apply === "confirm" ||
1386 - parsed.apply === "review",
1387 - "apply must be auto, confirm, or review",
1388 - );
1390 - fs.writeFileSync(configPath, newContent, "utf-8");
1391 - state.config = loadConfig(state.cwd) || { documents: [] };
1392 - return { saved: true };
1393 - } catch (e) {
1394 - return {
1395 - saved: false,
1396 - error: e instanceof Error ? e.message : "Invalid config",
1397 - };
1399 - });
1402 1371 // ------------------------------------------------------------------------
1403 1372 // Command: /pulse
1404 1373 // ------------------------------------------------------------------------
1461 1430 async handler(args, ctx) {
1462 1431 state.cwd = getCwd(pi, ctx);
1463 - state.config = loadConfig(state.cwd) || { documents: [] };
1464 - state.isTracking = state.config.documents.length > 0;
1466 1432 const parts = parsePulseArgs(args || "");
1467 1433 const subcmd = (parts[0]?.toLowerCase() as Subcommand) || "help";
1468 1434 const subArgs = parts.slice(1);
1435 + const loaded = loadConfigResult(state.cwd);
1436 + if (loaded.error && subcmd !== "help" && subcmd !== "init") {
1437 + state.config = { documents: [] };
1438 + state.isTracking = false;
1439 + ctx.ui.notify(`Pulse: invalid config: ${loaded.error}`, "warning");
1440 + return;
1442 + state.config = loaded.config || { documents: [] };
1443 + state.isTracking = state.config.documents.length > 0;
1470 1445 switch (subcmd) {
1471 1446 case "help":
1501 1476 case "resume":
1502 1477 handleResume(ctx);
1504 - case "config":
1505 - handleConfig(ctx);
1506 - break;
1507 1479 default:
1508 1480 ctx.ui.notify(`Pulse: unknown command ${subcmd}`, "warning");
1539 1511 pi.on("session_start", async (_event, ctx) => {
1540 1512 const ticket = ++generation;
1541 - stopConfigWatcher();
1542 1513 stopTimer();
1543 1514 state.cwd = getCwd(pi, ctx as any);
1545 - const config = loadConfig(state.cwd);
1546 - if (config) {
1547 - state.config = config;
1548 - state.isTracking = config.documents.length > 0;
1516 + const loaded = loadConfigResult(state.cwd);
1517 + if (loaded.error) {
1518 + (ctx as any).ui.notify(
1519 + `Pulse: invalid config: ${loaded.error}`,
1520 + "warning",
1521 + );
1522 + state.config = { documents: [] };
1523 + state.isTracking = false;
1524 + } else if (loaded.config) {
1525 + state.config = loaded.config;
1526 + state.isTracking = loaded.config.documents.length > 0;
1549 1527 } else {
1550 1528 state.config = { documents: [] };
1551 1529 state.isTracking = false;
1563 1541 state.isChecking = false;
1564 1542 restoreState(ctx as any);
1566 - startConfigWatcher(ctx as any);
1567 1544 if (state.isTracking && state.config.documents.length > 0) {
1568 1545 startTimer(ctx as any);
1573 1550 pi.on("session_shutdown", async (_event, _ctx) => {
1574 1551 generation++;
1575 1552 state.isChecking = false;
1576 - stopConfigWatcher();
1577 1553 stopTimer();

extensions/super/__tests__/workflow-skills.test.ts

Added
new file mode 100644
1 +import assert from "node:assert";
2 +import { readFileSync } from "node:fs";
3 +import path from "node:path";
4 +import { describe, it } from "vitest";
6 +const root = path.resolve(import.meta.dirname, "..");
7 +const skill = (name: string) =>
8 + readFileSync(path.join(root, "skills", name, "SKILL.md"), "utf8");
10 +describe("super workflow phase skills", () => {
11 + it("offers spec prototyping after approved risky specs and before planning", () => {
12 + const brainstorming = skill("brainstorming");
14 + assert.match(brainstorming, /\bprototyping-spec\b/);
15 + assert.match(brainstorming, />250 lines/);
16 + assert.match(
17 + brainstorming,
18 + /spec review flags assumptions, ambiguity, integration risk, or logical gaps/,
19 + );
20 + assert.ok(
21 + brainstorming.indexOf("Optional spec prototyping") <
22 + brainstorming.indexOf("Choose writing-roadmaps or writing-plans"),
23 + );
24 + });
26 + it("defines a self-verifying temporary prototype phase", () => {
27 + const prototyping = skill("prototyping-spec");
29 + assert.match(prototyping, /temporary prototypes/);
30 + assert.match(prototyping, /supported \| falsified \| inconclusive/);
31 + assert.match(prototyping, /Suggested spec changes/);
32 + assert.match(prototyping, /Delete temporary artifacts/);
33 + });
35 + it("runs report-only execution review after plan execution", () => {
36 + const executing = skill("executing-plans");
37 + const reviewing = skill("reviewing-execution");
39 + assert.match(executing, /reviewing-execution/);
40 + assert.ok(
41 + executing.indexOf("reviewing-execution") <
42 + executing.indexOf("finishing-a-development-branch"),
43 + );
44 + assert.match(reviewing, /report-only/);
45 + assert.match(reviewing, /Architecture/);
46 + assert.match(reviewing, /Contact with existing APIs/);
47 + assert.match(reviewing, /New APIs/);
48 + assert.match(reviewing, /Risky new code/);
49 + });
50 +});

extensions/super/skills/brainstorming/SKILL.md

Modified
29 29 6. **Write design doc** — save to `docs/super/specs/YYYY-MM-DD-<topic>-design.md` and commit
30 30 7. **Spec self-review** — check the spec for completeness and consistency before user review
31 31 8. **User reviews written spec** — ask user to review the spec file before proceeding
32 -9. **Transition to planning** — invoke /skill:writing-roadmaps for large/multi-phase designs, otherwise invoke /skill:writing-plans
32 +9. **Optional spec prototyping** — offer /skill:prototyping-spec when the spec is >250 lines or spec review flags assumptions, ambiguity, integration risk, or logical gaps
33 +10. **Transition to planning** — invoke /skill:writing-roadmaps for large/multi-phase designs, otherwise invoke /skill:writing-plans
34 35 ## Process Flow
45 46 "Write design doc" [shape=box];
46 47 "Spec self-review\n(fix inline)" [shape=box];
47 48 "User reviews spec?" [shape=diamond];
49 + "Offer prototyping-spec?" [shape=diamond];
50 + "Run prototyping-spec\n(if accepted)" [shape=box];
48 51 "Choose writing-roadmaps or writing-plans" [shape=doublecircle];
50 53 "Explore project context" -> "Visual questions ahead?";
59 62 "Write design doc" -> "Spec self-review\n(fix inline)";
60 63 "Spec self-review\n(fix inline)" -> "User reviews spec?";
61 64 "User reviews spec?" -> "Write design doc" [label="changes requested"];
62 - "User reviews spec?" -> "Choose writing-roadmaps or writing-plans" [label="approved"];
65 + "User reviews spec?" -> "Offer prototyping-spec?" [label="approved"];
66 + "Offer prototyping-spec?" -> "Run prototyping-spec\n(if accepted)" [label=">250 lines or risky"];
67 + "Offer prototyping-spec?" -> "Choose writing-roadmaps or writing-plans" [label="skip"];
68 + "Run prototyping-spec\n(if accepted)" -> "Write design doc" [label="spec changes"];
69 + "Run prototyping-spec\n(if accepted)" -> "Choose writing-roadmaps or writing-plans" [label="proceed"];
66 -**The terminal state is choosing the next planning skill.** For designs too large for one detailed implementation plan or context window, invoke /skill:writing-roadmaps. For designs that fit in one plan, invoke /skill:writing-plans. Do NOT invoke frontend-design, mcp-builder, or any other implementation skill.
73 +**The terminal state is choosing optional prototyping or the next planning skill.** Offer /skill:prototyping-spec when the approved spec is >250 lines or spec review flags assumptions, ambiguity, integration risk, or logical gaps. If prototyping suggests spec changes, get user approval, update the spec, and repeat the spec review gate. Then invoke /skill:writing-roadmaps for designs too large for one detailed implementation plan or context window, otherwise invoke /skill:writing-plans. Do NOT invoke frontend-design, mcp-builder, or any implementation skill.
68 75 ## The Process
72 79 - Check out the current project state first (files, docs, recent commits)
73 80 - Before asking detailed questions, assess scope: if the request describes multiple independent subsystems (e.g., "build a platform with chat, file storage, billing, and analytics"), flag this immediately. Don't spend questions refining details of a project that needs to be decomposed first.
74 81 - If the project is too large for a single spec, help the user decompose into sub-projects: what are the independent pieces, how do they relate, what order should they be built? Then brainstorm the first sub-project through the normal design flow. Each sub-project gets its own spec → roadmap-or-plan → implementation cycle.
75 -- If the design fits in one spec but is too large for one detailed implementation plan or one context window, finish the design doc, then use /skill:writing-roadmaps to define ordered phases before any detailed plan.
82 +- If the design fits in one spec but is too large for one detailed implementation plan or one context window, finish the design doc, consider /skill:prototyping-spec when the spec is risky, then use /skill:writing-roadmaps to define ordered phases before any detailed plan.
76 83 - For appropriately-scoped projects, ask questions one at a time to refine the idea
77 84 - Prefer multiple choice questions when possible, but open-ended is fine too
78 85 - Only one question per message - if a topic needs more exploration, break it into multiple questions
132 139 Wait for the user's response. If they request changes, make them and re-run the spec review loop. Only proceed once the user approves.
141 +**Optional spec prototyping:**
143 +After the user approves the written spec, decide whether to offer /skill:prototyping-spec before planning.
144 +Offer it when the spec is >250 lines or spec review flags assumptions, ambiguity, integration risk, or logical gaps.
145 +If the user accepts, run prototyping before planning.
146 +If prototyping suggests spec changes, report them with rationale, get user approval, update the spec, and repeat the spec review gate before planning.
134 148 **Implementation:**
136 150 - If the design is large, multi-phase, or likely to exceed one context window as a detailed plan, invoke /skill:writing-roadmaps
137 151 - Otherwise, invoke /skill:writing-plans to create a detailed implementation plan
138 -- Do NOT invoke any other skill. Roadmap/planning is the next step.
152 +- Do NOT invoke any implementation skill. Roadmap/planning is the next step.
140 154 ## Key Principles

extensions/super/skills/executing-plans/SKILL.md

Modified
29 29 3. Run verifications as specified
30 30 4. Mark as completed
32 -### Step 3: Complete Development
32 +### Step 3: Review Execution
34 34 After all tasks complete and verified:
36 +- Announce: "I'm using the reviewing-execution skill to summarize the implemented code for review."
37 +- **REQUIRED SUB-SKILL:** Use /skill:reviewing-execution
38 +- Follow that skill to report architecture, contact with existing APIs, new APIs, and risky new code
39 +- Stop and let the human decide next actions
41 +### Step 4: Complete Development
43 +Only if the human chooses to finish the branch:
36 45 - Announce: "I'm using the finishing-a-development-branch skill to complete this work."
37 46 - **REQUIRED SUB-SKILL:** Use /skill:finishing-a-development-branch
38 47 - Follow that skill to verify tests, present options, execute choice
71 80 **Required workflow skills:**
73 82 - **/skill:writing-plans** - Creates the plan this skill executes
74 -- **/skill:finishing-a-development-branch** - Complete development after all tasks
83 +- **/skill:reviewing-execution** - Summarizes implemented code for human review focus
84 +- **/skill:finishing-a-development-branch** - Complete development after the human chooses to finish

extensions/super/skills/prototyping-spec/SKILL.md

Added
new file mode 100644
1 +---
2 +name: prototyping-spec
3 +description: Use after an approved spec, before roadmaps/plans, when spec size or quality makes assumptions risky and temporary prototypes can verify claims against reality.
4 +---
6 +# Prototyping Specs
8 +Verify an approved spec against reality before planning.
10 +This phase uses temporary prototypes to prove or falsify spec claims, assumptions, integrations, data shapes, and logical consistency.
11 +Prototype tech does not matter.
12 +Use project tech, throwaway scripts, mocked fixtures, real APIs, or tiny harnesses as needed, as long as the proof is definite.
14 +**Announce at start:** "I'm using the prototyping-spec skill to verify the spec with temporary prototypes."
16 +## When to Offer
18 +Offer this phase after user approval of the written spec and before `/skill:writing-roadmaps` or `/skill:writing-plans` when either condition is true:
20 +- the spec is >250 lines
21 +- spec review flags assumptions, ambiguity, integration risk, or logical gaps
23 +Skip it for small, concrete specs with no risky assumptions unless the user asks for it.
25 +## Hard Rules
27 +- Do not implement production code.
28 +- Do not start roadmap or plan writing during this phase.
29 +- Keep prototypes temporary unless the user explicitly asks to promote an artifact.
30 +- Prefer self-verifying commands over visual inspection or vibes.
31 +- Every claim checked must end as `supported | falsified | inconclusive`.
32 +- Delete temporary artifacts before handing back the report.
34 +## Process
36 +### Step 1: Load the Spec
38 +Read the spec and identify claims that must be true for implementation to work.
40 +Classify claims by risk:
42 +- **Architecture:** component boundaries, data flow, ownership, lifecycle
43 +- **Existing APIs:** real signatures, behavior, errors, extension points
44 +- **New APIs:** proposed shapes, call order, serialization, compatibility
45 +- **Data:** file formats, schemas, migrations, persistence, generated output
46 +- **Runtime:** platform behavior, dependency behavior, performance, concurrency
47 +- **Logic:** contradictions, impossible states, missing transitions
49 +### Step 2: Pick Prototype Targets
51 +Prototype only claims where uncertainty can damage the plan.
53 +For each target, write a short verification card before coding:
55 +```text
56 +Claim: ...
57 +Hypothesis: if ... then ... because ...
58 +Falsifier: false if ...
59 +Prototype: temp path and tech
60 +Command: exact command to run
61 +Proof: observable output/assertion
62 +Cleanup: exact temp paths to delete
63 +```
65 +Unfalsifiable claims are not ready for prototyping.
66 +Rewrite them into observable claims or flag them as spec ambiguity.
68 +### Step 3: Build Temporary Prototypes
70 +Use the smallest prototype that can answer the claim.
72 +Acceptable forms:
74 +- one-off scripts
75 +- tiny harnesses
76 +- fake fixtures
77 +- API probes
78 +- type-check probes
79 +- generated sample data
80 +- microbenchmarks when performance is the claim
82 +Default location is outside the repo.
83 +If repo context is required, use one contained ignored directory such as `.pi/tmp/<slug>/` or `tmp/<slug>/` and record it.
84 +Never scatter scratch files.
86 +### Step 4: Verify
88 +Run the command and record evidence.
90 +Use at least two independent checks when practical:
92 +- positive control
93 +- negative control
94 +- assertion failure on wrong output
95 +- rerun for determinism
96 +- compare with existing tests/docs/source
97 +- inspect generated output against expected shape
99 +Classify each claim:
101 +- **supported:** evidence backs the spec claim
102 +- **falsified:** evidence contradicts the spec claim
103 +- **inconclusive:** prototype cannot decide the claim cleanly
105 +### Step 5: Report Spec Improvements
107 +Do not silently edit the spec.
108 +Report suggested changes with rationale and evidence.
110 +Use this report shape:
112 +```markdown
113 +## Prototype Report
115 +**Spec:** `path/to/spec.md`
117 +### Summary
119 +- Supported: N
120 +- Falsified: N
121 +- Inconclusive: N
123 +### Evidence
125 +| Claim | Result | Evidence | Notes |
126 +| ----- | --------- | --------------------------- | ----- |
127 +| ... | supported | `command` + observed output | ... |
129 +### Suggested spec changes
131 +1. **Change:** ...
132 + **Rationale:** ...
133 + **Evidence:** ...
135 +### Cleaned
137 +- Deleted temporary artifacts: ...
139 +### Remaining questions
141 +- ...
142 +```
144 +### Step 6: Clean Up
146 +Delete temporary artifacts before final response.
148 +Required cleanup checklist:
150 +- stop started processes
151 +- delete temp dirs, scripts, outputs, logs, generated fixtures
152 +- keep only explicitly promoted artifacts
153 +- run `git status --short` if the repo was touched
154 +- explain any remaining dirty paths
156 +## Handoff
158 +After reporting, ask the user whether to apply suggested spec changes or proceed to planning.
160 +If the user applies spec changes, update the spec and repeat the normal spec review gate before planning.
161 +If the user proceeds without changes, use `/skill:writing-roadmaps` for large/multi-phase specs or `/skill:writing-plans` for single-plan specs.

extensions/super/skills/reviewing-execution/SKILL.md

Added
new file mode 100644
1 +---
2 +name: reviewing-execution
3 +description: Use after an implementation plan has been executed to summarize the new code, integration points, new APIs, and risky areas so the human can focus review attention.
4 +---
6 +# Reviewing Execution
8 +Create a report-only review guide after plan execution.
10 +The goal is not to approve, reject, or fix the work.
11 +The goal is to focus human attention on the code that matters most.
13 +**Announce at start:** "I'm using the reviewing-execution skill to summarize the implemented code for review."
15 +## When to Use
17 +Use after `/skill:executing-plans` completes all plan tasks and verification, before `/skill:finishing-a-development-branch`.
19 +Use it for every completed plan unless the user explicitly skips the review report.
21 +## Hard Rules
23 +- Report only.
24 +- Do not edit code.
25 +- Do not run formatting, fixes, or refactors.
26 +- Do not decide next actions for the user.
27 +- Do not request another code review unless the user asks.
28 +- If verification is missing or failed, report that plainly instead of treating execution as complete.
30 +## Inputs
32 +Gather only what is needed for review focus:
34 +- plan file and linked spec or roadmap
35 +- git diff against the plan start point, branch base, or `HEAD~1` when no better base exists
36 +- changed files and new files
37 +- verification commands already run and their results
39 +If the base diff is unclear, ask the user before inventing one.
41 +## Review Report
43 +Use this shape:
45 +```markdown
46 +## Execution Review Guide
48 +**Plan:** `path/to/plan.md`
49 +**Diff base:** `<sha-or-branch>`
50 +**Verification:** `<commands and results>`
52 +### Architecture
54 +- What changed structurally.
55 +- Which components own which responsibilities.
56 +- Why the design matches or diverges from the plan.
58 +### Contact with existing APIs
60 +- Existing functions, classes, files, commands, config, or extension points touched.
61 +- Assumptions made about existing behavior.
62 +- Compatibility or lifecycle concerns.
64 +### New APIs
66 +- New exported functions, types, commands, settings, files, schemas, or user-facing surfaces.
67 +- Expected callers and usage contracts.
68 +- Naming or shape decisions worth reviewing.
70 +### Risky new code
72 +Rank by review priority.
74 +1. `path/to/file`: why this is risky and what to inspect first.
75 +2. `path/to/file`: why this is risky and what to inspect first.
77 +### Review map
79 +- Start here: `path/to/highest-risk-file`
80 +- Then inspect: `path/to/next-file`
81 +- Low-risk/supporting files: `path/to/file`
83 +### Open questions
85 +- Questions the human should decide.
87 +### Suggested next actions
89 +- Options only; do not choose for the user.
90 +```
92 +## What Counts as Risky
94 +Prioritize:
96 +- new public API or behavior surface
97 +- auth, secrets, filesystem, network, process, or shell access
98 +- concurrency, caching, persistence, migrations, cleanup
99 +- code touching old fragile areas
100 +- code with sparse tests
101 +- code that coordinates multiple subsystems
102 +- generated or large mechanical changes that hide semantic edits
104 +## Handoff
106 +End after the report.
108 +Ask: "What would you like to do next: inspect, revise, request review, or finish the branch?"
110 +Only invoke `/skill:finishing-a-development-branch` if the user chooses to finish.

vitest.config.ts

Modified
1 1 import { defineConfig } from "vitest/config";
3 +const include = ["extensions/**/__tests__/**/*.test.ts", "skills/**/*.test.ts"];
4 +const exclude = ["**/__e2e__/**", "**/node_modules/**"];
3 6 export default defineConfig({
4 7 test: {
5 - include: ["extensions/**/__tests__/**/*.test.ts", "skills/**/*.test.ts"],
6 - exclude: ["**/__e2e__/**", "**/node_modules/**"],
7 8 reporters: ["minimal"],
8 9 testTimeout: 30_000,
9 10 hookTimeout: 30_000,
10 - isolate: false,
11 - // Three fork workers avoid CPU/process contention.
12 - maxWorkers: 3,
11 + projects: [
12 + {
13 + extends: true,
14 + test: {
15 + name: "fast",
16 + include,
17 + exclude: [...exclude, "extensions/web/**"],
18 + isolate: false,
19 + // Three fork workers avoid CPU/process contention.
20 + maxWorkers: 3,
21 + },
22 + },
23 + {
24 + extends: true,
25 + test: {
26 + name: "web",
27 + include: ["extensions/web/**/__tests__/**/*.test.ts"],
28 + exclude,
29 + isolate: true,
30 + maxWorkers: 1,
31 + },
32 + },
33 + ],