repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat: add lazy pi extension

982fc5474130fb674fb550bf7664729e6329a403

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (22)

docs/superpowers/plans/2026-07-03-lazy-pi-extension.md

Added
new file mode 100644
1 +# Lazy Pi Extension Implementation Plan
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use /skill:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
5 +**Goal:** Build `extensions/lazy` from `docs/superpowers/specs/2026-07-03-ponytail-pi-extension-design.md` and verify user-facing behavior through tests plus real tmux+pi.
7 +**Architecture:** Keep deterministic logic in small TypeScript modules under `extensions/lazy/src`. `index.ts` only wires Pi commands/events/UI to pure helpers. Review/audit commands hand off to skills; mode, instructions, debt, help, and gain stay direct.
9 +**Tech Stack:** Pi extension API, TypeScript, Vitest, Node fs/path/child_process APIs, existing `mise` tasks.
11 +**Roadmap:** None
13 +**Phase:** Single-plan implementation
15 +---
17 +## File map
19 +- Create `extensions/lazy/package.json`: workspace package metadata.
20 +- Create `extensions/lazy/index.ts`: Pi API wiring, state replay, commands, events, UI notifications.
21 +- Create `extensions/lazy/src/modes.ts`: mode parsing, deactivation parsing, command parsing.
22 +- Create `extensions/lazy/src/config.ts`: `lazy` settings resolution from Pi settings files/runtime.
23 +- Create `extensions/lazy/src/instructions.ts`: canonical lazy prompt block builder and idempotent injector.
24 +- Create `extensions/lazy/src/debt.ts`: Node-only lazy marker scanners for repo and git diff.
25 +- Create `extensions/lazy/src/ui.ts`: status/help/gain output helpers.
26 +- Create `extensions/lazy/skills/*/SKILL.md`: six discoverable Pi skills.
27 +- Create `extensions/lazy/__tests__/*.test.ts`: unit and harness coverage.
28 +- Update root `package.json`: export `extensions/lazy/skills` through `pi.skills`.
29 +- Update `extensions/lazy/package.json`: export `index.ts` and `skills` through the extension package `pi` manifest.
30 +- Create `extensions/lazy/README.md`: user-facing install/settings/commands docs.
32 +## Tasks
34 +### Task 1: Skeleton and skills
36 +- [x] Create extension package dirs.
37 +- [x] Add `package.json` and `README.md` stub.
38 +- [x] Add six skill files with exact lazy command behavior.
39 +- [x] Export `extensions/lazy/skills` from root `package.json`.
40 +- [x] Export `index.ts` and `skills` from `extensions/lazy/package.json`.
41 +- [x] Run skill checker.
43 +### Task 2: Pure mode/config/instruction helpers
45 +- [x] Implement `modes.ts` with valid modes, command parser, default fallback, and strict deactivation matcher.
46 +- [x] Implement `config.ts` with file/runtime settings precedence and defaults.
47 +- [x] Implement `instructions.ts` with one canonical block and idempotent injection.
48 +- [x] Add unit tests for modes/config/instructions.
49 +- [x] Run targeted Vitest.
51 +### Task 3: Debt scanners
53 +- [x] Implement repo scanner with skip dirs, text/binary/size caps, marker parsing, trigger detection, bounded output.
54 +- [x] Implement diff scanner using bounded `git diff --unified=0` via `pi.exec` only from `agent_end`.
55 +- [x] Add unit tests for marker parsing, skips, no-trigger, and output caps.
56 +- [x] Run targeted Vitest.
58 +### Task 4: Pi wiring and harness tests
60 +- [x] Implement `index.ts` session state replay through `lazy-mode` custom entries.
61 +- [x] Register `/lazy`, `/lazy-review`, `/lazy-audit`, `/lazy-debt`, `/lazy-gain`, `/lazy-help`.
62 +- [x] Add `/lazy` argument completions.
63 +- [x] Add `before_agent_start`, `agent_start`, `agent_end`, `session_start`, and `session_shutdown` behavior.
64 +- [x] Add harness tests for load, commands, mode append, status, injection, skill handoff, debt output, no-UI safety, and diff notification.
65 +- [x] Run targeted Vitest.
67 +### Task 5: Real tmux+pi verification
69 +- [x] Use real `pi` inside tmux with the lazy extension loaded.
70 +- [x] Verify `/lazy-help`, `/lazy-gain`, `/lazy-debt`, `/lazy ultra`, `/lazy status`, `/lazy off` user-facing behavior.
71 +- [x] Verify `/lazy-review` and `/lazy-audit` hand off to the matching skills.
72 +- [x] Verify status segment appears/clears in TUI.
73 +- [x] Save the exact tmux/pi commands and observed outputs in final notes.
75 +### Task 6: Release gate
77 +- [x] Run `mise run fmt`.
78 +- [x] Run `mise run lint`.
79 +- [x] Run `mise run test -- lazy`.
80 +- [x] Run `mise run ci`.
81 +- [x] Fix failures without touching unrelated dirty work.

docs/superpowers/specs/2026-07-03-ponytail-pi-extension-design.md

Added
new file mode 100644
1 +# Lazy Pi extension
3 +**Date:** 2026-07-03
4 +**Status:** Draft for review
5 +**Objective:** Create an idiomatic Pi extension named `lazy` with the same or better functionality as `DietrichGebert/ponytail`.
7 +## Source evidence
9 +Researched repository: `https://github.com/DietrichGebert/ponytail`.
10 +Local snapshot: `tmp/research/ponytail`.
11 +Commit: `40e50d9e03242aa5dd53ac771950f9127362b25f` on `main`.
12 +Package version observed: `4.8.4`.
14 +Primary source files inspected:
16 +- `README.md` for install UX, modes, commands, benchmark claims, and safety boundary.
17 +- `package.json` for Pi package manifest: `pi.extensions = ["./pi-extension/index.js"]`, `pi.skills = ["./skills"]`.
18 +- `pi-extension/index.js` for Pi adapter behavior.
19 +- `pi-extension/test/*.test.js` for Pi command, state, config, and prompt injection expectations.
20 +- `hooks/ponytail-config.js`, `hooks/ponytail-instructions.js`, `hooks/ponytail-runtime.js`, `hooks/ponytail-activate.js`, `hooks/ponytail-mode-tracker.js`, `hooks/ponytail-subagent.js` for shared mode/config/instruction behavior.
21 +- `skills/ponytail*/SKILL.md` for the six portable skills.
22 +- `docs/platform-native.md` for stdlib/native replacement reference content.
23 +- `docs/agent-portability.md` for host adapter model.
24 +- `benchmarks/results/2026-06-18-agentic.md` for the current benchmark claim and limitations.
25 +- `.claude-plugin/plugin.json`, `.codex-plugin/plugin.json`, `.opencode/plugins/ponytail.mjs`, `plugin.yaml`, `__init__.py`, `gemini-extension.json` for non-Pi adapter parity.
27 +Pi docs inspected:
29 +- `/opt/pi-coding-agent/docs/extensions.md`
30 +- `/opt/pi-coding-agent/docs/packages.md`
31 +- `/opt/pi-coding-agent/docs/skills.md`
32 +- local extension patterns in `extensions/terse`, `extensions/notes`, and repo test harness patterns.
34 +## Problem
36 +Ponytail already ships a Pi adapter, but it is a thin compatibility layer inside a multi-host package.
37 +It reuses CommonJS hook files, has minimal Pi-native UI, and delegates most commands to skill prompts.
38 +`lazy` is a new Pi-only extension for this repo, so it should keep the useful behavior and drop all host portability, migration, legacy config, and compatibility shims.
40 +## Goals
42 +- Provide always-on lazy-senior-dev guidance for Pi coding sessions.
43 +- Preserve Ponytail's core ladder: YAGNI, reuse codebase, stdlib, native platform, installed dependency, one-line solution, then minimum custom code.
44 +- Preserve intensity levels: `lite`, `full`, `ultra`, and `off`.
45 +- Preserve behavior while renaming the command surface to `/lazy`, `/lazy-review`, `/lazy-audit`, `/lazy-debt`, `/lazy-gain`, `/lazy-help`.
46 +- Preserve session-local mode persistence across branch reloads using Pi session entries.
47 +- Use only Pi settings for default mode.
48 +- Preserve skill discoverability through normal Pi skills.
49 +- Add Pi-native UX that current Ponytail lacks: proper settings integration, compact status rendering, command completions, and optional direct command implementations where they beat prompt aliases.
50 +- Keep extension behavior cross-platform and shell-free by default.
51 +- Keep output injection compact and deterministic.
53 +## Non-goals
55 +- Reimplement all non-Pi host adapters.
56 +- Support Ponytail install/config migration.
57 +- Keep Ponytail command or skill names for compatibility.
58 +- Copy Ponytail's benchmarks or benchmark runner into this repo.
59 +- Add a new model provider, MCP server, or external service.
60 +- Automatically mutate user code when running review/audit/debt commands.
61 +- Replace Pi's built-in skills system.
62 +- Add dependencies for parsing markdown or config unless a stdlib/Node API cannot cover it.
64 +## Product behavior
66 +### Modes
68 +`/lazy [mode]` controls a session mode.
69 +Modes:
71 +- `lite`: build what was asked, but mention the lazier alternative briefly.
72 +- `full`: default ladder enforcement.
73 +- `ultra`: deletion-first, YAGNI-extreme, challenge nonessential requirements while still shipping the smallest safe version.
74 +- `off`: no prompt injection and no active status badge.
76 +Bare `/lazy` enables the configured default mode.
77 +If configured default is `off`, bare `/lazy` enables `full`.
78 +`/lazy status` reports session mode and default mode.
79 +`/lazy default <mode>` writes the default mode to extension settings if Pi exposes a safe setting writer; otherwise it explains the exact settings JSON entry.
81 +### Deactivation
83 +A user message equal to `stop lazy` or `normal mode`, ignoring case and trailing punctuation, turns the mode off.
84 +Incidental mentions such as `add a normal mode toggle` must not turn it off.
86 +### Prompt injection
88 +On `before_agent_start`, the extension injects one lazy-mode instruction block only when mode is not `off`.
89 +The block must be built from a single canonical source inside this package, not copy-pasted across command handlers.
91 +The block contains:
93 +- `LAZY MODE ACTIVE — level: <mode>` header.
94 +- The ladder.
95 +- Root-cause bug-fix rule: inspect callers and fix the shared route when possible.
96 +- Safety floor: never remove trust-boundary validation, data-loss handling, security, accessibility, hardware calibration, or explicitly requested behavior.
97 +- Test floor: non-trivial logic leaves one small runnable check; trivial one-liners need no test.
98 +- Output discipline: code first; short skipped/when-to-add note; no unrequested essays.
99 +- Mode-specific section only for the active mode.
101 +The injection must be idempotent per turn: repeated `before_agent_start` hooks cannot duplicate the block.
103 +### Status
105 +In TUI/RPC UI-capable sessions, show a compact status segment:
107 +- inactive turn: `○ lazy: <mode>`
108 +- active generation: `● lazy: <mode>`
109 +- off: clear the segment
111 +Use `ctx.ui.setStatus("lazy", ...)`.
112 +Do not require theme APIs to exist; degrade silently in non-UI modes.
114 +### Commands
116 +`/lazy-review` reviews the current diff for over-engineering only.
117 +It returns one finding per line with tags: `delete`, `stdlib`, `native`, `yagni`, `shrink`.
118 +It ends with `net: -<N> lines possible.` or `Lean already. Ship.`
119 +It does not apply fixes.
121 +`/lazy-audit` scans the repository, not just the diff, for over-engineering.
122 +It ranks largest reductions first and ends with `net: -<N> lines, -<M> deps possible.` or `Lean already. Ship.`
123 +It does not apply fixes.
125 +`/lazy-debt` finds deliberate shortcut comments matching comment markers such as `// lazy:` and `# lazy:`.
126 +It reports file, line, ceiling, and upgrade trigger.
127 +It flags markers without a trigger as `no-trigger`.
128 +It changes nothing unless a future explicit `--write` option is added.
130 +When an agent turn adds a new `lazy:` marker, the extension sends a UI notification with the file count and suggests `/lazy-debt`.
131 +Detection happens after the agent turn by scanning the current git diff for newly added `lazy:` lines.
132 +No background watcher is needed.
134 +`/lazy-gain` prints a compact benchmark card.
135 +It must be honest that numbers are published benchmark medians, not current-repo savings.
136 +Prefer the current agentic figures from `2026-06-18-agentic.md`: feature tasks `LOC -54%`, `tokens -22%`, `cost -20%`, `time -27%`, `safe 100%`; safety tasks note `safe 100%` and that bare one-liner prompt slipped to `95%`.
137 +Avoid the older single-shot `80–94%` headline except as historical context.
139 +`/lazy-help` prints command, mode, deactivation, and config reference.
141 +### Skills
143 +Ship Pi skills in `extensions/lazy/skills/*/SKILL.md` exported by root `package.json`.
144 +Skill names:
146 +- `lazy`
147 +- `lazy-review`
148 +- `lazy-audit`
149 +- `lazy-debt`
150 +- `lazy-gain`
151 +- `lazy-help`
153 +The extension commands may either:
155 +1. directly implement deterministic behavior, or
156 +2. send `/skill:<name>` as a follow-up.
158 +Recommended split:
160 +- Direct extension implementation: `/lazy`, `/lazy-debt`, `/lazy-gain`, `/lazy-help`.
161 +- Skill handoff: `/lazy-review`, `/lazy-audit` because the agent must reason over code and diffs.
163 +This is better than upstream Pi adapter because deterministic commands avoid spending model turns for static cards and grep-like ledgers.
165 +## Architecture
167 +Create a new extension package: `extensions/lazy`.
169 +Suggested files:
171 +```text
172 +extensions/lazy/
173 +├── index.ts
174 +├── package.json
175 +├── README.md
176 +├── src/
177 +│ ├── config.ts
178 +│ ├── instructions.ts
179 +│ ├── modes.ts
180 +│ ├── commands.ts
181 +│ ├── debt.ts
182 +│ └── ui.ts
183 +├── skills/
184 +│ ├── lazy/SKILL.md
185 +│ ├── lazy-review/SKILL.md
186 +│ ├── lazy-audit/SKILL.md
187 +│ ├── lazy-debt/SKILL.md
188 +│ ├── lazy-gain/SKILL.md
189 +│ └── lazy-help/SKILL.md
190 +└── __tests__/
191 + ├── config.test.ts
192 + ├── instructions.test.ts
193 + ├── debt.test.ts
194 + └── harness.test.ts
195 +```
197 +### State model
199 +Use Pi custom session entries for branch-aware mode state.
200 +Entry type: `lazy-mode`.
201 +Entry data: `{ mode: "lite" | "full" | "ultra" | "off", at: number }`.
202 +On `session_start`, replay the current branch and use the latest valid mode.
203 +If no session entry exists, use configured default.
205 +This is idiomatic Pi and better than host-level flag files because it respects session branches.
207 +### Settings
209 +Prefer Pi settings over a separate config file.
210 +Settings namespace:
212 +```json
214 + "lazy": {
215 + "defaultMode": "full",
216 + "status": true
219 +```
221 +No legacy config compatibility.
222 +No `PONYTAIL_DEFAULT_MODE`.
223 +No `~/.config/ponytail/config.json`.
224 +Only `lazy.defaultMode` in Pi settings.
226 +Valid default modes: `off`, `lite`, `full`, `ultra`.
227 +Reject `review` as a persistent Pi mode unless a future design adds explicit review-mode semantics.
228 +No `review` mode.
229 +Pi has `/lazy-review` for that.
231 +### Instruction builder
233 +Keep a typed instruction builder in `src/instructions.ts`.
234 +Inputs: active mode, optional skill body text.
235 +Outputs: complete prompt block.
237 +Filtering requirement:
239 +- Remove skill frontmatter.
240 +- Keep only the active mode row in the intensity table.
241 +- Keep only the active mode example bullets.
242 +- Do not accidentally remove normal rule bullets containing colons.
244 +This keeps the useful filtering behavior without upstream compatibility code.
246 +### Direct debt scanner
248 +Implement with Node APIs, not shell `grep`.
249 +Scan text files under `ctx.cwd`.
250 +Skip `.git`, `node_modules`, build outputs, lock/cache dirs, and large/binary files.
251 +Match common comment forms:
253 +- `// lazy:`
254 +- `# lazy:`
255 +- `/* lazy:`
256 +- `<!-- lazy:`
258 +Return bounded output and count totals.
259 +If a full list is too large, truncate and tell the user how many were omitted.
261 +### Review and audit handoff
263 +For `/lazy-review` and `/lazy-audit`, use `pi.sendUserMessage` with `/skill:lazy-review` or `/skill:lazy-audit`.
264 +If the agent is streaming, queue as `followUp`.
265 +If idle, send immediately.
266 +Forward command args as user arguments so `/lazy-review path/to/file` works.
267 +Add argument completions for `/lazy` modes: `lite`, `full`, `ultra`, `off`, `status`, and `default`.
269 +### Subagents
271 +No subagent handoff in v1.
272 +Lazy injects only into normal Pi agent turns that load the extension.
273 +It does not try to force lazy mode into SDK-created subagents.
274 +It does not export APIs for other extensions, and other extensions must not import lazy files or call lazy functions.
275 +If Pi later adds a first-class subagent prompt hook, add subagent support then.
277 +## Package integration
279 +Root `package.json` must export the extension and skills.
280 +Add `extensions/lazy/skills` to root `pi.skills`.
281 +Current root manifest exports `extensions/*/index.ts` and selected skill dirs only, so add `extensions/lazy/skills` explicitly.
283 +Extension package `package.json` should include only peer dependencies for Pi packages if imported directly.
284 +No runtime dependency is expected.
286 +## Performance
288 +Lazy must add near-zero overhead to normal turns.
290 +- Do no repository-wide scan on startup or every prompt.
291 +- Prompt injection is string assembly only.
292 +- Status updates are constant-time.
293 +- `agent_end` marker detection reads only `git diff --numstat` and `git diff --unified=0`, and only when inside a Git worktree.
294 +- Diff scanning caps output read size and stops after the first notification-worthy marker batch.
295 +- `/lazy-debt` is the only repo-wide marker scan, runs only on explicit command, skips ignored/heavy dirs, and has file-size/output limits.
296 +- No file watchers, polling loops, timers, background daemons, or startup indexing.
297 +- No spawned shell for routine behavior except bounded `git diff` for post-turn marker detection.
298 +- If Git is unavailable or the worktree is huge, skip notification and stay silent.
300 +Performance tests:
302 +- `before_agent_start` instruction injection is pure and deterministic.
303 +- `agent_end` with no Git repo does no scan and returns fast.
304 +- `agent_end` scans only diff output, not the filesystem.
305 +- `/lazy-debt` respects skip dirs, file-size caps, and output caps.
307 +## Testing
309 +Use `mise run test -- lazy` or exact vitest filters once implemented.
310 +Do not bypass `mise` for repo tasks.
312 +Required unit tests:
314 +- mode normalization accepts only `off`, `lite`, `full`, `ultra`.
315 +- bare `/lazy` falls back from default `off` to `full`.
316 +- `status` and `default <mode>` parse correctly.
317 +- Pi setting default is used when no session entry exists.
318 +- session replay picks latest branch entry.
319 +- deactivation matches only standalone `stop lazy` and `normal mode`.
320 +- instruction injection includes active header and excludes inactive mode examples.
321 +- instruction filtering keeps non-mode bullets containing colons.
322 +- instruction injection is idempotent.
323 +- debt scanner finds `lazy:` markers and skips ignored dirs.
324 +- debt scanner flags missing upgrade trigger.
326 +Required harness tests:
328 +- extension loads in real Pi extension runtime.
329 +- agent-end diff scan notifies when a new `lazy:` marker appears.
330 +- commands registered: `lazy`, `lazy-review`, `lazy-audit`, `lazy-debt`, `lazy-gain`, `lazy-help`.
331 +- `/lazy ultra` appends a `lazy-mode` entry and updates status.
332 +- `before_agent_start` injects instructions when active and returns undefined when off.
333 +- skill alias commands send `/skill:<name>` immediately when idle and `followUp` when streaming.
334 +- `/lazy-debt` produces deterministic output without mutating files.
335 +- status gracefully does nothing when UI or theme is unavailable.
337 +Static checks:
339 +- skill files pass `scripts/check_skills.mjs`.
340 +- README lists commands, settings, and install path.
341 +- no shell-specific code is used for scanner/config logic.
343 +Release gate: `mise run ci`.
345 +## Same-or-better checklist
347 +Same as upstream:
349 +- Always-on prompt injection.
350 +- Lite/full/ultra/off modes.
351 +- Session mode persistence.
352 +- Default mode config.
353 +- Equivalent `/lazy*` command set.
354 +- Six skills.
355 +- Status indication.
356 +- Honest gain card.
357 +- Safety boundaries and test-floor rules.
359 +Better than upstream Pi adapter:
361 +- TypeScript, typed internals, and Vitest harness tests aligned with this repo.
362 +- Pi settings namespace instead of defaulting to host-specific config files.
363 +- Branch-aware Pi session entries instead of process/global flag files.
364 +- Direct deterministic `/lazy-debt`, `/lazy-gain`, and `/lazy-help` commands.
365 +- Command argument completions for modes and note-like target args.
366 +- No CommonJS bridge to hook files.
367 +- No shell grep in user-facing logic.
368 +- No fragile subagent event timing; v1 intentionally has no subagent handoff.
370 +## Risks and decisions
372 +- **Prompt weight:** always-on instructions add tokens every turn.
373 + Keep the injected block shorter than the full skill body while preserving safety rules.
374 +- **Review/audit are model tasks:** direct deterministic implementation would be brittle.
375 + Keep them as skill handoffs.
376 +- **Benchmarks:** do not claim current-repo savings.
377 + The gain card must state benchmark provenance.
379 +## Open questions for user review
381 +1. Should `/lazy default <mode>` write Pi settings if an API exists, or only print the JSON to add?
382 +2. Should `/lazy-debt --write` be in v1, or deferred until someone asks?
384 +## Implementation plan preview
386 +1. Add extension skeleton and exported skills.
387 +2. Implement mode/config/instruction modules with unit tests.
388 +3. Implement command registration, session replay, status, and prompt injection with harness tests.
389 +4. Implement direct debt/help/gain commands.
390 +5. Add README and root package skill export.
391 +6. Run `mise run fmt`, `mise run lint`, targeted tests, then `mise run ci`.

extensions/lazy/README.md

Added
new 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
21 + "lazy": {
22 + "defaultMode": "full",
23 + "status": true
24 + }
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

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

extensions/lazy/__tests__/unit.test.ts

Added
new 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 {
7 + loadLazySettings,
8 + mergeLazySettings,
9 + pickLazy,
10 + settingsSnippet,
11 +} from "../src/config.ts";
12 +import {
13 + formatDebt,
14 + markersFromUnifiedDiff,
15 + parseLazyMarker,
16 + scanLazyDebt,
17 +} from "../src/debt.ts";
18 +import {
19 + buildLazyInstructions,
20 + injectLazyInstructions,
21 +} from "../src/instructions.ts";
22 +import {
23 + isStandaloneDeactivation,
24 + modeFromBareDefault,
25 + normalizeMode,
26 + parseLazyCommand,
27 +} from "../src/modes.ts";
29 +let dirs: string[] = [];
31 +afterEach(async () => {
32 + for (const dir of dirs) await rm(dir, { recursive: true, force: true });
33 + dirs = [];
34 +});
36 +async function tempDir(): Promise<string> {
37 + const dir = await mkdtemp(path.join(tmpdir(), "lazy-test-"));
38 + dirs.push(dir);
39 + return dir;
42 +describe("modes", () => {
43 + it("normalizes only lazy modes", () => {
44 + expect(normalizeMode("OFF")).toBe("off");
45 + expect(normalizeMode("lite")).toBe("lite");
46 + expect(normalizeMode("review")).toBeUndefined();
47 + });
49 + it("falls back from default off to full for bare command", () => {
50 + expect(modeFromBareDefault("off")).toBe("full");
51 + expect(parseLazyCommand("", "off")).toEqual({ kind: "set", mode: "full" });
52 + });
54 + it("parses status and default", () => {
55 + expect(parseLazyCommand("status", "full")).toEqual({ kind: "status" });
56 + expect(parseLazyCommand("/lazy status", "full")).toEqual({
57 + kind: "status",
58 + });
59 + expect(parseLazyCommand("default ultra", "full")).toEqual({
60 + kind: "default",
61 + mode: "ultra",
62 + });
63 + });
65 + it("matches only standalone deactivation", () => {
66 + expect(isStandaloneDeactivation("stop lazy!")).toBe(true);
67 + expect(isStandaloneDeactivation("normal mode.")).toBe(true);
68 + expect(isStandaloneDeactivation("add a normal mode toggle")).toBe(false);
69 + });
70 +});
72 +describe("config", () => {
73 + it("picks and merges valid lazy settings only", () => {
74 + expect(
75 + pickLazy({ lazy: { defaultMode: "ultra", status: false, nope: true } }),
76 + ).toEqual({ defaultMode: "ultra", status: false });
77 + expect(pickLazy({ lazy: { defaultMode: "review" } })).toEqual({});
78 + expect(
79 + mergeLazySettings({ defaultMode: "lite" }, { status: false }),
80 + ).toEqual({
81 + defaultMode: "lite",
82 + status: false,
83 + });
84 + });
86 + it("loads files before runtime", async () => {
87 + const dir = await tempDir();
88 + const file = path.join(dir, "settings.json");
89 + writeFileSync(file, JSON.stringify({ lazy: { defaultMode: "lite" } }));
90 + expect(
91 + loadLazySettings({
92 + files: [file],
93 + runtime: { lazy: { defaultMode: "ultra" } },
94 + }).defaultMode,
95 + ).toBe("ultra");
96 + });
98 + it("prints settings snippet", () => {
99 + expect(settingsSnippet("off")).toContain('"defaultMode": "off"');
100 + });
101 +});
103 +describe("instructions", () => {
104 + it("builds active header and excludes inactive mode lines", () => {
105 + const block = buildLazyInstructions("lite");
106 + expect(block).toContain("LAZY MODE ACTIVE — level: lite");
107 + expect(block).toContain("Root-cause bug-fix rule:");
108 + expect(block).not.toContain("Deletion first");
109 + });
111 + it("injects idempotently", () => {
112 + const once = injectLazyInstructions("BASE", "full");
113 + const twice = injectLazyInstructions(once, "ultra");
114 + expect(twice.match(/LAZY MODE ACTIVE/g)).toHaveLength(1);
115 + expect(twice).toContain("level: ultra");
116 + expect(twice).not.toContain("level: full");
117 + });
118 +});
120 +describe("debt", () => {
121 + it("parses markers and missing triggers", () => {
122 + expect(
123 + parseLazyMarker("// lazy: cap at 10 until > 10 users", "a.ts", 3),
124 + ).toEqual({
125 + file: "a.ts",
126 + line: 3,
127 + ceiling: "cap at 10",
128 + trigger: "> 10 users",
129 + noTrigger: false,
130 + });
131 + expect(parseLazyMarker("# lazy: ship quick", "a.sh", 1)?.noTrigger).toBe(
132 + true,
133 + );
134 + });
136 + it("scans repo and skips heavy dirs", async () => {
137 + const dir = await tempDir();
138 + mkdirSync(path.join(dir, "src"), { recursive: true });
139 + mkdirSync(path.join(dir, "node_modules"), { recursive: true });
140 + writeFileSync(
141 + path.join(dir, "src", "a.ts"),
142 + "// lazy: rough until API stable\n",
143 + );
144 + writeFileSync(path.join(dir, "node_modules", "b.ts"), "// lazy: nope\n");
145 + const result = scanLazyDebt(dir);
146 + expect(result.markers).toHaveLength(1);
147 + expect(formatDebt(result)).toContain(
148 + "src/a.ts:1 ceiling: rough trigger: API stable",
149 + );
150 + });
152 + it("extracts added markers from unified diff", () => {
153 + const diff = [
154 + "diff --git a/a.ts b/a.ts",
155 + "+++ b/a.ts",
156 + "@@ -0,0 +1,2 @@",
157 + "+const x = 1;",
158 + "+// lazy: fake until real API",
159 + ].join("\n");
160 + expect(markersFromUnifiedDiff(diff)).toEqual([
162 + file: "a.ts",
163 + line: 2,
164 + ceiling: "fake",
165 + trigger: "real API",
166 + noTrigger: false,
167 + },
168 + ]);
169 + });
170 +});

extensions/lazy/index.ts

Added
new 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, pi).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" },
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, pi);
118 + const command = parseLazyCommand(args, settings.defaultMode);
119 + if (command.kind === "invalid") {
120 + notify(ctx, command.message);
121 + return;
123 + if (command.kind === "help") {
124 + notify(ctx, helpText());
125 + return;
127 + if (command.kind === "status") {
128 + notify(ctx, statusText(state.mode, settings.defaultMode));
129 + return;
131 + if (command.kind === "default") {
132 + notify(ctx, `Add to Pi settings:\n${settingsSnippet(command.mode)}`);
133 + return;
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, pi);
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 + return {
186 + systemPrompt: injectLazyInstructions(
187 + event.systemPrompt,
188 + state.mode as ActiveLazyMode,
189 + ),
190 + };
191 + });
193 + pi.on("agent_start", (_event, ctx) => {
194 + state.activeGeneration = true;
195 + updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd, pi).status);
196 + });
198 + pi.on("agent_end", async (_event, ctx) => {
199 + state.activeGeneration = false;
200 + updateStatus(ctx, state, loadLazySettingsForCwd(ctx.cwd, pi).status);
201 + try {
202 + const root = await pi.exec("git", ["rev-parse", "--show-toplevel"], {
203 + cwd: ctx.cwd,
204 + timeout: 5000,
205 + });
206 + if (root.code !== 0) return;
207 + const diff = await pi.exec("git", ["diff", "--unified=0", "--"], {
208 + cwd: ctx.cwd,
209 + timeout: 5000,
210 + });
211 + if (diff.code !== 0 || diff.stdout.length > 256_000) return;
212 + const markers = markersFromUnifiedDiff(diff.stdout, 20);
213 + if (markers.length && ctx.hasUI) {
214 + const files = new Set(markers.map((marker) => marker.file)).size;
215 + ctx.ui.notify(
216 + `lazy debt added: ${markers.length} marker(s) in ${files} file(s). Run /lazy-debt.`,
217 + "info",
218 + );
220 + } catch {
221 + return;
223 + });
226 +export const __lazyTest = {
227 + replayMode,

extensions/lazy/package.json

Added
new 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 + }

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

Added
new 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 +End with `net: -<N> lines, -<M> deps possible.` when reductions exist.
16 +End with `Lean already. Ship.` when no reduction is worth making.
18 +Do not apply fixes.

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

Added
new 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

Added
new 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

Added
new 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

Added
new 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.
14 +Use tags exactly: `delete`, `stdlib`, `native`, `yagni`, `shrink`.
16 +End with `net: -<N> lines 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/SKILL.md

Added
new 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 +Safety floor: never remove trust-boundary validation, data-loss handling, security, accessibility, hardware calibration, or explicitly requested behavior.
22 +Test floor: non-trivial logic leaves one small runnable check; trivial one-liners need no test.
24 +Output code first, then a short skipped/when-to-add note only if useful.

extensions/lazy/src/config.ts

Added
new file mode 100644
1 +import { existsSync, readFileSync } from "node:fs";
2 +import path from "node:path";
3 +import { getAgentDir } from "@earendil-works/pi-coding-agent";
4 +import { type LazyMode, normalizeMode } from "./modes.ts";
6 +export interface LazySettings {
7 + defaultMode: LazyMode;
8 + status: boolean;
9 +}
11 +export const LAZY_DEFAULTS: LazySettings = {
12 + defaultMode: "full",
13 + status: true,
14 +};
16 +export interface SettingsSource {
17 + files: string[];
18 + runtime?: unknown;
21 +type SettingsAPI = {
22 + settingsManager?: { getSettings(): unknown };
23 +};
25 +function isPlainObject(value: unknown): value is Record<string, unknown> {
26 + return value !== null && typeof value === "object" && !Array.isArray(value);
29 +export function pickLazy(raw: unknown): Partial<LazySettings> {
30 + if (!isPlainObject(raw) || !isPlainObject(raw.lazy)) return {};
31 + const out: Partial<LazySettings> = {};
32 + const defaultMode = normalizeMode(raw.lazy.defaultMode);
33 + if (defaultMode) out.defaultMode = defaultMode;
34 + if (typeof raw.lazy.status === "boolean") out.status = raw.lazy.status;
35 + return out;
38 +export function readLazySettings(file: string): Partial<LazySettings> {
39 + try {
40 + if (!existsSync(file)) return {};
41 + return pickLazy(JSON.parse(readFileSync(file, "utf8")));
42 + } catch {
43 + return {};
44 + }
47 +export function mergeLazySettings(
48 + ...partials: Partial<LazySettings>[]
49 +): LazySettings {
50 + return partials.reduce<LazySettings>(
51 + (settings, partial) => ({
52 + defaultMode: partial.defaultMode ?? settings.defaultMode,
53 + status:
54 + typeof partial.status === "boolean" ? partial.status : settings.status,
55 + }),
56 + { ...LAZY_DEFAULTS },
57 + );
60 +export function loadLazySettings(source: SettingsSource): LazySettings {
61 + return mergeLazySettings(
62 + ...source.files.map(readLazySettings),
63 + pickLazy(source.runtime),
64 + );
67 +export function loadLazySettingsForCwd(
68 + cwd: string,
69 + pi: SettingsAPI,
70 +): LazySettings {
71 + return loadLazySettings({
72 + files: [
73 + path.join(getAgentDir(), "settings.json"),
74 + path.join(cwd, ".pi", "settings.json"),
75 + path.join(cwd, "settings.json"),
76 + ],
77 + runtime: pi.settingsManager?.getSettings(),
78 + });
81 +export function settingsSnippet(mode: LazyMode): string {
82 + return JSON.stringify(
83 + { lazy: { defaultMode: mode, status: true } },
84 + null,
85 + "\t",
86 + );

extensions/lazy/src/debt.ts

Added
new 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;
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;
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;
143 + const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/u);
144 + if (hunk) {
145 + newLine = Number(hunk[1]);
146 + continue;
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;
157 + if (markers.length >= max) break;
159 + return markers;

extensions/lazy/src/instructions.ts

Added
new 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 MODE_LINES: Record<ActiveLazyMode, string[]> = {
17 + lite: [
18 + "Build the requested thing, then mention the lazier alternative briefly.",
19 + "Do not block straightforward implementation with repeated challenges.",
20 + ],
21 + full: [
22 + "Enforce the ladder before custom code.",
23 + "Challenge unnecessary scope once, then ship the smallest safe version.",
24 + ],
25 + ultra: [
26 + "Deletion first: remove, merge, inline, or configure before adding code.",
27 + "Challenge nonessential requirements aggressively while preserving explicitly requested behavior.",
28 + ],
29 +};
31 +export function buildLazyInstructions(mode: ActiveLazyMode): string {
32 + return [
33 + `LAZY MODE ACTIVE — level: ${mode}`,
34 + "",
35 + "Ladder:",
36 + ...LADDER.map((line, index) => `${index + 1}. ${line}`),
37 + "",
38 + "Root-cause bug-fix rule: inspect callers and fix the shared route when possible.",
39 + "Safety floor: never remove trust-boundary validation, data-loss handling, security, accessibility, hardware calibration, or explicitly requested behavior.",
40 + "Test floor: non-trivial logic leaves one small runnable check; trivial one-liners need no test.",
41 + "Output discipline: code first; short skipped/when-to-add note; no unrequested essays.",
42 + "",
43 + "Mode-specific:",
44 + ...MODE_LINES[mode].map((line) => `- ${line}`),
45 + "END LAZY MODE",
46 + ].join("\n");
49 +export function stripLazyInstructions(prompt: string): string {
50 + return prompt
51 + .replace(LAZY_HEADER_RE, "\n")
52 + .replace(/\n{3,}/g, "\n\n")
53 + .trimEnd();
56 +export function injectLazyInstructions(
57 + prompt: string,
58 + mode: ActiveLazyMode,
59 +): string {
60 + const base = stripLazyInstructions(prompt);
61 + return `${base}\n\n${buildLazyInstructions(mode)}`;

extensions/lazy/src/modes.ts

Added
new 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);
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;
22 +export function modeFromBareDefault(defaultMode: LazyMode): LazyMode {
23 + return defaultMode === "off" ? "full" : defaultMode;
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 + };
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";

extensions/lazy/src/ui.ts

Added
new 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");
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");
26 +export function statusText(
27 + sessionMode: LazyMode,
28 + defaultMode: LazyMode,
29 +): string {
30 + return `lazy session: ${sessionMode}\nlazy default: ${defaultMode}`;
33 +export function statusSegment(
34 + mode: LazyMode,
35 + active: boolean,
36 +): string | undefined {
37 + if (mode === "off") return undefined;
38 + return `${active ? "●" : "○"} lazy: ${mode}`;

package-lock.json

Modified
178 178 "typebox": "*"
181 + "extensions/lazy": {
182 + "name": "@bugabinga/pi-ext-lazy",
183 + "license": "MIT",
184 + "devDependencies": {
185 + "@marcfargas/pi-test-harness": "^0.6.1",
186 + "vitest": "^4.1.9"
187 + },
188 + "peerDependencies": {
189 + "@earendil-works/pi-coding-agent": "*",
190 + "@earendil-works/pi-tui": "*"
192 + },
181 193 "extensions/leaks": {
182 194 "name": "@bugabinga/pi-ext-leaks",
183 195 "license": "MIT",
213 225 "vitest": "^4.1.9"
215 227 "peerDependencies": {
216 - "@earendil-works/pi-coding-agent": "*"
228 + "@earendil-works/pi-coding-agent": "*",
229 + "@earendil-works/pi-tui": "*"
219 232 "extensions/model-info": {
1292 1305 "resolved": "extensions/goldfish",
1293 1306 "link": true
1308 + "node_modules/@bugabinga/pi-ext-lazy": {
1309 + "resolved": "extensions/lazy",
1310 + "link": true
1311 + },
1295 1312 "node_modules/@bugabinga/pi-ext-leaks": {
1296 1313 "resolved": "extensions/leaks",
1297 1314 "link": true
3826 3843 "arm64"
3828 3845 "dev": true,
3829 - "libc": [
3830 - "glibc"
3831 - ],
3832 3846 "license": "MIT",
3833 3847 "optional": true,
3834 3848 "os": [
3846 3860 "arm64"
3848 3862 "dev": true,
3849 - "libc": [
3850 - "musl"
3851 - ],
3852 3863 "license": "MIT",
3853 3864 "optional": true,
3854 3865 "os": [
3866 3877 "ppc64"
3868 3879 "dev": true,
3869 - "libc": [
3870 - "glibc"
3871 - ],
3872 3880 "license": "MIT",
3873 3881 "optional": true,
3874 3882 "os": [
3886 3894 "s390x"
3888 3896 "dev": true,
3889 - "libc": [
3890 - "glibc"
3891 - ],
3892 3897 "license": "MIT",
3893 3898 "optional": true,
3894 3899 "os": [
3908 3913 "dev": true,
3909 - "libc": [
3910 - "glibc"
3911 - ],
3912 3914 "license": "MIT",
3913 3915 "optional": true,
3914 3916 "os": [
3928 3930 "dev": true,
3929 - "libc": [
3930 - "musl"
3931 - ],
3932 3931 "license": "MIT",
3933 3932 "optional": true,
3934 3933 "os": [
5321 5320 "arm64"
5323 5322 "dev": true,
5324 - "libc": [
5325 - "glibc"
5326 - ],
5327 5323 "license": "MPL-2.0",
5328 5324 "optional": true,
5329 5325 "os": [
5345 5341 "arm64"
5347 5343 "dev": true,
5348 - "libc": [
5349 - "musl"
5350 - ],
5351 5344 "license": "MPL-2.0",
5352 5345 "optional": true,
5353 5346 "os": [
5371 5364 "dev": true,
5372 - "libc": [
5373 - "glibc"
5374 - ],
5375 5365 "license": "MPL-2.0",
5376 5366 "optional": true,
5377 5367 "os": [
5395 5385 "dev": true,
5396 - "libc": [
5397 - "musl"
5398 - ],
5399 5386 "license": "MPL-2.0",
5400 5387 "optional": true,
5401 5388 "os": [

package.json

Modified
26 26 "skills": [
27 27 "extensions/super/skills",
28 - "extensions/ultra/skills"
28 + "extensions/ultra/skills",
29 + "extensions/lazy/skills"

scripts/extensions.mjs

Modified
827 827 errors.push("root: pi.extensions must be ['extensions/*/index.ts']");
829 829 JSON.stringify(pkg.pi?.skills) !==
830 - JSON.stringify(["extensions/super/skills", "extensions/ultra/skills"])
830 + JSON.stringify([
831 + "extensions/super/skills",
832 + "extensions/ultra/skills",
833 + "extensions/lazy/skills",
834 + ])
832 836 errors.push(
833 - "root: pi.skills must be ['extensions/super/skills', 'extensions/ultra/skills']",
837 + "root: pi.skills must be ['extensions/super/skills', 'extensions/ultra/skills', 'extensions/lazy/skills']",
835 839 for (const key of ["prompts", "themes"])
836 840 if (key in (pkg.pi ?? {})) errors.push(`root: pi.${key} must be absent`);

scripts/test_extensions_static_check.mjs

Modified
114 114 assert.deepEqual(rootPkg().pi?.skills, [
115 115 "extensions/super/skills",
116 116 "extensions/ultra/skills",
117 + "extensions/lazy/skills",
118 119 assert.deepEqual(
119 120 JSON.parse(readFileSync(join(ROOT, "extensions/super/package.json"), "utf8"))