repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

rework extension continuity ownership

33eca6ac0f1c902043efd7eb73f317c38df3ef8a

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (26)

README.md

Modified
71 71 | `angel` | Structured advisor and command guardrail for configured Pi model pairs. | [README](extensions/angel/README.md) |
72 72 | `cmprss` | Compress oversized tool results with exact retrieval. | [README](extensions/cmprss/README.md) |
73 73 | `context-size` | Context-window usage telemetry for Pi. | [README](extensions/context-size/README.md) |
74 +| `continuity` | Continue Pi tasks after context compaction. | [README](extensions/continuity/README.md) |
74 75 | `cost` | Token and spend telemetry for Pi. | [README](extensions/cost/README.md) |
75 76 | `cwd` | Switch Pi cwd without leaving the session. | [README](extensions/cwd/README.md) |
76 77 | `devil` | Structured `/devil` command for stress-testing an idea. | [README](extensions/devil/README.md) |
107 108 ## Resources
109 -The root package exports extension entrypoints and extension-owned skills only.
110 +The root package exports extension entrypoints only.
110 111 Personal skills, prompts, and themes live in global Pi config.
112 113 ```json
114 - "extensions": ["extensions/*/index.ts"],
115 - "skills": ["extensions/lazy/skills"]
115 + "extensions": ["extensions/*/index.ts"]

extensions/continuity/README.md

Added
new file mode 100644
1 +# continuity
3 +Continues the current Pi task after context compaction.
5 +## Install / load
7 +Loaded through the root `pi-ext` package.
8 +See [../../README.md](../../README.md).
10 +## Commands / tools / settings
12 +No commands, tools, or settings.
14 +Pi hooks:
16 +- `session_compact` schedules continuation after successful compaction.
17 +- `agent_start` cancels stale scheduled continuation when another run takes over.
18 +- `session_shutdown` clears scheduled continuation.
20 +## Behavior
22 +Continuity sends one hidden follow-up after manual, threshold, or non-retrying overflow compaction.
23 +The follow-up uses Pi's compaction summary and current worktree first.
24 +It points at persisted active-branch history only as fallback when recovered intent remains unclear.
26 +Pi's own overflow retry wins.
27 +Existing queued messages win.
28 +Active `/goal` and `/tune` continuation capabilities win.
29 +Session replacement and shutdown cancel stale delivery.

extensions/continuity/__tests__/harness.test.ts

Added
new file mode 100644
1 +import path from "node:path";
2 +import { afterEach, describe, expect, it, vi } from "vitest";
3 +import { createTestSession, type TestSession } from "../../../test/harness";
5 +describe("continuity pi-test-harness", () => {
6 + let t: TestSession | undefined;
8 + afterEach(() => {
9 + t?.dispose();
10 + t = undefined;
11 + });
13 + it("loads through the real Pi extension runtime", async () => {
14 + const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
15 + t = await createTestSession({ extensions: [extensionPath] });
17 + expect(t.session.extensionRunner.extensions).toHaveLength(1);
18 + expect(t.session.extensionRunner.extensions[0].path).toBe(extensionPath);
19 + });
21 + it("dispatches a hidden follow-up through the real Pi binding", async () => {
22 + const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
23 + t = await createTestSession({ extensions: [extensionPath] });
24 + const send = vi
25 + .spyOn(t.session, "sendCustomMessage")
26 + .mockResolvedValue(undefined);
28 + await t.session.extensionRunner.emit({
29 + type: "session_compact",
30 + compactionEntry: { id: "compact-real" },
31 + fromExtension: false,
32 + reason: "manual",
33 + willRetry: false,
34 + });
35 + await new Promise((resolve) => setTimeout(resolve, 10));
37 + expect(send).toHaveBeenCalledOnce();
38 + expect(send).toHaveBeenCalledWith(
39 + expect.objectContaining({
40 + customType: "continuity-resume",
41 + display: false,
42 + }),
43 + { triggerTurn: true, deliverAs: "followUp" },
44 + );
45 + });
46 +});

extensions/continuity/__tests__/unit.test.ts

Added
new file mode 100644
1 +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2 +import continuityExtension, {
3 + __test,
4 + buildContinuationPrompt,
5 +} from "../index.ts";
7 +type Handler = (event: any, ctx: any) => unknown;
9 +function compactionEvent(
10 + overrides: Record<string, unknown> = {},
11 +): Record<string, unknown> {
12 + return {
13 + type: "session_compact",
14 + compactionEntry: { id: "compact-1" },
15 + fromExtension: false,
16 + reason: "manual",
17 + willRetry: false,
18 + ...overrides,
19 + };
22 +function createHarness() {
23 + const handlers = new Map<string, Handler[]>();
24 + const sent: Array<{ message: any; options: any }> = [];
25 + const notices: Array<[string, string]> = [];
26 + let activeTools: string[] = [];
27 + let idle = true;
28 + let pendingMessages = false;
29 + let sessionId = "session-1";
30 + let sessionFile: string | undefined = "/sessions/work.jsonl";
31 + let branch: any[] = [];
32 + let sendError: Error | undefined;
34 + const pi = {
35 + on(event: string, handler: Handler) {
36 + handlers.set(event, [...(handlers.get(event) ?? []), handler]);
37 + },
38 + getActiveTools: () => activeTools,
39 + sendMessage(message: any, options: any) {
40 + if (sendError) throw sendError;
41 + sent.push({ message, options });
42 + },
43 + };
44 + const ctx = {
45 + isIdle: () => idle,
46 + hasPendingMessages: () => pendingMessages,
47 + sessionManager: {
48 + getSessionId: () => sessionId,
49 + getSessionFile: () => sessionFile,
50 + getBranch: () => branch,
51 + },
52 + ui: {
53 + notify(message: string, severity: string) {
54 + notices.push([message, severity]);
55 + },
56 + },
57 + };
58 + continuityExtension(pi as never);
60 + return {
61 + sent,
62 + notices,
63 + ctx,
64 + emit(event: string, payload: any = {}) {
65 + for (const handler of handlers.get(event) ?? []) handler(payload, ctx);
66 + },
67 + setActiveTools(names: string[]) {
68 + activeTools = names;
69 + },
70 + setIdle(value: boolean) {
71 + idle = value;
72 + },
73 + setPendingMessages(value: boolean) {
74 + pendingMessages = value;
75 + },
76 + setSessionId(value: string) {
77 + sessionId = value;
78 + },
79 + setSessionFile(value: string | undefined) {
80 + sessionFile = value;
81 + },
82 + setBranch(value: any[]) {
83 + branch = value;
84 + },
85 + setSendError(error: Error | undefined) {
86 + sendError = error;
87 + },
88 + };
91 +beforeEach(() => vi.useFakeTimers());
92 +afterEach(() => vi.useRealTimers());
94 +describe("continuation prompt", () => {
95 + it("uses the summary first and persisted active history only as fallback", () => {
96 + const prompt = buildContinuationPrompt(
97 + '/sessions/a "quoted" session.jsonl',
98 + "compact-7",
99 + );
101 + expect(prompt).toContain(
102 + "Use the compaction summary and current worktree first.",
103 + );
104 + expect(prompt).toContain(
105 + 'Persisted session JSONL: "/sessions/a \\"quoted\\" session.jsonl".',
106 + );
107 + expect(prompt).toContain("following parentId links");
108 + expect(prompt).toContain("Do not treat append order as branch order");
109 + expect(prompt).toContain('Compaction entry ID: "compact-7".');
110 + expect(prompt).toContain("immediately perform the next unfinished step");
111 + });
113 + it("handles ephemeral sessions without claiming history exists", () => {
114 + const prompt = buildContinuationPrompt(undefined, "compact-1");
116 + expect(prompt).toContain("This session is ephemeral");
117 + expect(prompt).not.toContain("Persisted session JSONL");
118 + expect(prompt).toContain('Compaction entry ID: "compact-1".');
119 + });
120 +});
122 +describe("continuity lifecycle", () => {
123 + it.each(["manual", "threshold"])(
124 + "continues once after successful %s compaction",
125 + async (reason) => {
126 + const h = createHarness();
128 + h.emit("session_compact", compactionEvent({ reason }));
129 + await vi.runAllTimersAsync();
131 + expect(h.sent).toHaveLength(1);
132 + expect(h.sent[0].message).toMatchObject({
133 + customType: __test.CONTINUATION_TYPE,
134 + display: false,
135 + details: { compactionEntryId: "compact-1", reason },
136 + });
137 + expect(h.sent[0].options).toEqual({
138 + triggerTurn: true,
139 + deliverAs: "followUp",
140 + });
141 + },
142 + );
144 + it("does not duplicate Pi's overflow retry", async () => {
145 + const h = createHarness();
147 + h.emit(
148 + "session_compact",
149 + compactionEvent({ reason: "overflow", willRetry: true }),
150 + );
151 + await vi.runAllTimersAsync();
153 + expect(h.sent).toEqual([]);
154 + });
156 + it("continues after non-retrying overflow compaction", async () => {
157 + const h = createHarness();
159 + h.emit(
160 + "session_compact",
161 + compactionEvent({ reason: "overflow", willRetry: false }),
162 + );
163 + await vi.runAllTimersAsync();
165 + expect(h.sent).toHaveLength(1);
166 + });
168 + it("leaves an already queued continuation or user message alone", async () => {
169 + const h = createHarness();
170 + h.setPendingMessages(true);
172 + h.emit("session_compact", compactionEvent());
173 + await vi.runAllTimersAsync();
175 + expect(h.sent).toEqual([]);
176 + });
178 + it("yields when a message becomes pending during deferral", async () => {
179 + const h = createHarness();
181 + h.emit("session_compact", compactionEvent());
182 + h.setPendingMessages(true);
183 + await vi.runAllTimersAsync();
185 + expect(h.sent).toEqual([]);
186 + });
188 + it("yields when another run starts during deferral", async () => {
189 + const h = createHarness();
191 + h.emit("session_compact", compactionEvent());
192 + h.emit("agent_start");
193 + await vi.runAllTimersAsync();
195 + expect(h.sent).toEqual([]);
196 + });
198 + it("does not dispatch while Pi remains busy", async () => {
199 + const h = createHarness();
200 + h.setIdle(false);
202 + h.emit("session_compact", compactionEvent());
203 + await vi.runAllTimersAsync();
205 + expect(h.sent).toEqual([]);
206 + });
208 + it("does not deliver into a replacement session", async () => {
209 + const h = createHarness();
211 + h.emit("session_compact", compactionEvent());
212 + h.setSessionId("session-2");
213 + await vi.runAllTimersAsync();
215 + expect(h.sent).toEqual([]);
216 + });
218 + it("replaces an obsolete scheduled continuation with the latest compaction", async () => {
219 + const h = createHarness();
221 + h.emit("session_compact", compactionEvent());
222 + h.emit(
223 + "session_compact",
224 + compactionEvent({ compactionEntry: { id: "compact-2" } }),
225 + );
226 + await vi.runAllTimersAsync();
228 + expect(h.sent).toHaveLength(1);
229 + expect(h.sent[0].message.details.compactionEntryId).toBe("compact-2");
230 + });
232 + it("clears scheduled work on session shutdown", async () => {
233 + const h = createHarness();
235 + h.emit("session_compact", compactionEvent());
236 + h.emit("session_shutdown");
237 + await vi.runAllTimersAsync();
239 + expect(h.sent).toEqual([]);
240 + });
242 + it.each(["update_goal", "run_experiment", "log_experiment"])(
243 + "yields to specialized continuation capability %s",
244 + async (tool) => {
245 + const h = createHarness();
246 + h.setActiveTools([tool]);
248 + h.emit("session_compact", compactionEvent());
249 + await vi.runAllTimersAsync();
251 + expect(h.sent).toEqual([]);
252 + },
253 + );
255 + it("yields to an active first-turn goal before update_goal becomes active", async () => {
256 + const h = createHarness();
257 + h.setBranch([
259 + type: "custom",
260 + customType: __test.GOAL_STATE_TYPE,
261 + data: { status: "active", sessionId: "session-1", turnsUsed: 0 },
262 + },
263 + ]);
265 + h.emit("session_compact", compactionEvent());
266 + await vi.runAllTimersAsync();
268 + expect(h.sent).toEqual([]);
269 + });
271 + it.each([
272 + ["paused goal", { status: "paused", sessionId: "session-1" }],
273 + ["foreign goal", { status: "active", sessionId: "session-2" }],
274 + ["cleared goal", { cleared: true }],
275 + ])("does not yield to %s state", async (_name, data) => {
276 + const h = createHarness();
277 + h.setBranch([{ type: "custom", customType: __test.GOAL_STATE_TYPE, data }]);
279 + h.emit("session_compact", compactionEvent());
280 + await vi.runAllTimersAsync();
282 + expect(h.sent).toHaveLength(1);
283 + });
285 + it("uses the latest goal state event", async () => {
286 + const h = createHarness();
287 + h.setBranch([
289 + type: "custom",
290 + customType: __test.GOAL_STATE_TYPE,
291 + data: { status: "active", sessionId: "session-1" },
292 + },
294 + type: "custom",
295 + customType: __test.GOAL_STATE_TYPE,
296 + data: { status: "paused", sessionId: "session-1" },
297 + },
298 + ]);
300 + h.emit("session_compact", compactionEvent());
301 + await vi.runAllTimersAsync();
303 + expect(h.sent).toHaveLength(1);
304 + });
306 + it("rechecks specialized continuation capabilities during deferral", async () => {
307 + const h = createHarness();
309 + h.emit("session_compact", compactionEvent());
310 + h.setActiveTools(["update_goal"]);
311 + await vi.runAllTimersAsync();
313 + expect(h.sent).toEqual([]);
314 + });
316 + it("does not yield merely because inactive goal and tune tools exist", async () => {
317 + const h = createHarness();
318 + h.setActiveTools(["read", "bash"]);
320 + h.emit("session_compact", compactionEvent());
321 + await vi.runAllTimersAsync();
323 + expect(h.sent).toHaveLength(1);
324 + });
326 + it("reports dispatch failures without throwing from the timer", async () => {
327 + const h = createHarness();
328 + h.setSendError(new Error("stale runtime"));
330 + h.emit("session_compact", compactionEvent());
331 + await vi.runAllTimersAsync();
333 + expect(h.sent).toEqual([]);
334 + expect(h.notices).toEqual([
335 + ["Continuity could not resume: stale runtime", "error"],
336 + ]);
337 + });
339 + it("uses ephemeral context from the live session", async () => {
340 + const h = createHarness();
341 + h.setSessionFile(undefined);
343 + h.emit("session_compact", compactionEvent());
344 + await vi.runAllTimersAsync();
346 + expect(h.sent[0].message.content).toContain("This session is ephemeral");
347 + });
348 +});

extensions/continuity/index.ts

Added
new file mode 100644
1 +import type {
2 + ExtensionAPI,
3 + ExtensionContext,
4 + SessionCompactEvent,
5 +} from "@earendil-works/pi-coding-agent";
7 +const CONTINUATION_TYPE = "continuity-resume";
8 +const GOAL_STATE_TYPE = "goal-state";
9 +const SPECIALIZED_CONTINUATION_TOOLS = new Set([
10 + "update_goal",
11 + "run_experiment",
12 + "log_experiment",
13 +]);
15 +type PendingContinuation = {
16 + sessionId: string;
17 + timer: ReturnType<typeof setTimeout>;
18 +};
20 +export function buildContinuationPrompt(
21 + sessionFile: string | undefined,
22 + compactionEntryId: string,
23 +): string {
24 + const sessionSource =
25 + sessionFile === undefined
26 + ? "This session is ephemeral, so no persisted history is available."
27 + : [
28 + `Persisted session JSONL: ${JSON.stringify(sessionFile)}.`,
29 + "If the summary leaves intent or the next action unclear, inspect only the active branch ending at the compaction entry by following parentId links.",
30 + "Do not treat append order as branch order and do not launch a nested Pi process.",
31 + ].join(" ");
33 + return [
34 + "Compaction completed. Continue the existing task now instead of waiting for user input.",
35 + "Use the compaction summary and current worktree first.",
36 + sessionSource,
37 + `Compaction entry ID: ${JSON.stringify(compactionEntryId)}.`,
38 + "The worktree is authoritative for file state; session history is authoritative for user intent and constraints.",
39 + "Briefly state the recovered context, then immediately perform the next unfinished step.",
40 + "Do not stop after the recap or ask the user to repeat context unless it remains genuinely unavailable or ambiguous.",
41 + ].join("\n\n");
44 +function isRecord(value: unknown): value is Record<string, unknown> {
45 + return value !== null && typeof value === "object" && !Array.isArray(value);
48 +function hasActiveGoal(ctx: ExtensionContext): boolean {
49 + const sessionId = ctx.sessionManager.getSessionId();
50 + const entries = ctx.sessionManager.getBranch();
51 + for (let index = entries.length - 1; index >= 0; index--) {
52 + const entry = entries[index];
53 + if (
54 + entry.type !== "custom" ||
55 + entry.customType !== GOAL_STATE_TYPE ||
56 + !isRecord(entry.data)
57 + )
58 + continue;
59 + return (
60 + entry.data.status === "active" &&
61 + (entry.data.sessionId === undefined || entry.data.sessionId === sessionId)
62 + );
63 + }
64 + return false;
67 +function hasSpecializedContinuation(
68 + pi: ExtensionAPI,
69 + ctx: ExtensionContext,
70 +): boolean {
71 + return (
72 + hasActiveGoal(ctx) ||
73 + pi.getActiveTools().some((name) => SPECIALIZED_CONTINUATION_TOOLS.has(name))
74 + );
77 +export default function continuityExtension(pi: ExtensionAPI): void {
78 + let pending: PendingContinuation | undefined;
80 + const cancelPending = (): void => {
81 + if (!pending) return;
82 + clearTimeout(pending.timer);
83 + pending = undefined;
84 + };
86 + const sameSession = (ctx: ExtensionContext, sessionId: string): boolean => {
87 + try {
88 + return ctx.sessionManager.getSessionId() === sessionId;
89 + } catch {
90 + return false;
91 + }
92 + };
94 + const scheduleContinuation = (
95 + event: SessionCompactEvent,
96 + ctx: ExtensionContext,
97 + ): void => {
98 + cancelPending();
99 + if (
100 + event.willRetry ||
101 + ctx.hasPendingMessages() ||
102 + hasSpecializedContinuation(pi, ctx)
104 + return;
106 + const sessionId = ctx.sessionManager.getSessionId();
107 + const prompt = buildContinuationPrompt(
108 + ctx.sessionManager.getSessionFile(),
109 + event.compactionEntry.id,
110 + );
111 + const candidate: PendingContinuation = {
112 + sessionId,
113 + timer: setTimeout(() => {
114 + if (pending !== candidate) return;
115 + pending = undefined;
116 + if (
117 + !sameSession(ctx, sessionId) ||
118 + !ctx.isIdle() ||
119 + ctx.hasPendingMessages() ||
120 + hasSpecializedContinuation(pi, ctx)
122 + return;
123 + try {
124 + pi.sendMessage(
126 + customType: CONTINUATION_TYPE,
127 + content: prompt,
128 + display: false,
129 + details: {
130 + compactionEntryId: event.compactionEntry.id,
131 + reason: event.reason,
132 + },
133 + },
134 + { triggerTurn: true, deliverAs: "followUp" },
135 + );
136 + } catch (error) {
137 + ctx.ui.notify(
138 + `Continuity could not resume: ${error instanceof Error ? error.message : String(error)}`,
139 + "error",
140 + );
142 + }, 0),
143 + };
144 + pending = candidate;
145 + };
147 + pi.on("session_compact", scheduleContinuation);
148 + pi.on("agent_start", cancelPending);
149 + pi.on("session_shutdown", cancelPending);
152 +export const __test = {
153 + CONTINUATION_TYPE,
154 + GOAL_STATE_TYPE,
155 + SPECIALIZED_CONTINUATION_TOOLS,
156 + hasActiveGoal,

extensions/continuity/package.json

Added
new file mode 100644
1 +{
2 + "name": "@bugabinga/pi-ext-continuity",
3 + "private": true,
4 + "type": "module",
5 + "main": "index.ts",
6 + "peerDependencies": {
7 + "@earendil-works/pi-coding-agent": "*"
8 + },
9 + "devDependencies": {
10 + "@marcfargas/pi-test-harness": "^0.6.1",
11 + "vitest": "^4.1.9"
12 + },
13 + "scripts": {
14 + "test:harness": "vitest run ./__tests__/harness.test.ts",
15 + "test": "vitest run ./__tests__/*.test.ts"
16 + },
17 + "license": "MIT",
18 + "description": "Continue Pi tasks after context compaction.",
19 + "keywords": [
20 + "pi",
21 + "pi-extension",
22 + "compaction"
23 + ]

extensions/lazy/README.md

Deleted
deleted file mode 100644
1 -# lazy
3 -Pi-native lazy senior dev mode.
5 -## Commands
7 -- `/lazy` enables configured default mode; default `off` falls back to `full`.
8 -- `/lazy lite|full|ultra|off` sets session mode.
9 -- `/lazy status` reports session and default mode.
10 -- `/lazy default <mode>` prints the Pi settings JSON to add.
11 -- `/lazy-review [args]` asks the agent to review current diff for over-engineering only.
12 -- `/lazy-audit [args]` asks the agent to scan the repo for over-engineering.
13 -- `/lazy-debt` lists `lazy:` shortcut markers.
14 -- `/lazy-gain` prints published benchmark medians.
15 -- `/lazy-help` prints compact help.
17 -## Settings
19 -```json
20 -{
21 - "lazy": {
22 - "defaultMode": "full",
23 - "status": true
24 - }
25 -}
26 -```
28 -Valid modes: `off`, `lite`, `full`, `ultra`.
30 -## Deactivation
32 -Type `stop lazy` or `normal mode` as a standalone message.

extensions/lazy/__tests__/harness.test.ts

Deleted
deleted file mode 100644
1 -import { execFileSync } from "node:child_process";
2 -import { mkdirSync, writeFileSync } from "node:fs";
3 -import path from "node:path";
4 -import { fileURLToPath } from "node:url";
5 -import { afterEach, describe, expect, it } from "vitest";
6 -import { createTestSession, type TestSession } from "../../../test/harness";
7 -import lazyExtension from "../index.ts";
9 -let t: TestSession | undefined;
11 -function extensionPath(): string {
12 - return fileURLToPath(new URL("../index.ts", import.meta.url));
15 -function command(name: string) {
16 - const cmd = t?.session.extensionRunner.extensions[0].commands.get(name);
17 - if (!cmd) throw new Error(`missing command: ${name}`);
18 - return cmd;
21 -async function runCommand(name: string, args = ""): Promise<void> {
22 - if (!t) throw new Error("missing test session");
23 - await command(name).handler(
24 - args,
25 - t.session.extensionRunner.createCommandContext(),
26 - );
29 -function uiArgs(method: string): unknown[][] {
30 - return t?.events.uiCallsFor(method).map((call) => call.args) ?? [];
33 -function customEntries(kind: string): Array<Record<string, unknown>> {
34 - if (!t) throw new Error("missing test session");
35 - return (
36 - t.session.sessionManager.getEntries() as Array<{
37 - type: string;
38 - customType?: string;
39 - data?: Record<string, unknown>;
40 - }>
41 - )
42 - .filter((entry) => entry.type === "custom" && entry.customType === kind)
43 - .map((entry) => entry.data ?? {});
46 -afterEach(() => {
47 - t?.dispose();
48 - t = undefined;
49 -});
51 -describe("lazy harness", () => {
52 - it("loads in real Pi extension runtime and registers commands", async () => {
53 - t = await createTestSession({ extensions: [extensionPath()] });
54 - expect([
55 - ...t.session.extensionRunner.extensions[0].commands.keys(),
56 - ]).toEqual([
57 - "lazy",
58 - "lazy-review",
59 - "lazy-audit",
60 - "lazy-debt",
61 - "lazy-gain",
62 - "lazy-help",
63 - ]);
64 - });
66 - it("/lazy ultra appends mode and updates status", async () => {
67 - t = await createTestSession({ extensions: [extensionPath()] });
68 - await runCommand("lazy", "ultra");
69 - expect(customEntries("lazy-mode").at(-1)).toEqual({
70 - mode: "ultra",
71 - at: expect.any(Number),
72 - });
73 - expect(uiArgs("setStatus").at(-1)).toEqual(["lazy", "○ lazy: ultra"]);
74 - });
76 - it("injects instructions when active and returns undefined when off", async () => {
77 - t = await createTestSession({ extensions: [extensionPath()] });
78 - let result = await t.session.extensionRunner.emitBeforeAgentStart(
79 - "hello",
80 - undefined,
81 - "BASE",
82 - {} as never,
83 - );
84 - expect(result?.systemPrompt).toContain("LAZY MODE ACTIVE — level: full");
85 - await runCommand("lazy", "full");
86 - result = await t.session.extensionRunner.emitBeforeAgentStart(
87 - "hello",
88 - undefined,
89 - "BASE",
90 - {} as never,
91 - );
92 - expect(result?.systemPrompt).toContain("LAZY MODE ACTIVE — level: full");
93 - await runCommand("lazy", "off");
94 - result = await t.session.extensionRunner.emitBeforeAgentStart(
95 - "hello",
96 - undefined,
97 - "BASE",
98 - {} as never,
99 - );
100 - expect(result).toBeUndefined();
101 - });
103 - it("skill alias commands send immediately when idle and follow-up when streaming", async () => {
104 - t = await createTestSession({ extensions: [extensionPath()] });
105 - const sent: Array<{ content: unknown; options: unknown }> = [];
106 - t.session.extensionRunner.runtime.sendUserMessage = (
107 - content: unknown,
108 - options: unknown,
109 - ) => sent.push({ content, options });
110 - await runCommand("lazy-review", "src/a.ts");
111 - const ctx = t.session.extensionRunner.createCommandContext();
112 - ctx.isIdle = () => false;
113 - await command("lazy-audit").handler("src", ctx);
114 - expect(sent).toEqual([
115 - { content: "/skill:lazy-review src/a.ts", options: undefined },
116 - { content: "/skill:lazy-audit src", options: { deliverAs: "followUp" } },
117 - ]);
118 - });
120 - it("/lazy-debt produces deterministic output without mutating files", async () => {
121 - t = await createTestSession({ extensions: [extensionPath()] });
122 - mkdirSync(`${t.cwd}/src`, { recursive: true });
123 - writeFileSync(`${t.cwd}/src/a.ts`, "// lazy: fake until real API\n");
124 - await runCommand("lazy-debt");
125 - expect(uiArgs("notify").at(-1)?.[0]).toContain(
126 - "src/a.ts:1 ceiling: fake trigger: real API",
127 - );
128 - });
130 - it("status marks active generation and clears back to inactive", async () => {
131 - t = await createTestSession({ extensions: [extensionPath()] });
132 - await runCommand("lazy", "ultra");
133 - t.events.ui.length = 0;
134 - await t.session.extensionRunner.emit({ type: "agent_start" } as never);
135 - expect(uiArgs("setStatus").at(-1)).toEqual(["lazy", "● lazy: ultra"]);
136 - await t.session.extensionRunner.emit({
137 - type: "agent_end",
138 - messages: [],
139 - } as never);
140 - expect(uiArgs("setStatus").at(-1)).toEqual(["lazy", "○ lazy: ultra"]);
141 - });
143 - it("standalone deactivation turns lazy off and clears status", async () => {
144 - t = await createTestSession({ extensions: [extensionPath()] });
145 - await runCommand("lazy", "ultra");
146 - t.events.ui.length = 0;
147 - await t.session.extensionRunner.emit({
148 - type: "input",
149 - text: "normal mode.",
150 - source: "interactive",
151 - } as never);
152 - expect(customEntries("lazy-mode").at(-1)).toEqual({
153 - mode: "off",
154 - at: expect.any(Number),
155 - });
156 - expect(uiArgs("setStatus").at(-1)).toEqual(["lazy", undefined]);
157 - });
159 - it("status gracefully does nothing when disabled", async () => {
160 - t = await createTestSession({ extensionFactories: [lazyExtension] });
161 - mkdirSync(path.join(t.cwd, ".pi"), { recursive: true });
162 - writeFileSync(
163 - path.join(t.cwd, ".pi", "settings.json"),
164 - JSON.stringify({ lazy: { status: false } }),
165 - );
166 - t.events.ui.length = 0;
167 - await runCommand("lazy", "ultra");
168 - expect(uiArgs("setStatus")).toEqual([]);
169 - });
171 - it("agent_end notifies for newly added lazy markers", async () => {
172 - t = await createTestSession({ extensions: [extensionPath()] });
173 - execFileSync("git", ["init", "-q"], { cwd: t.cwd });
174 - execFileSync("git", ["config", "core.autocrlf", "false"], {
175 - cwd: t.cwd,
176 - });
177 - execFileSync("git", ["config", "user.email", "lazy@example.invalid"], {
178 - cwd: t.cwd,
179 - });
180 - execFileSync("git", ["config", "user.name", "Lazy"], { cwd: t.cwd });
181 - writeFileSync(`${t.cwd}/a.ts`, "const x = 1;\n");
182 - execFileSync("git", ["add", "a.ts"], { cwd: t.cwd });
183 - execFileSync("git", ["commit", "-qm", "initial"], { cwd: t.cwd });
184 - writeFileSync(
185 - `${t.cwd}/a.ts`,
186 - "const x = 1;\n// lazy: fake until real API\n",
187 - );
188 - await t.session.extensionRunner.emit({
189 - type: "agent_end",
190 - messages: [],
191 - } as never);
192 - expect(uiArgs("notify").at(-1)).toEqual([
193 - "lazy debt added: 1 marker(s) in 1 file(s). Run /lazy-debt.",
194 - "info",
195 - ]);
196 - });
197 -});

extensions/lazy/__tests__/unit.test.ts

Deleted
deleted file mode 100644
1 -import { mkdirSync, writeFileSync } from "node:fs";
2 -import { mkdtemp, rm } from "node:fs/promises";
3 -import { tmpdir } from "node:os";
4 -import path from "node:path";
5 -import { afterEach, describe, expect, it } from "vitest";
6 -import lazyExtension from "../index.ts";
7 -import {
8 - loadLazySettingsForCwd,
9 - mergeLazySettings,
10 - pickLazy,
11 - settingsSnippet,
12 -} from "../src/config.ts";
13 -import {
14 - formatDebt,
15 - markersFromUnifiedDiff,
16 - parseLazyMarker,
17 - scanLazyDebt,
18 -} from "../src/debt.ts";
19 -import {
20 - buildLazyInstructions,
21 - injectLazyInstructions,
22 -} from "../src/instructions.ts";
23 -import {
24 - isStandaloneDeactivation,
25 - modeFromBareDefault,
26 - normalizeMode,
27 - parseLazyCommand,
28 -} from "../src/modes.ts";
30 -let dirs: string[] = [];
32 -afterEach(async () => {
33 - for (const dir of dirs) await rm(dir, { recursive: true, force: true });
34 - dirs = [];
35 -});
37 -async function tempDir(): Promise<string> {
38 - const dir = await mkdtemp(path.join(tmpdir(), "lazy-test-"));
39 - dirs.push(dir);
40 - return dir;
43 -describe("modes", () => {
44 - it("normalizes only lazy modes", () => {
45 - expect(normalizeMode("OFF")).toBe("off");
46 - expect(normalizeMode("lite")).toBe("lite");
47 - expect(normalizeMode("review")).toBeUndefined();
48 - });
50 - it("falls back from default off to full for bare command", () => {
51 - expect(modeFromBareDefault("off")).toBe("full");
52 - expect(parseLazyCommand("", "off")).toEqual({ kind: "set", mode: "full" });
53 - });
55 - it("parses status and default", () => {
56 - expect(parseLazyCommand("status", "full")).toEqual({ kind: "status" });
57 - expect(parseLazyCommand("/lazy status", "full")).toEqual({
58 - kind: "status",
59 - });
60 - expect(parseLazyCommand("default ultra", "full")).toEqual({
61 - kind: "default",
62 - mode: "ultra",
63 - });
64 - });
66 - it("matches only standalone deactivation", () => {
67 - expect(isStandaloneDeactivation("stop lazy!")).toBe(true);
68 - expect(isStandaloneDeactivation("normal mode.")).toBe(true);
69 - expect(isStandaloneDeactivation("add a normal mode toggle")).toBe(false);
70 - });
71 -});
73 -describe("config", () => {
74 - it("picks and merges valid lazy settings only", () => {
75 - expect(
76 - pickLazy({ lazy: { defaultMode: "ultra", status: false, nope: true } }),
77 - ).toEqual({ defaultMode: "ultra", status: false });
78 - expect(pickLazy({ lazy: { defaultMode: "review" } })).toEqual({});
79 - expect(
80 - mergeLazySettings({ defaultMode: "lite" }, { status: false }),
81 - ).toEqual({
82 - defaultMode: "lite",
83 - status: false,
84 - });
85 - });
87 - it("loads runtime Pi settings and ignores workspace-root settings.json", async () => {
88 - const dir = await tempDir();
89 - writeFileSync(
90 - path.join(dir, "settings.json"),
91 - JSON.stringify({ lazy: { defaultMode: "lite" } }),
92 - );
94 - mkdirSync(path.join(dir, ".pi"));
95 - writeFileSync(
96 - path.join(dir, ".pi", "settings.json"),
97 - JSON.stringify({ lazy: { defaultMode: "ultra" } }),
98 - );
99 - expect(loadLazySettingsForCwd(dir).defaultMode).toBe("ultra");
101 - writeFileSync(path.join(dir, ".pi", "settings.json"), "{}");
102 - expect(loadLazySettingsForCwd(dir).defaultMode).toBe("full");
103 - });
105 - it("prints settings snippet", () => {
106 - expect(settingsSnippet("off")).toContain('"defaultMode": "off"');
107 - });
108 -});
110 -describe("instructions", () => {
111 - it("builds active header and excludes inactive mode lines", () => {
112 - const block = buildLazyInstructions("lite");
113 - expect(block).toContain("LAZY MODE ACTIVE — level: lite");
114 - expect(block).toContain("Root-cause bug-fix rule:");
115 - expect(block).not.toContain("Deletion first");
116 - });
118 - it("includes concrete over-engineering guardrails", () => {
119 - const block = buildLazyInstructions("full");
120 - expect(block).toContain("No unrequested abstractions");
121 - expect(block).toContain("same size");
122 - expect(block).toContain("`lazy:`");
123 - });
125 - it("before_agent_start tolerates a missing event or prompt", () => {
126 - const events = new Map<string, (...args: never[]) => unknown>();
127 - lazyExtension({
128 - on: (name: string, handler: (...args: never[]) => unknown) =>
129 - events.set(name, handler),
130 - registerCommand: () => undefined,
131 - appendEntry: () => undefined,
132 - } as never);
133 - const ctx = {
134 - cwd: "/",
135 - hasUI: false,
136 - sessionManager: { getBranch: () => [] },
137 - };
138 - events.get("session_start")?.({} as never, ctx as never);
139 - const missingEvent = events.get("before_agent_start")?.(undefined as never);
140 - const missingPrompt = events.get("before_agent_start")?.({} as never);
141 - expect(missingEvent).toEqual({
142 - systemPrompt: expect.stringContaining("LAZY MODE ACTIVE"),
143 - });
144 - expect(JSON.stringify(missingEvent)).not.toContain("undefined");
145 - expect(missingPrompt).toEqual({
146 - systemPrompt: expect.stringContaining("LAZY MODE ACTIVE"),
147 - });
148 - });
150 - it("injects idempotently", () => {
151 - const once = injectLazyInstructions("BASE", "full");
152 - const twice = injectLazyInstructions(once, "ultra");
153 - expect(twice.match(/LAZY MODE ACTIVE/g)).toHaveLength(1);
154 - expect(twice).toContain("level: ultra");
155 - expect(twice).not.toContain("level: full");
156 - });
157 -});
159 -describe("debt", () => {
160 - it("parses markers and missing triggers", () => {
161 - expect(
162 - parseLazyMarker("// lazy: cap at 10 until > 10 users", "a.ts", 3),
163 - ).toEqual({
164 - file: "a.ts",
165 - line: 3,
166 - ceiling: "cap at 10",
167 - trigger: "> 10 users",
168 - noTrigger: false,
169 - });
170 - expect(parseLazyMarker("# lazy: ship quick", "a.sh", 1)?.noTrigger).toBe(
171 - true,
172 - );
173 - });
175 - it("scans repo and skips heavy dirs", async () => {
176 - const dir = await tempDir();
177 - mkdirSync(path.join(dir, "src"), { recursive: true });
178 - mkdirSync(path.join(dir, "node_modules"), { recursive: true });
179 - writeFileSync(
180 - path.join(dir, "src", "a.ts"),
181 - "// lazy: rough until API stable\n",
182 - );
183 - writeFileSync(path.join(dir, "node_modules", "b.ts"), "// lazy: nope\n");
184 - const result = scanLazyDebt(dir);
185 - expect(result.markers).toHaveLength(1);
186 - expect(formatDebt(result)).toContain(
187 - "src/a.ts:1 ceiling: rough trigger: API stable",
188 - );
189 - });
191 - it("extracts added markers from unified diff", () => {
192 - const diff = [
193 - "diff --git a/a.ts b/a.ts",
194 - "+++ b/a.ts",
195 - "@@ -0,0 +1,2 @@",
196 - "+const x = 1;",
197 - "+// lazy: fake until real API",
198 - ].join("\n");
199 - expect(markersFromUnifiedDiff(diff)).toEqual([
200 - {
201 - file: "a.ts",
202 - line: 2,
203 - ceiling: "fake",
204 - trigger: "real API",
205 - noTrigger: false,
206 - },
207 - ]);
208 - });
209 -});

extensions/lazy/index.ts

Deleted
deleted file mode 100644
1 -import type {
2 - ExtensionAPI,
3 - ExtensionContext,
4 -} from "@earendil-works/pi-coding-agent";
5 -import type { AutocompleteItem } from "@earendil-works/pi-tui";
6 -import { loadLazySettingsForCwd, settingsSnippet } from "./src/config.ts";
7 -import {
8 - formatDebt,
9 - markersFromUnifiedDiff,
10 - scanLazyDebt,
11 -} from "./src/debt.ts";
12 -import { injectLazyInstructions } from "./src/instructions.ts";
13 -import {
14 - type ActiveLazyMode,
15 - isStandaloneDeactivation,
16 - type LazyMode,
17 - parseLazyCommand,
18 -} from "./src/modes.ts";
19 -import { gainText, helpText, statusSegment, statusText } from "./src/ui.ts";
21 -const ENTRY_TYPE = "lazy-mode";
22 -const STATUS_KEY = "lazy";
24 -type EntryLike = { type?: unknown; customType?: unknown; data?: unknown };
25 -type ModeEntry = { mode: LazyMode; at: number };
27 -type State = {
28 - mode: LazyMode;
29 - activeGeneration: boolean;
30 -};
32 -function modeEntry(data: unknown): ModeEntry | undefined {
33 - if (!data || typeof data !== "object") return undefined;
34 - const entry = data as Record<string, unknown>;
35 - if (
36 - (entry.mode === "off" ||
37 - entry.mode === "lite" ||
38 - entry.mode === "full" ||
39 - entry.mode === "ultra") &&
40 - typeof entry.at === "number"
41 - ) {
42 - return { mode: entry.mode, at: entry.at };
43 - }
44 - return undefined;
47 -function replayMode(
48 - entries: readonly EntryLike[],
49 - defaultMode: LazyMode,
50 -): LazyMode {
51 - let latest: ModeEntry | undefined;
52 - for (const entry of entries) {
53 - if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE) continue;
54 - const parsed = modeEntry(entry.data);
55 - if (parsed && (!latest || parsed.at >= latest.at)) latest = parsed;
56 - }
57 - return latest?.mode ?? defaultMode;
60 -function notify(ctx: ExtensionContext, message: string): void {
61 - if (ctx.hasUI) ctx.ui.notify(message, "info");
64 -function updateStatus(
65 - ctx: ExtensionContext,
66 - state: State,
67 - enabled: boolean,
68 -): void {
69 - if (!ctx.hasUI || !enabled) return;
70 - ctx.ui.setStatus(
71 - STATUS_KEY,
72 - statusSegment(state.mode, state.activeGeneration),
73 - );
76 -function appendMode(
77 - pi: ExtensionAPI,
78 - state: State,
79 - mode: LazyMode,
80 - ctx: ExtensionContext,
81 -): void {
82 - state.mode = mode;
83 - pi.appendEntry(ENTRY_TYPE, { mode, at: Date.now() });
84 - updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd).status);
87 -function sendSkill(
88 - pi: ExtensionAPI,
89 - ctx: ExtensionContext,
90 - skill: string,
91 - args: string,
92 -): void {
93 - const message = `/skill:${skill}${args.trim() ? ` ${args.trim()}` : ""}`;
94 - if (ctx.isIdle()) pi.sendUserMessage(message);
95 - else pi.sendUserMessage(message, { deliverAs: "followUp" });
98 -const COMPLETIONS: AutocompleteItem[] = [
99 - { value: "lite", label: "lite" },
100 - { value: "full", label: "full" },
101 - { value: "ultra", label: "ultra" },
102 - { value: "off", label: "off" },
103 - { value: "status", label: "status" },
104 - { value: "default", label: "default" },
105 -];
107 -export default function lazyExtension(pi: ExtensionAPI): void {
108 - const state: State = { mode: "off", activeGeneration: false };
110 - pi.registerCommand("lazy", {
111 - description: "Control lazy senior dev mode",
112 - getArgumentCompletions: (prefix) => {
113 - const clean = prefix.trim().toLowerCase();
114 - return COMPLETIONS.filter((item) => item.value.startsWith(clean));
115 - },
116 - handler: async (args, ctx) => {
117 - const settings = loadLazySettingsForCwd(ctx.cwd);
118 - const command = parseLazyCommand(args, settings.defaultMode);
119 - if (command.kind === "invalid") {
120 - notify(ctx, command.message);
121 - return;
122 - }
123 - if (command.kind === "help") {
124 - notify(ctx, helpText());
125 - return;
126 - }
127 - if (command.kind === "status") {
128 - notify(ctx, statusText(state.mode, settings.defaultMode));
129 - return;
130 - }
131 - if (command.kind === "default") {
132 - notify(ctx, `Add to Pi settings:\n${settingsSnippet(command.mode)}`);
133 - return;
134 - }
135 - appendMode(pi, state, command.mode, ctx);
136 - notify(ctx, `lazy: ${command.mode}`);
137 - },
138 - });
140 - pi.registerCommand("lazy-review", {
141 - description: "Review current diff for over-engineering",
142 - handler: async (args, ctx) => sendSkill(pi, ctx, "lazy-review", args),
143 - });
144 - pi.registerCommand("lazy-audit", {
145 - description: "Audit repo for over-engineering",
146 - handler: async (args, ctx) => sendSkill(pi, ctx, "lazy-audit", args),
147 - });
148 - pi.registerCommand("lazy-debt", {
149 - description: "List lazy debt markers",
150 - handler: async (_args, ctx) =>
151 - notify(ctx, formatDebt(scanLazyDebt(ctx.cwd))),
152 - });
153 - pi.registerCommand("lazy-gain", {
154 - description: "Show published lazy benchmark medians",
155 - handler: async (_args, ctx) => notify(ctx, gainText()),
156 - });
157 - pi.registerCommand("lazy-help", {
158 - description: "Show lazy help",
159 - handler: async (_args, ctx) => notify(ctx, helpText()),
160 - });
162 - pi.on("session_start", (_event, ctx) => {
163 - const settings = loadLazySettingsForCwd(ctx.cwd);
164 - state.mode = replayMode(
165 - ctx.sessionManager.getBranch() as EntryLike[],
166 - settings.defaultMode,
167 - );
168 - state.activeGeneration = false;
169 - updateStatus(ctx, state, settings.status);
170 - });
172 - pi.on("session_shutdown", (_event, ctx) => {
173 - state.activeGeneration = false;
174 - if (ctx.hasUI) ctx.ui.setStatus(STATUS_KEY, undefined);
175 - });
177 - pi.on("input", (event, ctx) => {
178 - if (!isStandaloneDeactivation(event.text)) return;
179 - appendMode(pi, state, "off", ctx);
180 - return { action: "handled" };
181 - });
183 - pi.on("before_agent_start", (event) => {
184 - if (state.mode === "off") return;
185 - const prompt =
186 - event && typeof event.systemPrompt === "string" ? event.systemPrompt : "";
187 - return {
188 - systemPrompt: injectLazyInstructions(
189 - prompt,
190 - state.mode as ActiveLazyMode,
191 - ),
192 - };
193 - });
195 - pi.on("agent_start", (_event, ctx) => {
196 - state.activeGeneration = true;
197 - updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd).status);
198 - });
200 - pi.on("agent_end", async (_event, ctx) => {
201 - state.activeGeneration = false;
202 - updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd).status);
203 - try {
204 - const root = await pi.exec("git", ["rev-parse", "--show-toplevel"], {
205 - cwd: ctx.cwd,
206 - timeout: 5000,
207 - });
208 - if (root.code !== 0) return;
209 - const diff = await pi.exec("git", ["diff", "--unified=0", "--"], {
210 - cwd: ctx.cwd,
211 - timeout: 5000,
212 - });
213 - if (diff.code !== 0 || diff.stdout.length > 256_000) return;
214 - const markers = markersFromUnifiedDiff(diff.stdout, 20);
215 - if (markers.length && ctx.hasUI) {
216 - const files = new Set(markers.map((marker) => marker.file)).size;
217 - ctx.ui.notify(
218 - `lazy debt added: ${markers.length} marker(s) in ${files} file(s). Run /lazy-debt.`,
219 - "info",
220 - );
221 - }
222 - } catch {
223 - return;
224 - }
225 - });
228 -export const __lazyTest = {
229 - replayMode,
230 -};

extensions/lazy/package.json

Deleted
deleted file mode 100644
1 -{
2 - "name": "@bugabinga/pi-ext-lazy",
3 - "private": true,
4 - "type": "module",
5 - "main": "index.ts",
6 - "license": "MIT",
7 - "description": "Pi-native lazy senior dev mode.",
8 - "keywords": [
9 - "pi",
10 - "pi-extension",
11 - "lazy",
12 - "yagni"
13 - ],
14 - "peerDependencies": {
15 - "@earendil-works/pi-coding-agent": "*",
16 - "@earendil-works/pi-tui": "*"
17 - },
18 - "devDependencies": {
19 - "@marcfargas/pi-test-harness": "^0.6.1",
20 - "vitest": "^4.1.9"
21 - },
22 - "scripts": {
23 - "test": "vitest run ./__tests__/*.test.ts"
24 - },
25 - "pi": {
26 - "extensions": [
27 - "index.ts"
28 - ],
29 - "skills": [
30 - "skills"
31 - ]
32 - }
33 -}

extensions/lazy/skills/lazy-audit/SKILL.md

Deleted
deleted file mode 100644
1 ----
2 -name: lazy-audit
3 -description: Scan the repository for over-engineering and rank largest safe reductions first; no fixes applied.
4 ----
6 -# Lazy Audit
8 -Scan the repository, not just the diff.
10 -Rank largest safe reductions first.
12 -Use tags exactly: `delete`, `stdlib`, `native`, `yagni`, `shrink`.
14 -Hunt one-impl interfaces, factories with one product, wrappers that only delegate, unused config, new deps for native/stdlib features, and hand-rolled stdlib.
16 -End with `net: -<N> lines, -<M> deps possible.` when reductions exist.
18 -End with `Lean already. Ship.` when no reduction is worth making.
20 -Do not apply fixes.

extensions/lazy/skills/lazy-debt/SKILL.md

Deleted
deleted file mode 100644
1 ----
2 -name: lazy-debt
3 -description: Find deliberate lazy shortcut comments and their upgrade triggers.
4 ----
6 -# Lazy Debt
8 -Find comments marked `lazy:`.
10 -Report file, line, ceiling, and upgrade trigger.
12 -Flag markers without a trigger as `no-trigger`.
14 -Do not change files.

extensions/lazy/skills/lazy-gain/SKILL.md

Deleted
deleted file mode 100644
1 ----
2 -name: lazy-gain
3 -description: Explain published Lazy/Ponytail benchmark medians honestly.
4 ----
6 -# Lazy Gain
8 -Print the compact benchmark card.
10 -State that numbers are published benchmark medians, not current-repo savings.
12 -Use current agentic figures:
14 -- feature tasks: LOC -54%, tokens -22%, cost -20%, time -27%, safe 100%
15 -- safety tasks: safe 100%; bare one-liner prompt slipped to 95%
17 -Avoid old 80–94% headlines except as historical context.

extensions/lazy/skills/lazy-help/SKILL.md

Deleted
deleted file mode 100644
1 ----
2 -name: lazy-help
3 -description: Show Lazy command, mode, deactivation, and settings reference.
4 ----
6 -# Lazy Help
8 -Explain commands, modes, deactivation, and settings.
10 -Keep it compact.

extensions/lazy/skills/lazy-review/SKILL.md

Deleted
deleted file mode 100644
1 ----
2 -name: lazy-review
3 -description: Review the current diff for over-engineering only; no fixes applied.
4 ----
6 -# Lazy Review
8 -Review only the current diff.
10 -Report over-engineering only.
12 -One finding per line: location, tag, what to cut, replacement.
14 -Use tags exactly: `delete`, `stdlib`, `native`, `yagni`, `shrink`.
16 -Hunt one-impl interfaces, factories with one product, wrappers that only delegate, unused config, new deps for native/stdlib features, and hand-rolled stdlib.
18 -End with `net: -<N> lines possible.` when reductions exist.
20 -End with `Lean already. Ship.` when no reduction is worth making.
22 -Do not apply fixes.

extensions/lazy/skills/lazy/SKILL.md

Deleted
deleted file mode 100644
1 ----
2 -name: lazy
3 -description: "Always-on lazy senior dev guidance: YAGNI, reuse, stdlib, native platform, installed deps, one-line solution, minimum custom code."
4 ----
6 -# Lazy
8 -Use the smallest safe implementation.
10 -Ladder:
12 -1. Do not build what was not asked.
13 -2. Reuse existing code in this repo.
14 -3. Prefer stdlib.
15 -4. Prefer native platform APIs.
16 -5. Prefer installed deps over new deps.
17 -6. Prefer one-line/data-only changes.
18 -7. Write minimum custom code.
20 -Rules:
22 -- No unrequested abstractions: no one-impl interfaces, factories, wrappers, or config nobody sets.
23 -- Deletion over addition. Boring over clever. Fewest files possible.
24 -- Lazy about the solution, never about reading: inspect the touched flow before choosing a rung.
25 -- Two stdlib/native options, same size? Pick the edge-case-correct one.
26 -- Mark deliberate simplifications with `lazy:` plus ceiling and upgrade trigger.
28 -Safety floor: never remove trust-boundary validation, data-loss handling, security, accessibility, hardware calibration, or explicitly requested behavior.
30 -Test floor: non-trivial logic leaves one small runnable check; trivial one-liners need no test.
32 -Output code first, then a short skipped/when-to-add note only if useful.

extensions/lazy/src/config.ts

Deleted
deleted file mode 100644
1 -import { SettingsManager } from "@earendil-works/pi-coding-agent";
2 -import { type LazyMode, normalizeMode } from "./modes.ts";
4 -export interface LazySettings {
5 - defaultMode: LazyMode;
6 - status: boolean;
7 -}
9 -export const LAZY_DEFAULTS: LazySettings = {
10 - defaultMode: "full",
11 - status: true,
12 -};
14 -function isPlainObject(value: unknown): value is Record<string, unknown> {
15 - return value !== null && typeof value === "object" && !Array.isArray(value);
16 -}
18 -export function pickLazy(raw: unknown): Partial<LazySettings> {
19 - if (!isPlainObject(raw) || !isPlainObject(raw.lazy)) return {};
20 - const out: Partial<LazySettings> = {};
21 - const defaultMode = normalizeMode(raw.lazy.defaultMode);
22 - if (defaultMode) out.defaultMode = defaultMode;
23 - if (typeof raw.lazy.status === "boolean") out.status = raw.lazy.status;
24 - return out;
25 -}
27 -export function mergeLazySettings(
28 - ...partials: Partial<LazySettings>[]
29 -): LazySettings {
30 - return partials.reduce<LazySettings>(
31 - (settings, partial) => ({
32 - defaultMode: partial.defaultMode ?? settings.defaultMode,
33 - status:
34 - typeof partial.status === "boolean" ? partial.status : settings.status,
35 - }),
36 - { ...LAZY_DEFAULTS },
37 - );
38 -}
40 -export function loadLazySettings(runtime?: unknown): LazySettings {
41 - return mergeLazySettings(pickLazy(runtime));
42 -}
44 -export function loadLazySettingsForCwd(cwd: string): LazySettings {
45 - const manager = SettingsManager.create(cwd);
46 - return mergeLazySettings(
47 - pickLazy(manager.getGlobalSettings()),
48 - pickLazy(manager.getProjectSettings()),
49 - );
50 -}
52 -export function settingsSnippet(mode: LazyMode): string {
53 - return JSON.stringify(
54 - { lazy: { defaultMode: mode, status: true } },
55 - null,
56 - "\t",
57 - );
58 -}

extensions/lazy/src/debt.ts

Deleted
deleted file mode 100644
1 -import { readdirSync, readFileSync, statSync } from "node:fs";
2 -import path from "node:path";
4 -const SKIP_DIRS = new Set([
5 - ".git",
6 - "node_modules",
7 - "dist",
8 - "build",
9 - "coverage",
10 - ".cache",
11 - ".turbo",
12 - ".next",
13 - "target",
14 - "vendor",
15 -]);
17 -const MARKER_RE = /(?:\/\/|#|\/\*|<!--)\s*lazy:\s*(.*)$/i;
18 -const TRIGGER_RE = /\b(?:until|when|trigger|upgrade|if)\b\s*[:=-]?\s*(.+)$/i;
20 -export interface LazyDebtMarker {
21 - file: string;
22 - line: number;
23 - ceiling: string;
24 - trigger?: string;
25 - noTrigger: boolean;
28 -export interface ScanOptions {
29 - maxFileBytes?: number;
30 - maxMarkers?: number;
33 -export interface ScanResult {
34 - markers: LazyDebtMarker[];
35 - omitted: number;
38 -function isBinary(buffer: Buffer): boolean {
39 - return buffer.includes(0);
42 -function parseMarkerText(text: string): { ceiling: string; trigger?: string } {
43 - const triggerMatch = text.match(TRIGGER_RE);
44 - if (!triggerMatch?.[1]) return { ceiling: text.trim() || "unspecified" };
45 - const ceiling = text
46 - .slice(0, triggerMatch.index)
47 - .trim()
48 - .replace(/[;,-]+$/u, "");
49 - return {
50 - ceiling: ceiling || "unspecified",
51 - trigger: triggerMatch[1].trim().replace(/\s*(?:\*\/|-->)\s*$/u, ""),
52 - };
55 -export function parseLazyMarker(
56 - lineText: string,
57 - file: string,
58 - line: number,
59 -): LazyDebtMarker | undefined {
60 - const match = lineText.match(MARKER_RE);
61 - if (!match) return undefined;
62 - const parsed = parseMarkerText(match[1] ?? "");
63 - return {
64 - file,
65 - line,
66 - ceiling: parsed.ceiling,
67 - trigger: parsed.trigger,
68 - noTrigger: !parsed.trigger,
69 - };
72 -function scanFile(abs: string, rel: string): LazyDebtMarker[] {
73 - const buffer = readFileSync(abs);
74 - if (isBinary(buffer)) return [];
75 - return buffer
76 - .toString("utf8")
77 - .split(/\r?\n/u)
78 - .flatMap((lineText, index) => {
79 - const marker = parseLazyMarker(lineText, rel, index + 1);
80 - return marker ? [marker] : [];
81 - });
84 -export function scanLazyDebt(
85 - root: string,
86 - options: ScanOptions = {},
87 -): ScanResult {
88 - const maxFileBytes = options.maxFileBytes ?? 256 * 1024;
89 - const maxMarkers = options.maxMarkers ?? 100;
90 - const markers: LazyDebtMarker[] = [];
91 - let omitted = 0;
93 - function visit(dir: string): void {
94 - for (const entry of readdirSync(dir, { withFileTypes: true })) {
95 - if (entry.name.startsWith(".") && entry.name !== ".pi") {
96 - if (SKIP_DIRS.has(entry.name)) continue;
97 - }
98 - const abs = path.join(dir, entry.name);
99 - const rel = path.relative(root, abs).split(path.sep).join("/");
100 - if (entry.isDirectory()) {
101 - if (SKIP_DIRS.has(entry.name)) continue;
102 - visit(abs);
103 - continue;
104 - }
105 - if (!entry.isFile()) continue;
106 - const stat = statSync(abs);
107 - if (stat.size > maxFileBytes) continue;
108 - for (const marker of scanFile(abs, rel)) {
109 - if (markers.length < maxMarkers) markers.push(marker);
110 - else omitted += 1;
111 - }
112 - }
113 - }
115 - visit(root);
116 - return { markers, omitted };
119 -export function formatDebt(result: ScanResult): string {
120 - if (result.markers.length === 0) return "No lazy debt.";
121 - const lines = result.markers.map((marker) => {
122 - const trigger = marker.noTrigger
123 - ? "no-trigger"
124 - : `trigger: ${marker.trigger}`;
125 - return `${marker.file}:${marker.line} ceiling: ${marker.ceiling} ${trigger}`;
126 - });
127 - if (result.omitted > 0) lines.push(`… ${result.omitted} omitted`);
128 - return lines.join("\n");
131 -export function markersFromUnifiedDiff(
132 - diff: string,
133 - max = 20,
134 -): LazyDebtMarker[] {
135 - const markers: LazyDebtMarker[] = [];
136 - let file = "";
137 - let newLine = 0;
138 - for (const line of diff.split(/\r?\n/u)) {
139 - if (line.startsWith("+++ b/")) {
140 - file = line.slice(6);
141 - continue;
142 - }
143 - const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/u);
144 - if (hunk) {
145 - newLine = Number(hunk[1]);
146 - continue;
147 - }
148 - if (line.startsWith("+") && !line.startsWith("+++")) {
149 - const marker = parseLazyMarker(line.slice(1), file, newLine);
150 - if (marker) markers.push(marker);
151 - newLine += 1;
152 - } else if (line.startsWith("-") && !line.startsWith("---")) {
153 - continue;
154 - } else if (line) {
155 - newLine += 1;
156 - }
157 - if (markers.length >= max) break;
158 - }
159 - return markers;

extensions/lazy/src/instructions.ts

Deleted
deleted file mode 100644
1 -import type { ActiveLazyMode } from "./modes.ts";
3 -export const LAZY_HEADER_RE =
4 - /\n?LAZY MODE ACTIVE — level: (lite|full|ultra)\n[\s\S]*?\nEND LAZY MODE\n?/g;
6 -const LADDER = [
7 - "Do not build what was not asked.",
8 - "Reuse existing code in this repo.",
9 - "Prefer stdlib.",
10 - "Prefer native platform APIs.",
11 - "Prefer installed deps over new deps.",
12 - "Prefer one-line/data-only changes.",
13 - "Write minimum custom code.",
14 -];
16 -const RULES = [
17 - "No unrequested abstractions: no one-impl interfaces, factories, wrappers, or config nobody sets.",
18 - "Deletion over addition. Boring over clever. Fewest files possible.",
19 - "Lazy about the solution, never about reading: inspect the touched flow before choosing a rung.",
20 - "Two stdlib/native options, same size? Pick the edge-case-correct one.",
21 - "Mark deliberate simplifications with `lazy:` plus ceiling and upgrade trigger.",
22 -];
24 -const MODE_LINES: Record<ActiveLazyMode, string[]> = {
25 - lite: [
26 - "Build the requested thing, then mention the lazier alternative briefly.",
27 - "Do not block straightforward implementation with repeated challenges.",
28 - ],
29 - full: [
30 - "Enforce the ladder before custom code.",
31 - "Challenge unnecessary scope once, then ship the smallest safe version.",
32 - ],
33 - ultra: [
34 - "Deletion first: remove, merge, inline, or configure before adding code.",
35 - "Challenge nonessential requirements aggressively while preserving explicitly requested behavior.",
36 - ],
37 -};
39 -export function buildLazyInstructions(mode: ActiveLazyMode): string {
40 - return [
41 - `LAZY MODE ACTIVE — level: ${mode}`,
42 - "",
43 - "Ladder:",
44 - ...LADDER.map((line, index) => `${index + 1}. ${line}`),
45 - "",
46 - "Root-cause bug-fix rule: inspect callers and fix the shared route when possible.",
47 - "Rules:",
48 - ...RULES.map((line) => `- ${line}`),
49 - "Safety floor: never remove trust-boundary validation, data-loss handling, security, accessibility, hardware calibration, or explicitly requested behavior.",
50 - "Test floor: non-trivial logic leaves one small runnable check; trivial one-liners need no test.",
51 - "Output discipline: code first; short skipped/when-to-add note; no unrequested essays.",
52 - "",
53 - "Mode-specific:",
54 - ...MODE_LINES[mode].map((line) => `- ${line}`),
55 - "END LAZY MODE",
56 - ].join("\n");
57 -}
59 -export function stripLazyInstructions(prompt: string): string {
60 - return prompt
61 - .replace(LAZY_HEADER_RE, "\n")
62 - .replace(/\n{3,}/g, "\n\n")
63 - .trimEnd();
64 -}
66 -export function injectLazyInstructions(
67 - prompt: string,
68 - mode: ActiveLazyMode,
69 -): string {
70 - const base = stripLazyInstructions(prompt);
71 - return `${base}\n\n${buildLazyInstructions(mode)}`;
72 -}

extensions/lazy/src/modes.ts

Deleted
deleted file mode 100644
1 -export const LAZY_MODES = ["off", "lite", "full", "ultra"] as const;
2 -export type LazyMode = (typeof LAZY_MODES)[number];
3 -export type ActiveLazyMode = Exclude<LazyMode, "off">;
5 -export type LazyCommand =
6 - | { kind: "set"; mode: LazyMode }
7 - | { kind: "status" }
8 - | { kind: "default"; mode: LazyMode }
9 - | { kind: "help" }
10 - | { kind: "invalid"; message: string };
12 -export function isLazyMode(value: unknown): value is LazyMode {
13 - return typeof value === "string" && LAZY_MODES.includes(value as LazyMode);
14 -}
16 -export function normalizeMode(value: unknown): LazyMode | undefined {
17 - if (typeof value !== "string") return undefined;
18 - const mode = value.trim().toLowerCase();
19 - return isLazyMode(mode) ? mode : undefined;
20 -}
22 -export function modeFromBareDefault(defaultMode: LazyMode): LazyMode {
23 - return defaultMode === "off" ? "full" : defaultMode;
24 -}
26 -export function parseLazyCommand(
27 - args: string,
28 - defaultMode: LazyMode,
29 -): LazyCommand {
30 - const parts = args.trim().split(/\s+/).filter(Boolean);
31 - if (parts[0]?.toLowerCase().replace(/^\//u, "") === "lazy") parts.shift();
32 - const first = parts[0]?.toLowerCase();
33 - if (!first) return { kind: "set", mode: modeFromBareDefault(defaultMode) };
34 - if (first === "status") return { kind: "status" };
35 - if (first === "help" || first === "--help" || first === "-h") {
36 - return { kind: "help" };
37 - }
38 - if (first === "default") {
39 - const mode = normalizeMode(parts[1]);
40 - if (!mode || parts.length !== 2) {
41 - return {
42 - kind: "invalid",
43 - message: "usage: /lazy default off|lite|full|ultra",
44 - };
45 - }
46 - return { kind: "default", mode };
47 - }
48 - const mode = normalizeMode(first);
49 - if (mode && parts.length === 1) return { kind: "set", mode };
50 - return {
51 - kind: "invalid",
52 - message: "usage: /lazy [off|lite|full|ultra|status|default <mode>]",
53 - };
54 -}
56 -export function isStandaloneDeactivation(input: string): boolean {
57 - const normalized = input
58 - .trim()
59 - .toLowerCase()
60 - .replace(/[.!?。!?]+$/u, "")
61 - .trim();
62 - return normalized === "stop lazy" || normalized === "normal mode";
63 -}

extensions/lazy/src/ui.ts

Deleted
deleted file mode 100644
1 -import type { LazyMode } from "./modes.ts";
3 -export function helpText(): string {
4 - return [
5 - "lazy commands:",
6 - "/lazy [lite|full|ultra|off]",
7 - "/lazy status",
8 - "/lazy default <mode>",
9 - "/lazy-review [args]",
10 - "/lazy-audit [args]",
11 - "/lazy-debt",
12 - "/lazy-gain",
13 - "deactivate: stop lazy | normal mode",
14 - "settings: lazy.defaultMode, lazy.status",
15 - ].join("\n");
16 -}
18 -export function gainText(): string {
19 - return [
20 - "lazy gain — published benchmark medians, not current-repo savings",
21 - "feature tasks: LOC -54%, tokens -22%, cost -20%, time -27%, safe 100%",
22 - "safety tasks: safe 100%; bare one-liner prompt slipped to 95%",
23 - ].join("\n");
24 -}
26 -export function statusText(
27 - sessionMode: LazyMode,
28 - defaultMode: LazyMode,
29 -): string {
30 - return `lazy session: ${sessionMode}\nlazy default: ${defaultMode}`;
31 -}
33 -export function statusSegment(
34 - mode: LazyMode,
35 - active: boolean,
36 -): string | undefined {
37 - if (mode === "off") return undefined;
38 - return `${active ? "●" : "○"} lazy: ${mode}`;
39 -}

package-lock.json

Modified
76 76 "@earendil-works/pi-coding-agent": "*"
79 + "extensions/continuity": {
80 + "name": "@bugabinga/pi-ext-continuity",
81 + "license": "MIT",
82 + "devDependencies": {
83 + "@marcfargas/pi-test-harness": "^0.6.1",
84 + "vitest": "^4.1.9"
85 + },
86 + "peerDependencies": {
87 + "@earendil-works/pi-coding-agent": "*"
88 + }
89 + },
79 90 "extensions/cost": {
80 91 "name": "@bugabinga/pi-ext-cost",
81 92 "license": "MIT",
193 204 "typebox": "*"
196 - "extensions/lazy": {
197 - "name": "@bugabinga/pi-ext-lazy",
198 - "license": "MIT",
199 - "devDependencies": {
200 - "@marcfargas/pi-test-harness": "^0.6.1",
201 - "vitest": "^4.1.9"
202 - },
203 - "peerDependencies": {
204 - "@earendil-works/pi-coding-agent": "*",
205 - "@earendil-works/pi-tui": "*"
207 - },
208 207 "extensions/leaks": {
209 208 "name": "@bugabinga/pi-ext-leaks",
210 209 "license": "MIT",
1283 1282 "resolved": "extensions/context-size",
1284 1283 "link": true
1285 + "node_modules/@bugabinga/pi-ext-continuity": {
1286 + "resolved": "extensions/continuity",
1287 + "link": true
1288 + },
1286 1289 "node_modules/@bugabinga/pi-ext-cost": {
1287 1290 "resolved": "extensions/cost",
1288 1291 "link": true
1319 1322 "resolved": "extensions/goldfish",
1320 1323 "link": true
1322 - "node_modules/@bugabinga/pi-ext-lazy": {
1323 - "resolved": "extensions/lazy",
1324 - "link": true
1325 - },
1326 1325 "node_modules/@bugabinga/pi-ext-leaks": {
1327 1326 "resolved": "extensions/leaks",
1328 1327 "link": true

package.json

Modified
31 31 "pi": {
32 32 "extensions": [
33 33 "extensions/*/index.ts"
34 - ],
35 - "skills": [
36 - "extensions/lazy/skills"
39 36 "allowScripts": {

scripts/extensions.mjs

Modified
890 890 JSON.stringify(["extensions/*/index.ts"])
892 892 errors.push("root: pi.extensions must be ['extensions/*/index.ts']");
893 - if (
894 - JSON.stringify(pkg.pi?.skills) !==
895 - JSON.stringify(["extensions/lazy/skills"])
897 - errors.push("root: pi.skills must be ['extensions/lazy/skills']");
893 + if ("skills" in (pkg.pi ?? {})) errors.push("root: pi.skills must be absent");
898 894 if ("prompts" in (pkg.pi ?? {}))
899 895 errors.push("root: pi.prompts must be absent");
900 896 if ("themes" in (pkg.pi ?? {})) errors.push("root: pi.themes must be absent");

scripts/test_extensions_static_check.mjs

Modified
175 175 assert.deepEqual(rootPkg().pi, {
176 176 extensions: ["extensions/*/index.ts"],
177 - skills: ["extensions/lazy/skills"],
180 179 assert.deepEqual(