@geminixiang/pi-simplify 0.0.3 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +44 -19
  2. package/index.ts +585 -64
  3. package/package.json +32 -21
  4. package/tsconfig.json +11 -0
package/README.md CHANGED
@@ -1,47 +1,72 @@
1
1
  # pi-simplify
2
2
 
3
- A [pi coding agent](https://github.com/mariozechner/pi) extension that adds a `/simplify` command to review changed code for reuse, quality, and efficiency — then fix any issues found.
3
+ [![npm version](https://img.shields.io/npm/v/@geminixiang/pi-simplify.svg)](https://www.npmjs.com/package/@geminixiang/pi-simplify)
4
+
5
+ A [pi coding agent](https://github.com/mariozechner/pi) extension that cleans up leftover code after feature implementation.
4
6
 
5
7
  ## What it does
6
8
 
7
- Running `/simplify` launches three parallel sub-agents that each review your git diff from a different angle:
9
+ After implementing a feature, your code often accumulates:
8
10
 
9
- - **Code Reuse** — finds newly written code that duplicates existing utilities or helpers
10
- - **Code Quality** — catches hacky patterns: redundant state, parameter sprawl, copy-paste blocks, leaky abstractions, stringly-typed code, unnecessary comments
11
- - **Efficiency** — spots unnecessary work, missed concurrency, hot-path bloat, memory leaks, and overly broad operations
11
+ - **Dead code** - unused exports, orphaned files, zombie variables
12
+ - **Debug remnants** - console.log, debugger statements, temp flags
13
+ - **Commented-out code** - old logic left in comments
14
+ - **Over-engineering** - "might use later" abstractions never used
15
+ - **Duplicate logic** - repeated if-else blocks doing the same thing
12
16
 
13
- After all three agents finish, issues are aggregated and fixed in place. A brief summary is printed at the end.
17
+ `/simplify` finds these and removes them.
14
18
 
15
19
  ## Installation
16
20
 
17
- ### 1. Install pi-subagents
18
-
19
- `pi-simplify` relies on the Agent tool provided by the `pi-subagents` package. Install it first:
20
-
21
- ```sh
22
- pi install npm:pi-subagents
23
- ```
24
-
25
- ### 2. Install pi-simplify
26
-
27
21
  ```sh
28
22
  pi install npm:@geminixiang/pi-simplify
29
23
  ```
30
24
 
31
25
  ## Usage
32
26
 
33
- After installation, the `/simplify` command is available inside pi:
27
+ ### Full Simplify
34
28
 
35
29
  ```
36
30
  /simplify
37
31
  ```
38
32
 
39
- You can also pass an optional focus area to narrow the review:
33
+ Analyzes all git changes and presents cleanup candidates:
34
+
35
+ - **Safe** (green) - auto-selected, will be deleted
36
+ - **Confirm** (yellow) - delete after user confirms
37
+ - **Review** (orange) - user should review first
38
+
39
+ ### Quick Simplify
40
+
41
+ ```
42
+ /simplify-quick
43
+ ```
44
+
45
+ Only removes the obviously safe stuff:
46
+
47
+ - `console.log` / `console.warn` / `console.error`
48
+ - `debugger` statements
49
+ - Unused imports
50
+ - Empty catch blocks
51
+
52
+ No confirmation needed - just does it.
53
+
54
+ ### With Focus
40
55
 
41
56
  ```
42
- /simplify focus on performance in the database layer
57
+ /simplify focus on the utils folder
58
+ /simplify focus on removing debug code
43
59
  ```
44
60
 
61
+ ## Comparison with pi-review
62
+
63
+ | | pi-review | pi-simplify |
64
+ | ------------ | --------------------------- | --------------------- |
65
+ | **Goal** | Find problems | Delete excess |
66
+ | **Attitude** | Conservative (marks issues) | Active (removes junk) |
67
+ | **Output** | Findings list | Deletion plan |
68
+ | **Trigger** | Manual review | Post-feature cleanup |
69
+
45
70
  ## License
46
71
 
47
72
  MIT
package/index.ts CHANGED
@@ -1,89 +1,610 @@
1
+ /**
2
+ * pi-simplify: Code Cleanup Extension for pi
3
+ *
4
+ * Removes leftover code after feature implementation:
5
+ * - Dead code (unused exports, orphaned files)
6
+ * - Debug remnants (console.log, debugger, temp flags)
7
+ * - Commented-out code
8
+ * - Over-engineering ("might use later" abstractions)
9
+ * - Duplicate logic
10
+ */
11
+
1
12
  import type { ExtensionAPI, ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
13
+ import { matchesKey, Key, truncateToWidth, type SelectItem } from "@mariozechner/pi-tui";
14
+
15
+ type SimplifyResult = {
16
+ file: string;
17
+ lines: string;
18
+ reason: string;
19
+ risk: "safe" | "confirm" | "review";
20
+ };
2
21
 
3
- const CUSTOM_TYPE = "simplify-context";
4
- const DELIVERY_FOLLOW_UP = "followUp";
5
- const NOTIFY_REVIEW_STARTED = "Simplify review started";
6
- const NOTIFY_REVIEW_QUEUED = "Simplify review queued as a follow-up";
22
+ const SIMPLIFY_PROMPT = `# Simplify: Clean Up Leftover Code
7
23
 
8
- const SIMPLIFY_PROMPT = `# Simplify: Code Review and Cleanup
24
+ You are a code cleanup assistant. Your job is to identify and remove unnecessary code left over after feature implementation.
9
25
 
10
- Review all changed files for reuse, quality, and efficiency. Fix any issues found.
26
+ ## What to Find
11
27
 
12
- ## Phase 1: Identify Changes
28
+ ### 1. Dead Code (Safe to Delete)
29
+ - **Unused exports**: Functions/classes defined but never imported elsewhere
30
+ - **Orphan files**: Files created but never referenced
31
+ - **Zombie variables**: Variables assigned but never used
32
+ - **Empty blocks**: try/catch/if blocks with no logic
13
33
 
14
- Run \`git diff\` (or \`git diff HEAD\` if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation.
34
+ ### 2. Debug Remnants (Safe to Delete)
35
+ - console.log, console.warn, console.error statements
36
+ - debugger statements
37
+ - Temporary feature flags (e.g., \`ENABLE_DEBUG\`, \`DEBUG_MODE\`)
38
+ - Temporary todo comments that are now implemented
15
39
 
16
- ## Phase 2: Launch Three Review SubAgents in Parallel
40
+ ### 3. Commented-out Code (Review Before Deleting)
41
+ - Old logic left in comments
42
+ - Disabled features (commented out rather than deleted)
43
+ - Copy-pasted templates never customized
17
44
 
18
- Use the Agent tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context.
45
+ ### 4. Over-engineering (Confirm Before Deleting)
46
+ - Abstractions created "for future use" but never used
47
+ - Helper functions with single call sites (could be inlined)
48
+ - Layers of indirection that add no value
19
49
 
20
- ### SubAgent 1: Code Reuse Review
50
+ ### 5. Duplicate Logic (Confirm Before Deleting)
51
+ - Repeated if-else blocks doing the same thing
52
+ - Copy-paste code with minor variations
53
+ - Duplicate utility functions
21
54
 
22
- For each change:
55
+ ## How to Analyze
23
56
 
24
- 1. **Search for existing utilities and helpers** that could replace newly written code. Look for similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones.
25
- 2. **Flag any new function that duplicates existing functionality.** Suggest the existing function to use instead.
26
- 3. **Flag any inline logic that could use an existing utility** — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates.
57
+ 1. Run \`git diff\` to see what changed
58
+ 2. For each change, determine if it's:
59
+ - **Essential**: Required for the feature to work
60
+ - **Residual**: Left over from development/debugging
61
+ - **Legacy**: Old code not touched by this change
27
62
 
28
- ### SubAgent 2: Code Quality Review
63
+ 3. For each residual item:
64
+ - Identify exact file and line(s)
65
+ - Assess risk level
66
+ - Provide clear reason for removal
29
67
 
30
- Review the same changes for hacky patterns:
68
+ ## Risk Levels
31
69
 
32
- 1. **Redundant state**: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls
33
- 2. **Parameter sprawl**: adding new parameters to a function instead of generalizing or restructuring existing ones
34
- 3. **Copy-paste with slight variation**: near-duplicate code blocks that should be unified with a shared abstraction
35
- 4. **Leaky abstractions**: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries
36
- 5. **Stringly-typed code**: using raw strings where constants, enums (string unions), or branded types already exist in the codebase
37
- 6. **Unnecessary JSX nesting**: wrapper Boxes/elements that add no layout value — check if inner component props (flexShrink, alignItems, etc.) already provide the needed behavior
38
- 7. **Unnecessary comments**: comments explaining WHAT the code does (well-named identifiers already do that), narrating the change, or referencing the task/caller — delete; keep only non-obvious WHY (hidden constraints, subtle invariants, workarounds)
70
+ - **safe**: Definitely can be deleted (unused, debug code)
71
+ - **confirm**: Delete after user confirms (over-engineered, duplicates)
72
+ - **review**: User should review before action (commented code, ambiguous)
39
73
 
40
- ### SubAgent 3: Efficiency Review
74
+ ## Rules
41
75
 
42
- Review the same changes for efficiency:
76
+ 1. When in doubt, mark as "confirm" or "review" - don't delete without consent
77
+ 2. For inline candidates, show the alternative
78
+ 3. Don't flag necessary code just because it's simple
79
+ 4. Respect existing abstraction boundaries
80
+ 5. Be especially careful with:
81
+ - Error handling code
82
+ - Security-related logic
83
+ - Code that looks "unused" but is called via reflection/eval
84
+ - Database migration files
43
85
 
44
- 1. **Unnecessary work**: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns
45
- 2. **Missed concurrency**: independent operations run sequentially when they could run in parallel
46
- 3. **Hot-path bloat**: new blocking work added to startup or per-request/per-render hot paths
47
- 4. **Recurring no-op updates**: state/store updates inside polling loops, intervals, or event handlers that fire unconditionally — add a change-detection guard so downstream consumers aren't notified when nothing changed. Also: if a wrapper function takes an updater/reducer callback, verify it honors same-reference returns (or whatever the "no change" signal is) — otherwise callers' early-return no-ops are silently defeated
48
- 5. **Unnecessary existence checks**: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error
49
- 6. **Memory**: unbounded data structures, missing cleanup, event listener leaks
50
- 7. **Overly broad operations**: reading entire files when only a portion is needed, loading all items when filtering for one
86
+ ## Output Format (REQUIRED)
51
87
 
52
- ## Phase 3: Fix Issues
88
+ You may write prose analysis first, but you MUST end your response with a single fenced JSON block containing ALL candidates. This JSON is parsed programmatically — it must be valid JSON and use this exact shape:
53
89
 
54
- Wait for all three agents to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on — do not argue with the finding, just skip it.
90
+ \`\`\`json
91
+ {
92
+ "candidates": [
93
+ {
94
+ "risk": "safe",
95
+ "file": "path/to/file.ext",
96
+ "lines": "12-15",
97
+ "reason": "Why this should be removed",
98
+ "action": "delete"
99
+ }
100
+ ]
101
+ }
102
+ \`\`\`
55
103
 
56
- When done, briefly summarize what was fixed (or confirm the code was already clean).
104
+ Field notes:
105
+ - \`risk\` — one of: "safe", "confirm", "review"
106
+ - \`file\` — repository-relative path, no backticks, no markdown
107
+ - \`lines\` — line number or range ("42" or "42-57"); empty string if unknown
108
+ - \`reason\` — single plain-text sentence
109
+ - \`action\` — one of: "delete", "inline", "confirm" (appended to reason)
110
+
111
+ If there are no candidates, output \`{"candidates": []}\`. Do NOT output anything after the closing \`\`\` fence.
57
112
  `;
58
113
 
59
- function buildPrompt(args: string): string {
60
- const focus = args.trim();
61
- if (!focus) return SIMPLIFY_PROMPT;
62
- return `${SIMPLIFY_PROMPT}\n\n## Additional Focus\n\n${focus}`;
63
- }
114
+ export default function simplifyExtension(pi: ExtensionAPI) {
115
+ // Accumulate assistant text across the whole turn (multiple messages when
116
+ // the AI makes tool calls). Overwriting would drop the JSON block if it
117
+ // appears in an earlier message and a later one adds a short confirmation.
118
+ let assistantTextBuffer = "";
119
+ let resolvePendingTurnStart: (() => void) | null = null;
64
120
 
65
- function runSimplify(pi: ExtensionAPI, ctx: ExtensionCommandContext, args: string): void {
66
- const message = {
67
- customType: CUSTOM_TYPE,
68
- content: buildPrompt(args),
69
- display: false,
70
- };
71
-
72
- if (ctx.isIdle()) {
73
- pi.sendMessage(message, { triggerTurn: true });
74
- ctx.ui.notify(NOTIFY_REVIEW_STARTED, "info");
75
- return;
76
- }
77
-
78
- pi.sendMessage(message, { deliverAs: DELIVERY_FOLLOW_UP, triggerTurn: true });
79
- ctx.ui.notify(NOTIFY_REVIEW_QUEUED, "info");
80
- }
121
+ pi.on("turn_start", () => {
122
+ if (!resolvePendingTurnStart) return;
123
+ const resolve = resolvePendingTurnStart;
124
+ resolvePendingTurnStart = null;
125
+ resolve();
126
+ });
127
+
128
+ pi.on("message_end", (event) => {
129
+ const msg = event.message;
130
+ if (msg.role !== "assistant" || !Array.isArray(msg.content)) return;
131
+ const text = (msg.content as { type: string; text?: string }[])
132
+ .filter((b) => b.type === "text" && typeof b.text === "string")
133
+ .map((b) => b.text as string)
134
+ .join("\n");
135
+ if (text) assistantTextBuffer += (assistantTextBuffer ? "\n" : "") + text;
136
+ });
137
+
138
+ const RISK_VALUES = new Set(["safe", "confirm", "review"]);
139
+
140
+ function normalizeRisk(value: unknown): "safe" | "confirm" | "review" {
141
+ const v = String(value ?? "")
142
+ .toLowerCase()
143
+ .trim();
144
+ return RISK_VALUES.has(v) ? (v as "safe" | "confirm" | "review") : "review";
145
+ }
146
+
147
+ function stripMarkdown(text: string): string {
148
+ return text.replace(/[`*_]/g, "").trim();
149
+ }
150
+
151
+ /**
152
+ * Try to parse a JSON candidates block. The prompt requires this format,
153
+ * but we tolerate the AI wrapping it in ```json ... ``` or ``` ... ```,
154
+ * and also handle the case where it embeds the JSON inline without fences.
155
+ * Returns null only when no valid JSON with a `candidates` array is found —
156
+ * a valid empty list returns [] (which means "the AI found nothing").
157
+ */
158
+ function parseCandidatesJSON(response: string): SimplifyResult[] | null {
159
+ const fenceRe = /```(?:json)?\s*\n([\s\S]*?)\n```/gi;
160
+ const blocks: string[] = [];
161
+ let m: RegExpExecArray | null;
162
+ while ((m = fenceRe.exec(response)) !== null) blocks.push(m[1]);
163
+
164
+ const bareMatch = response.match(/\{[\s\S]*"candidates"[\s\S]*\}/);
165
+ if (bareMatch) blocks.push(bareMatch[0]);
166
+
167
+ // Walk newest-first: the contract puts the JSON at the end of the response.
168
+ for (let i = blocks.length - 1; i >= 0; i--) {
169
+ try {
170
+ const parsed = JSON.parse(blocks[i]);
171
+ const list = parsed?.candidates;
172
+ if (!Array.isArray(list)) continue;
173
+ const out: SimplifyResult[] = [];
174
+ for (const item of list) {
175
+ if (!item || typeof item !== "object") continue;
176
+ const file = stripMarkdown(String(item.file ?? item.location ?? ""));
177
+ // Validate path is within repo (no path traversal)
178
+ if (!file || file.includes("..") || file.startsWith("/")) continue;
179
+ const reason = stripMarkdown(String(item.reason ?? item.description ?? ""));
180
+ const action = item.action ? ` [${stripMarkdown(String(item.action))}]` : "";
181
+ out.push({
182
+ file,
183
+ lines: stripMarkdown(String(item.lines ?? "")),
184
+ reason: reason ? reason + action : action.trim() || "(no reason provided)",
185
+ risk: normalizeRisk(item.risk),
186
+ });
187
+ }
188
+ // A valid candidates array (even empty) is a successful parse
189
+ return out;
190
+ } catch {
191
+ // try next block
192
+ }
193
+ }
194
+ return null;
195
+ }
196
+
197
+ /**
198
+ * Show selection dialog for candidates with proper multi-select support
199
+ */
200
+ async function showCandidateSelector(
201
+ ctx: ExtensionCommandContext,
202
+ candidates: SimplifyResult[],
203
+ ): Promise<SimplifyResult[]> {
204
+ if (candidates.length === 0) {
205
+ return [];
206
+ }
207
+
208
+ // Categorize by risk level for display
209
+ const safeCandidates = candidates.filter((c) => c.risk === "safe");
210
+ const confirmCandidates = candidates.filter((c) => c.risk === "confirm");
211
+ const reviewCandidates = candidates.filter((c) => c.risk === "review");
212
+
213
+ const RISK_CONFIG = {
214
+ safe: { label: "Safe to delete", description: "Will be deleted", selected: true },
215
+ confirm: { label: "Needs confirmation", description: "Select to delete", selected: false },
216
+ review: { label: "Needs review", description: "Review before deleting", selected: false },
217
+ } as const;
218
+
219
+ const sections = [
220
+ { key: "safe" as const, items: safeCandidates },
221
+ { key: "confirm" as const, items: confirmCandidates },
222
+ { key: "review" as const, items: reviewCandidates },
223
+ ]
224
+ .map(({ key, items }) => ({ key, items, config: RISK_CONFIG[key], total: items.length }))
225
+ .filter((s) => s.total > 0);
226
+
227
+ const displayItems: SelectItem[] = [];
228
+ const selectableItems: { index: number; candidate: SimplifyResult }[] = [];
229
+ let globalIndex = 0;
230
+
231
+ for (const section of sections) {
232
+ displayItems.push({
233
+ value: `__section__${section.key}__`,
234
+ label: `── ${section.config.label} (${section.total}) ──`,
235
+ description: "",
236
+ });
237
+ globalIndex++;
238
+ for (const c of section.items) {
239
+ displayItems.push({
240
+ value: JSON.stringify(c),
241
+ label: `${c.file} - ${c.reason}`,
242
+ description: section.config.description,
243
+ });
244
+ selectableItems.push({ index: globalIndex++, candidate: c });
245
+ }
246
+ }
247
+
248
+ // Pre-select all safe items
249
+ const selectedSet = new Set<number>(
250
+ safeCandidates.length > 0 ? Array.from({ length: safeCandidates.length }, (_, i) => i) : [],
251
+ );
252
+
253
+ const maxVisible = 12;
254
+ let scrollOffset = 0;
255
+ let cursorPos = 0;
256
+
257
+ const result = await ctx.ui.custom<SimplifyResult[]>((tui, theme, _keybindings, done) => {
258
+ // Render the multi-select list manually
259
+ const renderList = (width: number): string[] => {
260
+ const lines: string[] = [];
261
+
262
+ // Calculate which items are visible
263
+ const visibleItems: { selectableIdx: number | null; item: SelectItem }[] = [];
264
+ for (let i = 0; i < displayItems.length; i++) {
265
+ const item = displayItems[i];
266
+ if (item.value.startsWith("__section__")) {
267
+ visibleItems.push({ selectableIdx: null, item });
268
+ } else {
269
+ const selectableIdx = selectableItems.findIndex((si) => si.index === i);
270
+ if (selectableIdx >= 0) {
271
+ visibleItems.push({ selectableIdx, item: displayItems[i] });
272
+ }
273
+ }
274
+ }
275
+
276
+ // Show visible range with scroll
277
+ const startIdx = Math.max(0, scrollOffset);
278
+ const endIdx = Math.min(visibleItems.length, startIdx + maxVisible);
279
+
280
+ for (let vIdx = startIdx; vIdx < endIdx; vIdx++) {
281
+ const { selectableIdx, item } = visibleItems[vIdx];
282
+
283
+ if (item.value.startsWith("__section__")) {
284
+ // Section header
285
+ lines.push(theme.fg("accent", item.label));
286
+ } else {
287
+ // Selectable item
288
+ const isCursor = selectableIdx === cursorPos;
289
+ const isSelected = selectableIdx !== null && selectedSet.has(selectableIdx);
290
+ const prefix = isCursor ? theme.fg("accent", "> ") : " ";
291
+ const checkbox = isSelected ? theme.fg("success", "[x]") : theme.fg("dim", "[ ]");
292
+ const truncatedLabel = truncateToWidth(item.label, width - 6);
293
+ const line = `${prefix}${checkbox} ${truncatedLabel}`;
294
+ lines.push(isCursor ? theme.fg("accent", line) : line);
295
+ }
296
+ }
297
+
298
+ // Scroll indicator
299
+ if (visibleItems.length > maxVisible) {
300
+ const scrollInfo = ` (${startIdx + 1}-${endIdx}/${visibleItems.length})`;
301
+ lines.push(theme.fg("dim", scrollInfo));
302
+ }
303
+
304
+ return lines;
305
+ };
306
+
307
+ return {
308
+ render(width: number) {
309
+ const lines: string[] = [];
310
+ lines.push(theme.bold("Simplify: Select items to remove"));
311
+ lines.push(
312
+ theme.fg(
313
+ "muted",
314
+ `Found ${candidates.length} candidates (${safeCandidates.length} safe, ${confirmCandidates.length} confirm, ${reviewCandidates.length} review)`,
315
+ ),
316
+ );
317
+ lines.push("");
318
+ lines.push(...renderList(width));
319
+ lines.push("");
320
+ lines.push(
321
+ theme.fg(
322
+ "muted",
323
+ `Selected: ${selectedSet.size} • ↑↓ navigate • space toggle • a select all • enter confirm • esc cancel`,
324
+ ),
325
+ );
326
+ return lines;
327
+ },
328
+ invalidate() {},
329
+ handleInput(data: string) {
330
+ if (matchesKey(data, Key.enter)) {
331
+ const results = Array.from(selectedSet).map((i) => selectableItems[i].candidate);
332
+ done(results);
333
+ return;
334
+ }
335
+ if (matchesKey(data, Key.escape)) {
336
+ done([]);
337
+ return;
338
+ }
339
+ if (matchesKey(data, Key.space)) {
340
+ // Toggle current selection
341
+ if (selectedSet.has(cursorPos)) {
342
+ selectedSet.delete(cursorPos);
343
+ } else {
344
+ selectedSet.add(cursorPos);
345
+ }
346
+ tui.requestRender();
347
+ return;
348
+ }
349
+ if (matchesKey(data, "a")) {
350
+ // Select/deselect all
351
+ if (selectedSet.size === selectableItems.length) {
352
+ selectedSet.clear();
353
+ } else {
354
+ for (let i = 0; i < selectableItems.length; i++) {
355
+ selectedSet.add(i);
356
+ }
357
+ }
358
+ tui.requestRender();
359
+ return;
360
+ }
361
+
362
+ // Navigation
363
+ if (matchesKey(data, Key.down)) {
364
+ cursorPos = Math.min(selectableItems.length - 1, cursorPos + 1);
365
+ // Ensure cursor is within visible window
366
+ const displayIdx = selectableItems[cursorPos].index;
367
+ if (displayIdx >= scrollOffset + maxVisible) {
368
+ scrollOffset = displayIdx - maxVisible + 1;
369
+ }
370
+ tui.requestRender();
371
+ return;
372
+ }
373
+ if (matchesKey(data, Key.up)) {
374
+ cursorPos = Math.max(0, cursorPos - 1);
375
+ // Ensure cursor is within visible window
376
+ const displayIdx = selectableItems[cursorPos].index;
377
+ if (displayIdx < scrollOffset) {
378
+ // Scroll up to show the item, and include section header if it's just above
379
+ scrollOffset = Math.max(0, displayIdx - 1);
380
+ }
381
+ tui.requestRender();
382
+ return;
383
+ }
384
+ if (matchesKey(data, Key.home)) {
385
+ cursorPos = 0;
386
+ scrollOffset = 0;
387
+ tui.requestRender();
388
+ return;
389
+ }
390
+ if (matchesKey(data, Key.end)) {
391
+ cursorPos = selectableItems.length - 1;
392
+ const lastDisplayIdx = selectableItems[cursorPos].index;
393
+ scrollOffset = Math.max(0, lastDisplayIdx - maxVisible + 1);
394
+ tui.requestRender();
395
+ return;
396
+ }
397
+ },
398
+ };
399
+ });
400
+
401
+ return result ?? [];
402
+ }
403
+
404
+ /**
405
+ * Execute the cleanup by sending deletion commands
406
+ */
407
+ async function executeCleanup(
408
+ ctx: ExtensionCommandContext,
409
+ selected: SimplifyResult[],
410
+ ): Promise<void> {
411
+ if (selected.length === 0) {
412
+ ctx.ui.notify("No items selected for cleanup", "info");
413
+ return;
414
+ }
415
+
416
+ const safeItems = selected.filter((c) => c.risk === "safe");
417
+ const confirmItems = selected.filter((c) => c.risk === "confirm");
418
+
419
+ // Build cleanup prompt with verification step
420
+ const cleanupPrompt = `# Cleanup Instructions
421
+
422
+ Delete the following code:
423
+
424
+ ${selected.map((c) => `- ${c.file}: ${c.reason}`).join("\n")}
425
+
426
+ For each item:
427
+ 1. Read the file to find the exact location
428
+ 2. Remove only the specified code (not surrounding code unless instructed)
429
+ 3. If the removal affects other code, stop and report the issue
430
+ 4. After all deletions, verify the code still works by running any existing tests
431
+
432
+ IMPORTANT: After completing deletions:
433
+ - Run \`npm test\` or equivalent test command
434
+ - If tests fail, report which tests failed and whether it's related to the cleanup
435
+ - If there are no tests, at least verify the files parse correctly (e.g., \`node --check\`)
436
+
437
+ Report:
438
+ - What was deleted
439
+ - Test results (pass/fail)
440
+ - Any issues encountered
441
+ - Files that may need further attention`;
442
+
443
+ ctx.ui.notify(
444
+ `Starting cleanup of ${selected.length} items (${safeItems.length} safe, ${confirmItems.length} confirmed)`,
445
+ "info",
446
+ );
447
+
448
+ pi.sendUserMessage(cleanupPrompt);
449
+ }
450
+
451
+ /**
452
+ * Main command handler
453
+ */
454
+ pi.registerCommand("simplify", {
455
+ description: "Clean up leftover code (dead code, debug remnants, over-engineering)",
456
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
457
+ if (!ctx.hasUI) {
458
+ ctx.ui.notify("Simplify requires interactive mode", "error");
459
+ return;
460
+ }
461
+
462
+ if (!ctx.isIdle()) {
463
+ ctx.ui.notify(
464
+ "Cannot run simplify while agent is busy. Wait for current task to complete.",
465
+ "warning",
466
+ );
467
+ return;
468
+ }
469
+
470
+ // Check if in git repo
471
+ const { code } = await pi.exec("git", ["rev-parse", "--git-dir"]);
472
+ if (code !== 0) {
473
+ ctx.ui.notify("Not a git repository", "error");
474
+ return;
475
+ }
476
+
477
+ // Check if there are changes
478
+ const { stdout: gitStatus } = await pi.exec("git", ["status", "--porcelain"]);
479
+ if (!gitStatus.trim()) {
480
+ ctx.ui.notify("No git changes found. Simplify reviews uncommitted changes.", "info");
481
+ return;
482
+ }
483
+
484
+ ctx.ui.notify("Analyzing code for cleanup candidates...", "info");
485
+
486
+ // Build prompt with optional focus
487
+ let fullPrompt = SIMPLIFY_PROMPT;
488
+ if (args.trim()) {
489
+ fullPrompt += `\n\n## Additional Focus\n\n${args.trim()}`;
490
+ }
491
+
492
+ // Reset capture buffer, then send prompt and wait.
493
+ // message_end events append to assistantTextBuffer during the turn.
494
+ //
495
+ // Wait for the queued analysis turn to actually begin before waiting for
496
+ // idle; otherwise waitForIdle() can return immediately while the agent is
497
+ // still idle and the queued prompt has not started yet.
498
+ assistantTextBuffer = "";
499
+ const turnStarted = new Promise<void>((r) => {
500
+ resolvePendingTurnStart = r;
501
+ });
502
+
503
+ pi.sendUserMessage(fullPrompt);
504
+
505
+ const started = await Promise.race<boolean>([
506
+ turnStarted.then(() => true),
507
+ new Promise<boolean>((r) => setTimeout(() => r(false), 10000)),
508
+ ]);
509
+ if (!started) {
510
+ resolvePendingTurnStart = null;
511
+ ctx.ui.notify("Analysis did not start within 10 seconds. Please try again.", "warning");
512
+ return;
513
+ }
514
+
515
+ await ctx.waitForIdle();
516
+ const analysisText = assistantTextBuffer;
517
+
518
+ if (!analysisText) {
519
+ ctx.ui.notify("Could not read analysis — no response captured.", "error");
520
+ return;
521
+ }
522
+
523
+ const candidates = parseCandidatesJSON(analysisText);
524
+
525
+ if (candidates === null) {
526
+ ctx.ui.notify(
527
+ "Could not parse cleanup candidates — the model did not return the expected JSON block.",
528
+ "warning",
529
+ );
530
+ return;
531
+ }
532
+
533
+ if (candidates.length === 0) {
534
+ ctx.ui.notify("No cleanup candidates found!", "info");
535
+ return;
536
+ }
537
+
538
+ ctx.ui.notify(`Found ${candidates.length} candidates. Select items to remove...`, "info");
539
+
540
+ // Show selector
541
+ const selected = await showCandidateSelector(ctx, candidates);
542
+
543
+ if (!selected || selected.length === 0) {
544
+ ctx.ui.notify("Cleanup cancelled", "info");
545
+ return;
546
+ }
547
+
548
+ // Execute cleanup
549
+ await executeCleanup(ctx, selected);
550
+ },
551
+ });
552
+
553
+ /**
554
+ * Quick simplify - auto-clean safe items only
555
+ */
556
+ pi.registerCommand("simplify-quick", {
557
+ description: "Quick cleanup of obviously safe items (debug code, unused exports)",
558
+ handler: async (_args: string, ctx: ExtensionCommandContext) => {
559
+ if (!ctx.hasUI) {
560
+ ctx.ui.notify("Simplify requires interactive mode", "error");
561
+ return;
562
+ }
563
+
564
+ if (!ctx.isIdle()) {
565
+ ctx.ui.notify("Agent is busy. Try again after current task.", "warning");
566
+ return;
567
+ }
568
+
569
+ const quickPrompt = `# Quick Cleanup
570
+
571
+ Find and delete ONLY the most obviously safe cleanup items:
572
+
573
+ 1. \`console.log\`, \`console.warn\`, \`console.error\` statements
574
+ 2. \`debugger\` statements
575
+ 3. Unused \`import\` statements (imported but never used)
576
+ 4. Empty \`catch\` blocks (just \`catch (e) {}\`)
577
+ 5. Unused \`const\`/\`let\`/\`var\` declarations
578
+
579
+ DO NOT delete:
580
+ - Commented-out code
581
+ - Over-engineered abstractions
582
+ - Duplicate logic
583
+ - Anything that might be needed
584
+
585
+ For each item found:
586
+ 1. Confirm it's truly unused by searching for references
587
+ 2. Delete only the specific lines
588
+ 3. Report what was deleted
589
+
590
+ Return a summary of what was deleted.`;
591
+
592
+ ctx.ui.notify("Running quick cleanup...", "info");
593
+ pi.sendUserMessage(quickPrompt, { deliverAs: "followUp" });
594
+ },
595
+ });
81
596
 
82
- export default function simplifyExtension(pi: ExtensionAPI): void {
83
- pi.registerCommand("simplify", {
84
- description: "Review changed code for reuse, quality, and efficiency, then fix issues",
85
- handler: async (args: string, ctx: ExtensionCommandContext) => {
86
- runSimplify(pi, ctx, args);
87
- },
88
- });
597
+ /**
598
+ * Status indicator on startup
599
+ */
600
+ /**pi.on("session_start", async (_event, ctx) => {
601
+ const { code } = await pi.exec("git", ["rev-parse", "--git-dir"]);
602
+ if (code === 0) {
603
+ ctx.ui.setStatus(
604
+ "simplify",
605
+ `${ctx.ui.theme.fg("accent", "simplify")} ${ctx.ui.theme.fg("muted", "ready (try /simplify)")}`,
606
+ );
607
+ }
608
+ });
609
+ */
89
610
  }
package/package.json CHANGED
@@ -1,23 +1,34 @@
1
1
  {
2
- "name": "@geminixiang/pi-simplify",
3
- "version": "0.0.3",
4
- "description": "Simplify: code reuse, quality, and efficiency review for pi coding agent",
5
- "main": "index.ts",
6
- "keywords": [
7
- "pi-package"
8
- ],
9
- "author": "geminixiang",
10
- "repository": {
11
- "type": "git",
12
- "url": "https://github.com/geminixiang/pi-simplify"
13
- },
14
- "license": "MIT",
15
- "pi": {
16
- "extensions": [
17
- "./index.ts"
18
- ]
19
- },
20
- "dependencies": {
21
- "@mariozechner/pi-coding-agent": "^0.65.2"
22
- }
2
+ "name": "@geminixiang/pi-simplify",
3
+ "version": "0.0.5",
4
+ "description": "Simplify: Clean up leftover code after feature implementation",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "license": "MIT",
9
+ "author": "geminixiang",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/geminixiang/pi-simplify"
13
+ },
14
+ "main": "index.ts",
15
+ "scripts": {
16
+ "lint": "oxlint",
17
+ "lint:fix": "oxlint --fix",
18
+ "fmt": "oxfmt",
19
+ "fmt:check": "oxfmt --check"
20
+ },
21
+ "dependencies": {
22
+ "@mariozechner/pi-coding-agent": "^0.65.2"
23
+ },
24
+ "devDependencies": {
25
+ "oxfmt": "^0.45.0",
26
+ "oxlint": "^1.60.0",
27
+ "typescript": "^6.0.2"
28
+ },
29
+ "pi": {
30
+ "extensions": [
31
+ "./index.ts"
32
+ ]
33
+ }
23
34
  }
package/tsconfig.json ADDED
@@ -0,0 +1,11 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "esModuleInterop": true,
8
+ "skipLibCheck": true,
9
+ "outDir": "dist"
10
+ }
11
+ }