pi-ext bugabingas pi extensions
owned by admin
README Source History Refs Compare Notes Search rework extension continuity ownership
33eca6ac0f1c902043efd7eb73f317c38df3ef8a
Oliver Jan Krylow <oliver@bugabinga.net > · 18 Aug 2026
SSH signature · not checked
Browse files Compare with HEAD
Changed files (26) 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) |
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.
114 - "extensions" : [
"extensions/*/index.ts" ],
115 - "skills" : [
"extensions/lazy/skills" ]
115 + "extensions" : [
"extensions/*/index.ts" ]
extensions/continuity/README.md Added new file mode 100644 3 + Continues the current Pi task after context compaction.
7 + Loaded through the root `pi-ext` package.
8 + See [../../README.md](../../README.md).
10 + ##
Commands / tools / settings 12 + No commands, tools, or settings.
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.
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 ;
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);
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] });
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 ,
35 + await new Promise ((resolve)
=> setTimeout (resolve,
10 ));
37 + expect (send).
toHaveBeenCalledOnce ();
38 + expect (send).
toHaveBeenCalledWith (
39 + expect.
objectContaining ({
40 + customType:
"continuity-resume" ,
43 + { triggerTurn:
true , deliverAs:
"followUp" },
extensions/continuity/__tests__/unit.test.ts Added new file mode 100644 1 + import { afterEach, beforeEach, describe, expect, it, vi }
from "vitest" ;
2 + import continuityExtension, {
4 + buildContinuationPrompt,
7 + type Handler = (event
: any , ctx
: any )
=> unknown ;
9 + function compactionEvent (
10 + overrides
: Record <
string ,
unknown >
= {},
11 + )
: Record <
string ,
unknown > {
13 + type:
"session_compact" ,
14 + compactionEntry: { id:
"compact-1" },
15 + fromExtension:
false ,
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 []
= [];
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 ;
35 + on (event
: string , handler
: Handler ) {
36 + handlers.
set (
event , [
... (handlers.
get (
event )
?? []), handler]);
38 + getActiveTools : ()
=> activeTools,
39 + sendMessage (message
: any , options
: any ) {
40 + if (sendError)
throw sendError;
41 + sent.
push ({ message, options });
46 + hasPendingMessages : ()
=> pendingMessages,
48 + getSessionId : ()
=> sessionId,
49 + getSessionFile : ()
=> sessionFile,
50 + getBranch : ()
=> branch,
53 + notify (message
: string , severity
: string ) {
54 + notices.
push ([message, severity]);
58 + continuityExtension (pi
as never );
64 + emit (event
: string , payload
: any = {}) {
65 + for (
const handler
of handlers.
get (
event )
?? [])
handler (payload, ctx);
67 + setActiveTools (names
: string []) {
68 + activeTools
= names;
70 + setIdle (value
: boolean ) {
73 + setPendingMessages (value
: boolean ) {
74 + pendingMessages
= value;
76 + setSessionId (value
: string ) {
79 + setSessionFile (value
: string | undefined ) {
80 + sessionFile
= value;
82 + setBranch (value
: any []) {
85 + setSendError (error
: Error | undefined ) {
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' ,
101 + expect (prompt).
toContain (
102 + "Use the compaction summary and current worktree first." ,
104 + expect (prompt).
toContain (
105 + 'Persisted session JSONL: "/sessions/a \\"quoted\\" session.jsonl".' ,
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" );
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".' );
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,
135 + details: { compactionEntryId:
"compact-1" , reason },
137 + expect (h.sent[
0 ].
options ).
toEqual ({
139 + deliverAs:
"followUp" ,
144 + it (
"does not duplicate Pi's overflow retry" ,
async ()
=> {
145 + const h
= createHarness ();
149 + compactionEvent ({ reason:
"overflow" , willRetry:
true }),
151 + await vi.
runAllTimersAsync ();
153 + expect (h.sent).
toEqual ([]);
156 + it (
"continues after non-retrying overflow compaction" ,
async ()
=> {
157 + const h
= createHarness ();
161 + compactionEvent ({ reason:
"overflow" , willRetry:
false }),
163 + await vi.
runAllTimersAsync ();
165 + expect (h.sent).
toHaveLength (
1 );
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 ([]);
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 ([]);
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 ([]);
198 + it (
"does not dispatch while Pi remains busy" ,
async ()
=> {
199 + const h
= createHarness ();
202 + h.
emit (
"session_compact" ,
compactionEvent ());
203 + await vi.
runAllTimersAsync ();
205 + expect (h.sent).
toEqual ([]);
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 ([]);
218 + it (
"replaces an obsolete scheduled continuation with the latest compaction" ,
async ()
=> {
219 + const h
= createHarness ();
221 + h.
emit (
"session_compact" ,
compactionEvent ());
224 + compactionEvent ({ compactionEntry: { id:
"compact-2" } }),
226 + await vi.
runAllTimersAsync ();
228 + expect (h.sent).
toHaveLength (
1 );
229 + expect (h.sent[
0 ].message.details.compactionEntryId).
toBe (
"compact-2" );
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 ([]);
242 + it.
each ([
"update_goal" ,
"run_experiment" ,
"log_experiment" ])(
243 + "yields to specialized continuation capability %s" ,
245 + const h
= createHarness ();
246 + h.
setActiveTools ([tool]);
248 + h.
emit (
"session_compact" ,
compactionEvent ());
249 + await vi.
runAllTimersAsync ();
251 + expect (h.sent).
toEqual ([]);
255 + it (
"yields to an active first-turn goal before update_goal becomes active" ,
async ()
=> {
256 + const h
= createHarness ();
260 + customType: __test.GOAL_STATE_TYPE,
261 + data: { status:
"active" , sessionId:
"session-1" , turnsUsed:
0 },
265 + h.
emit (
"session_compact" ,
compactionEvent ());
266 + await vi.
runAllTimersAsync ();
268 + expect (h.sent).
toEqual ([]);
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 );
285 + it (
"uses the latest goal state event" ,
async ()
=> {
286 + const h
= createHarness ();
290 + customType: __test.GOAL_STATE_TYPE,
291 + data: { status:
"active" , sessionId:
"session-1" },
295 + customType: __test.GOAL_STATE_TYPE,
296 + data: { status:
"paused" , sessionId:
"session-1" },
300 + h.
emit (
"session_compact" ,
compactionEvent ());
301 + await vi.
runAllTimersAsync ();
303 + expect (h.sent).
toHaveLength (
1 );
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 ([]);
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 );
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" ],
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" );
extensions/continuity/index.ts Added new file mode 100644 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 ([
15 + type PendingContinuation = {
17 + timer
: ReturnType <
typeof setTimeout>;
20 + export function buildContinuationPrompt (
21 + sessionFile
: string | undefined ,
22 + compactionEntryId
: string ,
24 + const sessionSource
= 25 + sessionFile
=== undefined 26 + ? "This session is ephemeral, so no persisted history is available." 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." ,
34 + "Compaction completed. Continue the existing task now instead of waiting for user input." ,
35 + "Use the compaction summary and current worktree first." ,
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." ,
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];
54 + entry.
type !== "custom" || 55 + entry.customType
!== GOAL_STATE_TYPE
|| 56 + ! isRecord (entry.
data )
60 + entry.
data .
status === "active" && 61 + (entry.
data .sessionId
=== undefined || entry.
data .sessionId
=== sessionId)
67 + function hasSpecializedContinuation (
69 + ctx
: ExtensionContext ,
72 + hasActiveGoal (ctx)
|| 73 + pi.
getActiveTools ().
some ((name)
=> SPECIALIZED_CONTINUATION_TOOLS.
has (name))
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 ;
86 + const sameSession = (ctx
: ExtensionContext , sessionId
: string )
: boolean => {
88 + return ctx.sessionManager.
getSessionId ()
=== sessionId;
94 + const scheduleContinuation = (
95 + event : SessionCompactEvent ,
96 + ctx
: ExtensionContext ,
101 + ctx.
hasPendingMessages ()
|| 102 + hasSpecializedContinuation (pi, ctx)
106 + const sessionId
= ctx.sessionManager.
getSessionId ();
107 + const prompt
= buildContinuationPrompt (
108 + ctx.sessionManager.
getSessionFile (),
109 + event .compactionEntry.
id ,
111 + const candidate
: PendingContinuation = {
113 + timer:
setTimeout (()
=> {
114 + if (pending
!== candidate)
return ;
115 + pending
= undefined ;
117 + ! sameSession (ctx, sessionId)
|| 119 + ctx.
hasPendingMessages ()
|| 120 + hasSpecializedContinuation (pi, ctx)
126 + customType: CONTINUATION_TYPE,
130 + compactionEntryId:
event .compactionEntry.
id ,
131 + reason:
event .reason,
134 + { triggerTurn:
true , deliverAs:
"followUp" },
138 + `Continuity could not resume: ${error instanceof Error ? error.message : String (error)}` ,
144 + pending
= candidate;
147 + pi.
on (
"session_compact" , scheduleContinuation);
148 + pi.
on (
"agent_start" , cancelPending);
149 + pi.
on (
"session_shutdown" , cancelPending);
152 + export const __test
= {
155 + SPECIALIZED_CONTINUATION_TOOLS,
extensions/continuity/package.json Added new file mode 100644 2 + "name" :
"@bugabinga/pi-ext-continuity" ,
6 + "peerDependencies" : {
7 + "@earendil-works/pi-coding-agent" :
"*" 10 + "@marcfargas/pi-test-harness" :
"^0.6.1" ,
14 + "test:harness" :
"vitest run ./__tests__/harness.test.ts" ,
15 + "test" :
"vitest run ./__tests__/*.test.ts" 18 + "description" :
"Continue Pi tasks after context compaction." ,
extensions/lazy/README.md Deleted deleted file mode 100644 3 - Pi-native lazy senior dev mode.
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.
22 - "defaultMode" :
"full" ,
28 - Valid modes: `off`, `lite`, `full`, `ultra`.
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}` );
21 - async function runCommand (name
: string , args
= "" )
: Promise <
void > {
22 - if (
! t)
throw new Error (
"missing test session" );
23 - await command (name).
handler (
25 - t.session.extensionRunner.
createCommandContext (),
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" );
36 - t.session.sessionManager.
getEntries ()
as Array <{
38 - customType
?: string ;
39 - data
?: Record <
string ,
unknown >;
42 - .
filter ((entry)
=> entry.
type === "custom" && entry.customType
=== kind)
43 - .
map ((entry)
=> entry.
data ?? {});
51 - describe (
"lazy harness" , ()
=> {
52 - it (
"loads in real Pi extension runtime and registers commands" ,
async ()
=> {
53 - t
= await createTestSession ({ extensions: [
extensionPath ()] });
55 - ... t.session.extensionRunner.extensions[
0 ].commands.
keys (),
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 ({
71 - at: expect.
any (
Number ),
73 - expect (
uiArgs (
"setStatus" ).
at (
- 1 )).
toEqual ([
"lazy" ,
"○ lazy: ultra" ]);
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 (
84 - expect (result?.systemPrompt).
toContain (
"LAZY MODE ACTIVE — level: full" );
85 - await runCommand (
"lazy" ,
"full" );
86 - result
= await t.session.extensionRunner.
emitBeforeAgentStart (
92 - expect (result?.systemPrompt).
toContain (
"LAZY MODE ACTIVE — level: full" );
93 - await runCommand (
"lazy" ,
"off" );
94 - result
= await t.session.extensionRunner.
emitBeforeAgentStart (
100 - expect (result).
toBeUndefined ();
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 = (
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" } },
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" ,
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 ({
140 - expect (
uiArgs (
"setStatus" ).
at (
- 1 )).
toEqual ([
"lazy" ,
"○ lazy: ultra" ]);
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 ({
149 - text:
"normal mode." ,
150 - source:
"interactive" ,
152 - expect (
customEntries (
"lazy-mode" ).
at (
- 1 )).
toEqual ({
154 - at: expect.
any (
Number ),
156 - expect (
uiArgs (
"setStatus" ).
at (
- 1 )).
toEqual ([
"lazy" ,
undefined ]);
159 - it (
"status gracefully does nothing when disabled" ,
async ()
=> {
160 - t
= await createTestSession ({ extensionFactories: [lazyExtension] });
161 - mkdirSync (path.
join (t.cwd,
".pi" ), { recursive:
true });
163 - path.
join (t.cwd,
".pi" ,
"settings.json" ),
164 - JSON .
stringify ({ lazy: { status:
false } }),
166 - t.events.ui.
length = 0 ;
167 - await runCommand (
"lazy" ,
"ultra" );
168 - expect (
uiArgs (
"setStatus" )).
toEqual ([]);
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" ], {
177 - execFileSync (
"git" , [
"config" ,
"user.email" ,
"lazy@example.invalid" ], {
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 });
186 - "const x = 1;\n// lazy: fake until real API\n" ,
188 - await t.session.extensionRunner.
emit ({
192 - expect (
uiArgs (
"notify" ).
at (
- 1 )).
toEqual ([
193 - "lazy debt added: 1 marker(s) in 1 file(s). Run /lazy-debt." ,
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" ;
8 - loadLazySettingsForCwd,
12 - }
from "../src/config.ts" ;
15 - markersFromUnifiedDiff,
18 - }
from "../src/debt.ts" ;
20 - buildLazyInstructions,
21 - injectLazyInstructions,
22 - }
from "../src/instructions.ts" ;
24 - isStandaloneDeactivation,
25 - modeFromBareDefault,
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 });
37 - async function tempDir ()
: Promise <
string > {
38 - const dir
= await mkdtemp (path.
join (
tmpdir (),
"lazy-test-" ));
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 ();
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" });
55 - it (
"parses status and default" , ()
=> {
56 - expect (
parseLazyCommand (
"status" ,
"full" )).
toEqual ({ kind:
"status" });
57 - expect (
parseLazyCommand (
"/lazy status" ,
"full" )).
toEqual ({
60 - expect (
parseLazyCommand (
"default ultra" ,
"full" )).
toEqual ({
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 );
73 - describe (
"config" , ()
=> {
74 - it (
"picks and merges valid lazy settings only" , ()
=> {
76 - pickLazy ({ lazy: { defaultMode:
"ultra" , status:
false , nope:
true } }),
77 - ).
toEqual ({ defaultMode:
"ultra" , status:
false });
78 - expect (
pickLazy ({ lazy: { defaultMode:
"review" } })).
toEqual ({});
80 - mergeLazySettings ({ defaultMode:
"lite" }, { status:
false }),
82 - defaultMode:
"lite" ,
87 - it (
"loads runtime Pi settings and ignores workspace-root settings.json" ,
async ()
=> {
88 - const dir
= await tempDir ();
90 - path.
join (dir,
"settings.json" ),
91 - JSON .
stringify ({ lazy: { defaultMode:
"lite" } }),
94 - mkdirSync (path.
join (dir,
".pi" ));
96 - path.
join (dir,
".pi" ,
"settings.json" ),
97 - JSON .
stringify ({ lazy: { defaultMode:
"ultra" } }),
99 - expect (
loadLazySettingsForCwd (dir).defaultMode).
toBe (
"ultra" );
101 - writeFileSync (path.
join (dir,
".pi" ,
"settings.json" ),
"{}" );
102 - expect (
loadLazySettingsForCwd (dir).defaultMode).
toBe (
"full" );
105 - it (
"prints settings snippet" , ()
=> {
106 - expect (
settingsSnippet (
"off" )).
toContain (
'"defaultMode": "off"' );
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" );
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:`" );
125 - it (
"before_agent_start tolerates a missing event or prompt" , ()
=> {
126 - const events
= new Map <
string , (
... args
: never [])
=> unknown >();
128 - on : (name
: string ,
handler : (
... args
: never [])
=> unknown )
=> 129 - events.
set (name, handler),
130 - registerCommand : ()
=> undefined ,
131 - appendEntry : ()
=> undefined ,
136 - sessionManager: {
getBranch : ()
=> [] },
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" ),
144 - expect (
JSON .
stringify (missingEvent)).not.
toContain (
"undefined" );
145 - expect (missingPrompt).
toEqual ({
146 - systemPrompt: expect.
stringContaining (
"LAZY MODE ACTIVE" ),
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" );
159 - describe (
"debt" , ()
=> {
160 - it (
"parses markers and missing triggers" , ()
=> {
162 - parseLazyMarker (
"// lazy: cap at 10 until > 10 users" ,
"a.ts" ,
3 ),
166 - ceiling:
"cap at 10" ,
167 - trigger:
"> 10 users" ,
170 - expect (
parseLazyMarker (
"# lazy: ship quick" ,
"a.sh" ,
1 )?.noTrigger).
toBe (
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 });
180 - path.
join (dir,
"src" ,
"a.ts" ),
181 - "// lazy: rough until API stable\n" ,
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" ,
191 - it (
"extracts added markers from unified diff" , ()
=> {
193 - "diff --git a/a.ts b/a.ts" ,
197 - "+// lazy: fake until real API" ,
199 - expect (
markersFromUnifiedDiff (diff)).
toEqual ([
204 - trigger:
"real API" ,
extensions/lazy/index.ts Deleted deleted file mode 100644 4 - }
from "@earendil-works/pi-coding-agent" ;
5 - import type { AutocompleteItem }
from "@earendil-works/pi-tui" ;
6 - import { loadLazySettingsForCwd, settingsSnippet }
from "./src/config.ts" ;
9 - markersFromUnifiedDiff,
11 - }
from "./src/debt.ts" ;
12 - import { injectLazyInstructions }
from "./src/instructions.ts" ;
14 - type ActiveLazyMode,
15 - isStandaloneDeactivation,
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 };
29 - activeGeneration
: boolean ;
32 - function modeEntry (data
: unknown )
: ModeEntry | undefined {
33 - if (
! data
|| typeof data
!== "object" )
return undefined ;
34 - const entry
= data
as Record <
string ,
unknown >;
36 - (entry.mode
=== "off" || 37 - entry.mode
=== "lite" || 38 - entry.mode
=== "full" || 39 - entry.mode
=== "ultra" )
&& 40 - typeof entry.at
=== "number" 42 - return { mode: entry.mode, at: entry.at };
48 - entries
: readonly EntryLike [],
49 - defaultMode
: 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;
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 ,
69 - if (
! ctx.hasUI
|| ! enabled)
return ;
72 - statusSegment (state.mode, state.activeGeneration),
80 - ctx
: ExtensionContext ,
83 - pi.
appendEntry (ENTRY_TYPE, { mode, at:
Date .
now () });
84 - updateStatus (ctx, state,
loadLazySettingsForCwd (ctx.cwd).
status );
89 - ctx
: ExtensionContext ,
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));
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);
123 - if (command.kind
=== "help" ) {
124 - notify (ctx,
helpText ());
127 - if (command.kind
=== "status" ) {
128 - notify (ctx,
statusText (state.mode, settings.defaultMode));
131 - if (command.kind
=== "default" ) {
132 - notify (ctx,
`Add to Pi settings:\n${ settingsSnippet (command.mode)}` );
135 - appendMode (pi, state, command.mode, ctx);
136 - notify (ctx,
`lazy: ${command.mode}` );
140 - pi.
registerCommand (
"lazy-review" , {
141 - description:
"Review current diff for over-engineering" ,
142 - handler :
async (args, ctx)
=> sendSkill (pi, ctx,
"lazy-review" , args),
144 - pi.
registerCommand (
"lazy-audit" , {
145 - description:
"Audit repo for over-engineering" ,
146 - handler :
async (args, ctx)
=> sendSkill (pi, ctx,
"lazy-audit" , args),
148 - pi.
registerCommand (
"lazy-debt" , {
149 - description:
"List lazy debt markers" ,
150 - handler :
async (_args, ctx)
=> 151 - notify (ctx,
formatDebt (
scanLazyDebt (ctx.cwd))),
153 - pi.
registerCommand (
"lazy-gain" , {
154 - description:
"Show published lazy benchmark medians" ,
155 - handler :
async (_args, ctx)
=> notify (ctx,
gainText ()),
157 - pi.
registerCommand (
"lazy-help" , {
158 - description:
"Show lazy help" ,
159 - handler :
async (_args, ctx)
=> notify (ctx,
helpText ()),
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,
168 - state.activeGeneration
= false ;
169 - updateStatus (ctx, state, settings.
status );
172 - pi.
on (
"session_shutdown" , (_event, ctx)
=> {
173 - state.activeGeneration
= false ;
174 - if (ctx.hasUI) ctx.ui.
setStatus (STATUS_KEY,
undefined );
177 - pi.
on (
"input" , (event, ctx)
=> {
178 - if (
! isStandaloneDeactivation (
event .
text ))
return ;
179 - appendMode (pi, state,
"off" , ctx);
180 - return { action:
"handled" };
183 - pi.
on (
"before_agent_start" , (event)
=> {
184 - if (state.mode
=== "off" )
return ;
186 - event && typeof event .systemPrompt
=== "string" ? event .systemPrompt
: "" ;
188 - systemPrompt:
injectLazyInstructions (
190 - state.mode
as ActiveLazyMode ,
195 - pi.
on (
"agent_start" , (_event, ctx)
=> {
196 - state.activeGeneration
= true ;
197 - updateStatus (ctx, state,
loadLazySettingsForCwd (ctx.cwd).
status );
200 - pi.
on (
"agent_end" ,
async (_event, ctx)
=> {
201 - state.activeGeneration
= false ;
202 - updateStatus (ctx, state,
loadLazySettingsForCwd (ctx.cwd).
status );
204 - const root
= await pi.
exec (
"git" , [
"rev-parse" ,
"--show-toplevel" ], {
208 - if (
root .
code !== 0 )
return ;
209 - const diff
= await pi.
exec (
"git" , [
"diff" ,
"--unified=0" ,
"--" ], {
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 ;
218 - `lazy debt added: ${markers. length } marker(s) in ${files} file(s). Run /lazy-debt.` ,
228 - export const __lazyTest
= {
extensions/lazy/package.json Deleted deleted file mode 100644 2 - "name" :
"@bugabinga/pi-ext-lazy" ,
7 - "description" :
"Pi-native lazy senior dev mode." ,
14 - "peerDependencies" : {
15 - "@earendil-works/pi-coding-agent" :
"*" ,
16 - "@earendil-works/pi-tui" :
"*" 18 - "devDependencies" : {
19 - "@marcfargas/pi-test-harness" :
"^0.6.1" ,
23 - "test" :
"vitest run ./__tests__/*.test.ts" extensions/lazy/skills/lazy-audit/SKILL.md Deleted deleted file mode 100644 3 - description: Scan the repository for over-engineering and rank largest safe reductions first; no fixes applied.
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.
extensions/lazy/skills/lazy-debt/SKILL.md Deleted deleted file mode 100644 3 - description: Find deliberate lazy shortcut comments and their upgrade triggers.
8 - Find comments marked `lazy:`.
10 - Report file, line, ceiling, and upgrade trigger.
12 - Flag markers without a trigger as `no-trigger`.
extensions/lazy/skills/lazy-gain/SKILL.md Deleted deleted file mode 100644 3 - description: Explain published Lazy/Ponytail benchmark medians honestly.
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 3 - description: Show Lazy command, mode, deactivation, and settings reference.
8 - Explain commands, modes, deactivation, and settings.
extensions/lazy/skills/lazy-review/SKILL.md Deleted deleted file mode 100644 3 - description: Review the current diff for over-engineering only; no fixes applied.
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.
extensions/lazy/skills/lazy/SKILL.md Deleted deleted file mode 100644 3 - description: "Always-on lazy senior dev guidance: YAGNI, reuse, stdlib, native platform, installed deps, one-line solution, minimum custom code."
8 - Use the smallest safe implementation.
12 - 1. Do not build what was not asked.
13 - 2. Reuse existing code in this repo.
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.
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 ;
9 - export const LAZY_DEFAULTS
: LazySettings = {
10 - defaultMode:
"full" ,
14 - function isPlainObject (value
: unknown )
: value
is Record <
string ,
unknown > {
15 - return value
!== null && typeof value
=== "object" && ! Array .
isArray (value);
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 ;
27 - export function mergeLazySettings (
28 - ... partials
: Partial <
LazySettings >[]
30 - return partials.
reduce <
LazySettings >(
31 - (settings, partial)
=> ({
32 - defaultMode: partial.defaultMode
?? settings.defaultMode,
34 - typeof partial.
status === "boolean" ? partial.
status : settings.
status ,
36 - {
... LAZY_DEFAULTS },
40 - export function loadLazySettings (runtime
?: unknown )
: LazySettings {
41 - return mergeLazySettings (
pickLazy (runtime));
44 - export function loadLazySettingsForCwd (cwd
: string )
: LazySettings {
45 - const manager
= SettingsManager.
create (cwd);
46 - return mergeLazySettings (
47 - pickLazy (manager.
getGlobalSettings ()),
48 - pickLazy (manager.
getProjectSettings ()),
52 - export function settingsSnippet (mode
: LazyMode )
: string {
53 - return JSON .
stringify (
54 - { lazy: { defaultMode: mode, status:
true } },
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 ([
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 {
28 - export interface ScanOptions {
29 - maxFileBytes
?: number ;
30 - maxMarkers
?: number ;
33 - export interface ScanResult {
34 - markers
: LazyDebtMarker [];
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 )
48 - .
replace (
/[;,-] +$ / u ,
"" );
50 - ceiling: ceiling
|| "unspecified" ,
51 - trigger: triggerMatch[
1 ].
trim ().
replace (
/\s * (?:\*\/ | -->)\s *$ / u ,
"" ),
55 - export function parseLazyMarker (
59 - )
: LazyDebtMarker | undefined {
60 - const match
= lineText.
match (MARKER_RE);
61 - if (
! match)
return undefined ;
62 - const parsed
= parseMarkerText (match[
1 ]
?? "" );
66 - ceiling: parsed.ceiling,
67 - trigger: parsed.trigger,
68 - noTrigger:
! parsed.trigger,
72 - function scanFile (abs
: string , rel
: string )
: LazyDebtMarker [] {
73 - const buffer
= readFileSync (abs);
74 - if (
isBinary (buffer))
return [];
78 - .
flatMap ((lineText, index)
=> {
79 - const marker
= parseLazyMarker (lineText, rel, index
+ 1 );
80 - return marker
? [marker]
: [];
84 - export function scanLazyDebt (
86 - options
: ScanOptions = {},
88 - const maxFileBytes
= options.maxFileBytes
?? 256 * 1024 ;
89 - const maxMarkers
= options.maxMarkers
?? 100 ;
90 - const markers
: LazyDebtMarker []
= [];
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 ;
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 ;
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);
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
124 - : `trigger: ${marker.trigger}` ;
125 - return `${marker.file}:${marker.line} ceiling: ${marker.ceiling} ${trigger}` ;
127 - if (result.omitted
> 0 ) lines.
push (
`… ${result.omitted} omitted` );
128 - return lines.
join (
"\n" );
131 - export function markersFromUnifiedDiff (
134 - )
: LazyDebtMarker [] {
135 - const markers
: LazyDebtMarker []
= [];
138 - for (
const line
of diff.
split (
/\r ? \n/ u )) {
139 - if (line.
startsWith (
"+++ b/" )) {
140 - file
= line.
slice (
6 );
143 - const hunk
= line.
match (
/ ^ @@ -\d + (?:,\d + ) ? \+(\d + )(?:,\d + ) ? @@/ u );
145 - newLine
= Number (hunk[
1 ]);
148 - if (line.
startsWith (
"+" )
&& ! line.
startsWith (
"+++" )) {
149 - const marker
= parseLazyMarker (line.
slice (
1 ), file, newLine);
150 - if (marker) markers.
push (marker);
152 - }
else if (line.
startsWith (
"-" )
&& ! line.
startsWith (
"---" )) {
157 - if (markers.
length >= max)
break ;
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 ;
7 - "Do not build what was not asked." ,
8 - "Reuse existing code in this repo." ,
10 - "Prefer native platform APIs." ,
11 - "Prefer installed deps over new deps." ,
12 - "Prefer one-line/data-only changes." ,
13 - "Write minimum custom code." ,
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." ,
24 - const MODE_LINES
: Record <
ActiveLazyMode ,
string []>
= {
26 - "Build the requested thing, then mention the lazier alternative briefly." ,
27 - "Do not block straightforward implementation with repeated challenges." ,
30 - "Enforce the ladder before custom code." ,
31 - "Challenge unnecessary scope once, then ship the smallest safe version." ,
34 - "Deletion first: remove, merge, inline, or configure before adding code." ,
35 - "Challenge nonessential requirements aggressively while preserving explicitly requested behavior." ,
39 - export function buildLazyInstructions (mode
: ActiveLazyMode )
: string {
41 - `LAZY MODE ACTIVE — level: ${mode}` ,
44 - ... LADDER.
map ((line, index)
=> `${index + 1}. ${line}` ),
46 - "Root-cause bug-fix rule: inspect callers and fix the shared route when possible." ,
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." ,
54 - ... MODE_LINES[mode].
map ((line)
=> `- ${line}` ),
59 - export function stripLazyInstructions (prompt
: string )
: string {
61 - .
replace (LAZY_HEADER_RE,
"\n" )
62 - .
replace (
/\n {3,} / g ,
"\n\n" )
66 - export function injectLazyInstructions (
68 - mode
: ActiveLazyMode ,
70 - const base
= stripLazyInstructions (prompt);
71 - return `${base}\n\n${ buildLazyInstructions (mode)}` ;
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 }
8 - | { kind
: "default" ; mode
: LazyMode }
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 (
28 - defaultMode
: LazyMode ,
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" };
38 - if (first
=== "default" ) {
39 - const mode
= normalizeMode (parts[
1 ]);
40 - if (
! mode
|| parts.
length !== 2 ) {
43 - message:
"usage: /lazy default off|lite|full|ultra" ,
46 - return { kind:
"default" , mode };
48 - const mode
= normalizeMode (first);
49 - if (mode
&& parts.
length === 1 )
return { kind:
"set" , mode };
52 - message:
"usage: /lazy [off|lite|full|ultra|status|default <mode>]" ,
56 - export function isStandaloneDeactivation (input
: string )
: boolean {
57 - const normalized
= input
60 - .
replace (
/[.!?。!?] +$ / u ,
"" )
62 - return normalized
=== "stop lazy" || normalized
=== "normal mode" ;
extensions/lazy/src/ui.ts Deleted deleted file mode 100644 1 - import type { LazyMode }
from "./modes.ts" ;
3 - export function helpText ()
: string {
6 - "/lazy [lite|full|ultra|off]" ,
8 - "/lazy default <mode>" ,
9 - "/lazy-review [args]" ,
10 - "/lazy-audit [args]" ,
13 - "deactivate: stop lazy | normal mode" ,
14 - "settings: lazy.defaultMode, lazy.status" ,
18 - export function gainText ()
: string {
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%" ,
26 - export function statusText (
27 - sessionMode
: LazyMode ,
28 - defaultMode
: LazyMode ,
30 - return `lazy session: ${sessionMode}\nlazy default: ${defaultMode}` ;
33 - export function statusSegment (
36 - )
: string | undefined {
37 - if (mode
=== "off" )
return undefined ;
38 - return `${active ? "●" : "○"} lazy: ${mode}` ;
package-lock.json Modified 76 76 "@earendil-works/pi-coding-agent" :
"*" 79 + "extensions/continuity" : {
80 + "name" :
"@bugabinga/pi-ext-continuity" ,
82 + "devDependencies" : {
83 + "@marcfargas/pi-test-harness" :
"^0.6.1" ,
86 + "peerDependencies" : {
87 + "@earendil-works/pi-coding-agent" :
"*" 79 90 "extensions/cost" : {
80 91 "name" :
"@bugabinga/pi-ext-cost" ,
196 - "extensions/lazy" : {
197 - "name" :
"@bugabinga/pi-ext-lazy" ,
199 - "devDependencies" : {
200 - "@marcfargas/pi-test-harness" :
"^0.6.1" ,
203 - "peerDependencies" : {
204 - "@earendil-works/pi-coding-agent" :
"*" ,
205 - "@earendil-works/pi-tui" :
"*" 208 207 "extensions/leaks" : {
209 208 "name" :
"@bugabinga/pi-ext-leaks" ,
210 209 "license" :
"MIT" ,
1283 1282 "resolved" :
"extensions/context-size" ,
1285 + "node_modules/@bugabinga/pi-ext-continuity" : {
1286 + "resolved" :
"extensions/continuity" ,
1286 1289 "node_modules/@bugabinga/pi-ext-cost" : {
1287 1290 "resolved" :
"extensions/cost" ,
1319 1322 "resolved" :
"extensions/goldfish" ,
1322 - "node_modules/@bugabinga/pi-ext-lazy" : {
1323 - "resolved" :
"extensions/lazy" ,
1326 1325 "node_modules/@bugabinga/pi-ext-leaks" : {
1327 1326 "resolved" :
"extensions/leaks" ,
33 33 "extensions/*/index.ts" 36 - "extensions/lazy/skills" scripts/extensions.mjs Modified 890 890 JSON .
stringify ([
"extensions/*/index.ts" ])
892 892 errors.push(
"root: pi.extensions must be ['extensions/*/index.ts']" );
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(