@geminixiang/pi-simplify 0.0.6 → 0.0.7
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.
- package/.pi/skills/release/SKILL.md +146 -0
- package/CHANGELOG.md +24 -0
- package/README.md +0 -15
- package/index.ts +3 -595
- package/package.json +4 -2
- package/prompt.ts +93 -0
- package/selector.ts +176 -0
- package/types.ts +12 -0
- package/workflow.ts +257 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: release
|
|
3
|
+
description: Prepare and publish a new pi-simplify release. Use when bumping the version, committing and pushing it, and creating a GitHub release in the style of earlier pi-simplify releases.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# pi-simplify Release
|
|
7
|
+
|
|
8
|
+
Repo defaults:
|
|
9
|
+
|
|
10
|
+
- branch: `main`
|
|
11
|
+
- remote: `origin`
|
|
12
|
+
- repo: `geminixiang/pi-simplify`
|
|
13
|
+
- npm package: `@geminixiang/pi-simplify`
|
|
14
|
+
- use `package.json` version as the git tag and GitHub release title
|
|
15
|
+
- versions with `-alpha.`, `-beta.`, or `-rc.` are prereleases by default
|
|
16
|
+
|
|
17
|
+
## Version rules
|
|
18
|
+
|
|
19
|
+
Examples:
|
|
20
|
+
|
|
21
|
+
- stable: `0.2.1`, `0.3.0`, `1.0.0`
|
|
22
|
+
- prerelease: `0.2.0-beta.8`, `0.3.0-rc.1`, `1.0.0-alpha.2`
|
|
23
|
+
|
|
24
|
+
Guidance:
|
|
25
|
+
|
|
26
|
+
- `patch` = bugfix / small maintenance
|
|
27
|
+
- `minor` = backward-compatible features
|
|
28
|
+
- `major` = breaking changes
|
|
29
|
+
- prerelease numbers increase within the same line, e.g. `beta.8 -> beta.9`
|
|
30
|
+
- promote prerelease to stable by dropping the suffix, e.g. `0.2.0-beta.8 -> 0.2.0`
|
|
31
|
+
|
|
32
|
+
## Flow
|
|
33
|
+
|
|
34
|
+
### 1. Check state
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
git status --short
|
|
38
|
+
git branch --show-current
|
|
39
|
+
git remote -v
|
|
40
|
+
git tag --list | tail -20
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Read `package.json` and `package-lock.json`. If unrelated files are modified, ask before committing.
|
|
44
|
+
|
|
45
|
+
### 2. Sync version files
|
|
46
|
+
|
|
47
|
+
Preferred:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm version <version> --no-git-tag-version
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Use this to sync `package.json` and `package-lock.json` without creating an automatic commit or tag. If the user already edited `package.json`, just verify `package-lock.json` matches.
|
|
54
|
+
|
|
55
|
+
### 3. Update CHANGELOG
|
|
56
|
+
|
|
57
|
+
`CHANGELOG.md` follows Keep a Changelog with `### Added / Changed / Fixed / Removed / Security / Performance / Tests` subsections. The newest release sits at the top under an `## [Unreleased]` placeholder.
|
|
58
|
+
|
|
59
|
+
Gather user-visible changes since the previous tag:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
git log --pretty=format:'%h %s' <previous-tag>..HEAD | grep -v "^[a-f0-9]* chore: bump version"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Then in `CHANGELOG.md`:
|
|
66
|
+
|
|
67
|
+
- Keep `## [Unreleased]` at the top as an empty placeholder.
|
|
68
|
+
- Insert a new section `## [<version>] - <YYYY-MM-DD>` (use today's date for stable, omit the date for prereleases to match the existing style).
|
|
69
|
+
- Group entries by subsection; one bullet per user-visible change, imperative voice, no commit hashes.
|
|
70
|
+
- Skip pure internal refactors that don't change behavior unless they affect contributors (then list under `### Changed`).
|
|
71
|
+
|
|
72
|
+
If you generated draft release notes in step 5 first, copy the same wording into CHANGELOG — they should match.
|
|
73
|
+
|
|
74
|
+
### 4. Commit and push
|
|
75
|
+
|
|
76
|
+
Stage version files and CHANGELOG together — the bump and the changelog entry belong in the same commit.
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
git add package.json package-lock.json CHANGELOG.md
|
|
80
|
+
git commit -m "chore: bump version to <version>"
|
|
81
|
+
git push origin main
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### 5. Draft release notes
|
|
85
|
+
|
|
86
|
+
Use the previous GitHub release as the style reference.
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
gh release list --repo geminixiang/pi-simplify --limit 10
|
|
90
|
+
gh release view <previous-tag> --repo geminixiang/pi-simplify --json tagName,name,body,url,publishedAt
|
|
91
|
+
git log --pretty=format:'%h %s' <previous-tag>..HEAD
|
|
92
|
+
git diff --stat <previous-tag>..HEAD
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Write concise notes focused on user-visible changes, usually with:
|
|
96
|
+
|
|
97
|
+
- `## What's changed`
|
|
98
|
+
- `### Highlights`
|
|
99
|
+
- `### Notable changes`
|
|
100
|
+
- `### Docs and maintenance`
|
|
101
|
+
- `### Verification`
|
|
102
|
+
|
|
103
|
+
Write notes to `/tmp/pi-simplify-release-<version>.md`. Keep them consistent with the CHANGELOG entry from step 3.
|
|
104
|
+
|
|
105
|
+
### 6. Create or update release
|
|
106
|
+
|
|
107
|
+
Prerelease:
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
gh release create <version> \
|
|
111
|
+
--repo geminixiang/pi-simplify \
|
|
112
|
+
--target main \
|
|
113
|
+
--title <version> \
|
|
114
|
+
--notes-file /tmp/pi-simplify-release-<version>.md \
|
|
115
|
+
--prerelease
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Stable:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
gh release create <version> \
|
|
122
|
+
--repo geminixiang/pi-simplify \
|
|
123
|
+
--target main \
|
|
124
|
+
--title <version> \
|
|
125
|
+
--notes-file /tmp/pi-simplify-release-<version>.md
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
If it already exists, use `gh release edit <version> ...` and keep prerelease/stable intent consistent.
|
|
129
|
+
|
|
130
|
+
## Report back
|
|
131
|
+
|
|
132
|
+
Return:
|
|
133
|
+
|
|
134
|
+
- released version
|
|
135
|
+
- stable or prerelease
|
|
136
|
+
- version-bump commit hash
|
|
137
|
+
- push status
|
|
138
|
+
- release URL
|
|
139
|
+
|
|
140
|
+
## Guardrails
|
|
141
|
+
|
|
142
|
+
- Always use `geminixiang/pi-simplify`.
|
|
143
|
+
- Infer stable vs prerelease from the version, or ask.
|
|
144
|
+
- Do not include raw commit hashes in release notes unless requested.
|
|
145
|
+
- If hooks fail during commit, fix or report before retrying.
|
|
146
|
+
- Never publish a release without a corresponding CHANGELOG entry — the version bump commit must include the new CHANGELOG section.
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.0.7] - 2026-05-25
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
|
|
13
|
+
- Use pi's native select list for findings selection.
|
|
14
|
+
- Wrap long finding recommendations in the selection menu.
|
|
15
|
+
- Split the simplify extension into prompt, selector, workflow, and shared type modules.
|
|
16
|
+
- Update dependencies to the current `@earendil-works` pi packages.
|
|
17
|
+
|
|
18
|
+
### Removed
|
|
19
|
+
|
|
20
|
+
- Remove the `/simplify-quick` command and its documentation.
|
|
21
|
+
|
|
22
|
+
### Added
|
|
23
|
+
|
|
24
|
+
- Add a project release workflow skill for future releases.
|
package/README.md
CHANGED
|
@@ -36,21 +36,6 @@ Analyzes all git changes and presents cleanup candidates:
|
|
|
36
36
|
- **Confirm** (yellow) - delete after user confirms
|
|
37
37
|
- **Review** (orange) - user should review first
|
|
38
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
39
|
### With Focus
|
|
55
40
|
|
|
56
41
|
```
|
package/index.ts
CHANGED
|
@@ -7,602 +7,10 @@
|
|
|
7
7
|
* - Efficiency: redundant work, missed concurrency, hot-path bloat, memory leaks
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import type { ExtensionAPI
|
|
11
|
-
import { matchesKey, Key, truncateToWidth, type SelectItem } from "@mariozechner/pi-tui";
|
|
10
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
12
11
|
|
|
13
|
-
|
|
14
|
-
type Risk = "safe" | "confirm" | "review";
|
|
15
|
-
type Action = "delete" | "inline" | "refactor" | "parallelize";
|
|
16
|
-
|
|
17
|
-
type SimplifyResult = {
|
|
18
|
-
category: Category;
|
|
19
|
-
file: string;
|
|
20
|
-
lines: string;
|
|
21
|
-
reason: string;
|
|
22
|
-
risk: Risk;
|
|
23
|
-
action: Action;
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
const SIMPLIFY_PROMPT = `# Simplify: Review Changed Code for Reuse, Quality, and Efficiency
|
|
27
|
-
|
|
28
|
-
You are a code review assistant. Review the changed code along three axes — **Reuse**, **Quality**, and **Efficiency** — and surface concrete fixes.
|
|
29
|
-
|
|
30
|
-
## What to Find
|
|
31
|
-
|
|
32
|
-
### A. Reuse (Confirm Before Replacing)
|
|
33
|
-
|
|
34
|
-
Before flagging, **search the codebase** (utility directories, shared modules, files adjacent to the change) for existing helpers. Quote the existing symbol you'd use.
|
|
35
|
-
|
|
36
|
-
- **Duplicates an existing function**: a newly written helper does what an existing one already does
|
|
37
|
-
- **Inline logic that has a utility**: hand-rolled string manipulation, manual path handling, custom env checks, ad-hoc type guards
|
|
38
|
-
- **Reinvented framework primitive**: re-implementing something the language/stdlib/framework already provides
|
|
39
|
-
|
|
40
|
-
### B. Quality
|
|
41
|
-
|
|
42
|
-
#### B1. Dead Code (Safe to Delete)
|
|
43
|
-
- Unused exports, orphan files, zombie variables, empty try/catch/if blocks
|
|
44
|
-
|
|
45
|
-
#### B2. Debug Remnants (Safe to Delete)
|
|
46
|
-
- \`console.log\` / \`console.warn\` / \`console.error\`, \`debugger\`, temporary feature flags, stale TODO comments
|
|
47
|
-
|
|
48
|
-
#### B3. Commented-out Code (Review)
|
|
49
|
-
- Old logic left in comments, disabled features, uncustomized templates
|
|
50
|
-
|
|
51
|
-
#### B4. Over-engineering (Confirm)
|
|
52
|
-
- Abstractions created "for future use" but unused, single-call-site helpers that should be inlined, useless indirection
|
|
53
|
-
|
|
54
|
-
#### B5. Hacky Patterns (Confirm)
|
|
55
|
-
- **Redundant state**: state that duplicates other state, cached values that could be derived, observers that could be direct calls
|
|
56
|
-
- **Parameter sprawl**: piling new parameters onto a function instead of restructuring
|
|
57
|
-
- **Copy-paste with variation**: near-duplicate blocks that should share an abstraction
|
|
58
|
-
- **Leaky abstractions**: exposing internals or breaking existing boundaries
|
|
59
|
-
- **Stringly-typed code**: raw strings where an existing constant/enum/union exists
|
|
60
|
-
- **Unnecessary wrapper elements**: JSX/DOM wrappers that add no layout value
|
|
61
|
-
- **Nested conditionals**: ternary chains or if/else nested 3+ levels deep — flatten with early returns or a lookup table
|
|
62
|
-
- **Useless comments**: comments restating WHAT the code does, narrating the change, or referencing the task/caller — keep only non-obvious WHY
|
|
63
|
-
|
|
64
|
-
### C. Efficiency (Confirm)
|
|
65
|
-
|
|
66
|
-
- **Unnecessary work**: redundant computations, repeated file reads, duplicate API calls, N+1 patterns
|
|
67
|
-
- **Missed concurrency**: independent operations run sequentially when they could run in parallel
|
|
68
|
-
- **Hot-path bloat**: blocking work added to startup or per-request/per-render hot paths
|
|
69
|
-
- **Recurring no-op updates**: state writes inside loops/intervals/handlers that fire unconditionally — add a change-detection guard
|
|
70
|
-
- **Unnecessary existence checks**: pre-checking file/resource existence before operating (TOCTOU) — operate directly and handle the error
|
|
71
|
-
- **Memory**: unbounded data structures, missing cleanup, event listener leaks
|
|
72
|
-
- **Overly broad operations**: reading whole files when a slice would do, loading all items when filtering for one
|
|
73
|
-
|
|
74
|
-
## How to Analyze
|
|
75
|
-
|
|
76
|
-
1. Run \`git diff\` to see what changed.
|
|
77
|
-
2. For each change, classify as **Essential** / **Residual** / **Legacy** (don't flag legacy code unless the diff touches it).
|
|
78
|
-
3. For each finding:
|
|
79
|
-
- Identify exact file and line(s)
|
|
80
|
-
- Assign **category** (reuse / quality / efficiency) and **risk**
|
|
81
|
-
- State the concrete fix (which existing utility to call, which lines to delete, how to parallelize, etc.)
|
|
82
|
-
|
|
83
|
-
## Risk Levels
|
|
84
|
-
|
|
85
|
-
- **safe**: Definitely apply (dead code, debug remnants)
|
|
86
|
-
- **confirm**: Apply after user confirms (reuse swaps, over-engineering, hacky patterns, efficiency fixes)
|
|
87
|
-
- **review**: User should look first (commented-out code, ambiguous cases)
|
|
88
|
-
|
|
89
|
-
## Rules
|
|
90
|
-
|
|
91
|
-
1. When in doubt, mark as "confirm" or "review" — don't change without consent.
|
|
92
|
-
2. For reuse findings, name the existing symbol/file you'd swap to.
|
|
93
|
-
3. For efficiency findings, briefly justify the win (e.g., "N+1 → single query", "sequential awaits → Promise.all").
|
|
94
|
-
4. Don't flag necessary code just because it's simple.
|
|
95
|
-
5. Respect existing abstraction boundaries.
|
|
96
|
-
6. Be especially careful with:
|
|
97
|
-
- Error handling code
|
|
98
|
-
- Security-related logic
|
|
99
|
-
- Code that looks "unused" but is called via reflection/eval
|
|
100
|
-
- Database migration files
|
|
101
|
-
|
|
102
|
-
## Output Format (REQUIRED)
|
|
103
|
-
|
|
104
|
-
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:
|
|
105
|
-
|
|
106
|
-
\`\`\`json
|
|
107
|
-
{
|
|
108
|
-
"candidates": [
|
|
109
|
-
{
|
|
110
|
-
"category": "reuse",
|
|
111
|
-
"risk": "confirm",
|
|
112
|
-
"file": "path/to/file.ext",
|
|
113
|
-
"lines": "12-15",
|
|
114
|
-
"reason": "Replace hand-rolled join with existing pathJoin() in src/utils/path.ts",
|
|
115
|
-
"action": "refactor"
|
|
116
|
-
}
|
|
117
|
-
]
|
|
118
|
-
}
|
|
119
|
-
\`\`\`
|
|
120
|
-
|
|
121
|
-
Field notes:
|
|
122
|
-
- \`category\` — one of: "reuse", "quality", "efficiency"
|
|
123
|
-
- \`risk\` — one of: "safe", "confirm", "review"
|
|
124
|
-
- \`file\` — repository-relative path, no backticks, no markdown
|
|
125
|
-
- \`lines\` — line number or range ("42" or "42-57"); empty string if unknown
|
|
126
|
-
- \`reason\` — single plain-text sentence stating the concrete fix
|
|
127
|
-
- \`action\` — one of: "delete", "inline", "refactor", "parallelize"
|
|
128
|
-
|
|
129
|
-
If there are no candidates, output \`{"candidates": []}\`. Do NOT output anything after the closing \`\`\` fence.
|
|
130
|
-
`;
|
|
12
|
+
import { registerSimplifyWorkflow } from "./workflow.js";
|
|
131
13
|
|
|
132
14
|
export default function simplifyExtension(pi: ExtensionAPI) {
|
|
133
|
-
|
|
134
|
-
// the AI makes tool calls). Overwriting would drop the JSON block if it
|
|
135
|
-
// appears in an earlier message and a later one adds a short confirmation.
|
|
136
|
-
let assistantTextBuffer = "";
|
|
137
|
-
let resolvePendingTurnStart: (() => void) | null = null;
|
|
138
|
-
|
|
139
|
-
pi.on("turn_start", () => {
|
|
140
|
-
if (!resolvePendingTurnStart) return;
|
|
141
|
-
const resolve = resolvePendingTurnStart;
|
|
142
|
-
resolvePendingTurnStart = null;
|
|
143
|
-
resolve();
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
pi.on("message_end", (event) => {
|
|
147
|
-
const msg = event.message;
|
|
148
|
-
if (msg.role !== "assistant" || !Array.isArray(msg.content)) return;
|
|
149
|
-
const text = (msg.content as { type: string; text?: string }[])
|
|
150
|
-
.filter((b) => b.type === "text" && typeof b.text === "string")
|
|
151
|
-
.map((b) => b.text as string)
|
|
152
|
-
.join("\n");
|
|
153
|
-
if (text) assistantTextBuffer += (assistantTextBuffer ? "\n" : "") + text;
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
const CATEGORY_VALUES = new Set<Category>(["reuse", "quality", "efficiency"]);
|
|
157
|
-
const RISK_VALUES = new Set<Risk>(["safe", "confirm", "review"]);
|
|
158
|
-
const ACTION_VALUES = new Set<Action>(["delete", "inline", "refactor", "parallelize"]);
|
|
159
|
-
|
|
160
|
-
function normalizeCategory(value: unknown): Category {
|
|
161
|
-
const v = String(value ?? "")
|
|
162
|
-
.toLowerCase()
|
|
163
|
-
.trim();
|
|
164
|
-
return CATEGORY_VALUES.has(v as Category) ? (v as Category) : "quality";
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
function normalizeRisk(value: unknown): Risk {
|
|
168
|
-
const v = String(value ?? "")
|
|
169
|
-
.toLowerCase()
|
|
170
|
-
.trim();
|
|
171
|
-
return RISK_VALUES.has(v as Risk) ? (v as Risk) : "review";
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
function normalizeAction(value: unknown): Action | null {
|
|
175
|
-
const v = String(value ?? "")
|
|
176
|
-
.toLowerCase()
|
|
177
|
-
.trim();
|
|
178
|
-
return ACTION_VALUES.has(v as Action) ? (v as Action) : null;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function stripMarkdown(text: string): string {
|
|
182
|
-
return text.replace(/[`*]/g, "").trim();
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/**
|
|
186
|
-
* Try to parse a JSON candidates block. The prompt requires this format,
|
|
187
|
-
* but we tolerate the AI wrapping it in ```json ... ``` or ``` ... ```,
|
|
188
|
-
* and also handle the case where it embeds the JSON inline without fences.
|
|
189
|
-
* Returns null only when no valid JSON with a `candidates` array is found —
|
|
190
|
-
* a valid empty list returns [] (which means "the AI found nothing").
|
|
191
|
-
*/
|
|
192
|
-
function parseCandidatesJSON(response: string): SimplifyResult[] | null {
|
|
193
|
-
const fenceRe = /```(?:json)?\s*\n([\s\S]*?)\n```/gi;
|
|
194
|
-
const blocks: string[] = [];
|
|
195
|
-
let m: RegExpExecArray | null;
|
|
196
|
-
while ((m = fenceRe.exec(response)) !== null) blocks.push(m[1]);
|
|
197
|
-
|
|
198
|
-
const bareMatch = response.match(/\{[\s\S]*"candidates"[\s\S]*\}/);
|
|
199
|
-
if (bareMatch) blocks.push(bareMatch[0]);
|
|
200
|
-
|
|
201
|
-
// Walk newest-first: the contract puts the JSON at the end of the response.
|
|
202
|
-
for (let i = blocks.length - 1; i >= 0; i--) {
|
|
203
|
-
try {
|
|
204
|
-
const parsed = JSON.parse(blocks[i]);
|
|
205
|
-
const list = parsed?.candidates;
|
|
206
|
-
if (!Array.isArray(list)) continue;
|
|
207
|
-
const out: SimplifyResult[] = [];
|
|
208
|
-
for (const item of list) {
|
|
209
|
-
if (!item || typeof item !== "object") continue;
|
|
210
|
-
const file = stripMarkdown(String(item.file ?? item.location ?? ""));
|
|
211
|
-
// Validate path is within repo (no path traversal)
|
|
212
|
-
if (!file || file.includes("..") || file.startsWith("/")) continue;
|
|
213
|
-
const reason = stripMarkdown(String(item.reason ?? item.description ?? ""));
|
|
214
|
-
const action = normalizeAction(item.action);
|
|
215
|
-
if (!action) continue;
|
|
216
|
-
out.push({
|
|
217
|
-
category: normalizeCategory(item.category),
|
|
218
|
-
file,
|
|
219
|
-
lines: stripMarkdown(String(item.lines ?? "")),
|
|
220
|
-
reason: reason || "(no reason provided)",
|
|
221
|
-
risk: normalizeRisk(item.risk),
|
|
222
|
-
action,
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
// A valid candidates array (even empty) is a successful parse
|
|
226
|
-
return out;
|
|
227
|
-
} catch {
|
|
228
|
-
// try next block
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
return null;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
async function showCandidateSelector(
|
|
235
|
-
ctx: ExtensionCommandContext,
|
|
236
|
-
candidates: SimplifyResult[],
|
|
237
|
-
): Promise<SimplifyResult[]> {
|
|
238
|
-
if (candidates.length === 0) {
|
|
239
|
-
return [];
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// Categorize by risk level for display
|
|
243
|
-
const safeCandidates = candidates.filter((c) => c.risk === "safe");
|
|
244
|
-
const confirmCandidates = candidates.filter((c) => c.risk === "confirm");
|
|
245
|
-
const reviewCandidates = candidates.filter((c) => c.risk === "review");
|
|
246
|
-
|
|
247
|
-
const RISK_CONFIG = {
|
|
248
|
-
safe: { label: "Safe to apply", description: "Will be applied" },
|
|
249
|
-
confirm: { label: "Needs confirmation", description: "Select to apply" },
|
|
250
|
-
review: { label: "Needs review", description: "Review before applying" },
|
|
251
|
-
} as const;
|
|
252
|
-
|
|
253
|
-
const sections = [
|
|
254
|
-
{ key: "safe" as const, items: safeCandidates },
|
|
255
|
-
{ key: "confirm" as const, items: confirmCandidates },
|
|
256
|
-
{ key: "review" as const, items: reviewCandidates },
|
|
257
|
-
]
|
|
258
|
-
.map(({ key, items }) => ({ key, items, config: RISK_CONFIG[key], total: items.length }))
|
|
259
|
-
.filter((s) => s.total > 0);
|
|
260
|
-
|
|
261
|
-
const displayItems: SelectItem[] = [];
|
|
262
|
-
const selectableItems: { index: number; candidate: SimplifyResult }[] = [];
|
|
263
|
-
let globalIndex = 0;
|
|
264
|
-
|
|
265
|
-
for (const section of sections) {
|
|
266
|
-
displayItems.push({
|
|
267
|
-
value: `__section__${section.key}__`,
|
|
268
|
-
label: `── ${section.config.label} (${section.total}) ──`,
|
|
269
|
-
description: "",
|
|
270
|
-
});
|
|
271
|
-
globalIndex++;
|
|
272
|
-
for (const c of section.items) {
|
|
273
|
-
displayItems.push({
|
|
274
|
-
value: JSON.stringify(c),
|
|
275
|
-
label: `${c.file} - ${c.reason}`,
|
|
276
|
-
description: section.config.description,
|
|
277
|
-
});
|
|
278
|
-
selectableItems.push({ index: globalIndex++, candidate: c });
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
// Pre-select all safe items
|
|
283
|
-
const selectedSet = new Set<number>(
|
|
284
|
-
safeCandidates.length > 0 ? Array.from({ length: safeCandidates.length }, (_, i) => i) : [],
|
|
285
|
-
);
|
|
286
|
-
|
|
287
|
-
const maxVisible = 12;
|
|
288
|
-
let scrollOffset = 0;
|
|
289
|
-
let cursorPos = 0;
|
|
290
|
-
|
|
291
|
-
const result = await ctx.ui.custom<SimplifyResult[]>((tui, theme, _keybindings, done) => {
|
|
292
|
-
const renderList = (width: number): string[] => {
|
|
293
|
-
const lines: string[] = [];
|
|
294
|
-
|
|
295
|
-
const visibleItems: { selectableIdx: number | null; item: SelectItem }[] = [];
|
|
296
|
-
let nextSelectableIdx = 0;
|
|
297
|
-
for (const item of displayItems) {
|
|
298
|
-
if (item.value.startsWith("__section__")) {
|
|
299
|
-
visibleItems.push({ selectableIdx: null, item });
|
|
300
|
-
} else {
|
|
301
|
-
visibleItems.push({ selectableIdx: nextSelectableIdx++, item });
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// Show visible range with scroll
|
|
306
|
-
const startIdx = Math.max(0, scrollOffset);
|
|
307
|
-
const endIdx = Math.min(visibleItems.length, startIdx + maxVisible);
|
|
308
|
-
|
|
309
|
-
for (let vIdx = startIdx; vIdx < endIdx; vIdx++) {
|
|
310
|
-
const { selectableIdx, item } = visibleItems[vIdx];
|
|
311
|
-
|
|
312
|
-
if (item.value.startsWith("__section__")) {
|
|
313
|
-
// Section header
|
|
314
|
-
lines.push(theme.fg("accent", item.label));
|
|
315
|
-
} else {
|
|
316
|
-
// Selectable item
|
|
317
|
-
const isCursor = selectableIdx === cursorPos;
|
|
318
|
-
const isSelected = selectableIdx !== null && selectedSet.has(selectableIdx);
|
|
319
|
-
const prefix = isCursor ? theme.fg("accent", "> ") : " ";
|
|
320
|
-
const checkbox = isSelected ? theme.fg("success", "[x]") : theme.fg("dim", "[ ]");
|
|
321
|
-
const truncatedLabel = truncateToWidth(item.label, width - 6);
|
|
322
|
-
const line = `${prefix}${checkbox} ${truncatedLabel}`;
|
|
323
|
-
lines.push(isCursor ? theme.fg("accent", line) : line);
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
// Scroll indicator
|
|
328
|
-
if (visibleItems.length > maxVisible) {
|
|
329
|
-
const scrollInfo = ` (${startIdx + 1}-${endIdx}/${visibleItems.length})`;
|
|
330
|
-
lines.push(theme.fg("dim", scrollInfo));
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
return lines;
|
|
334
|
-
};
|
|
335
|
-
|
|
336
|
-
return {
|
|
337
|
-
render(width: number) {
|
|
338
|
-
const lines: string[] = [];
|
|
339
|
-
lines.push(theme.bold("Simplify: Select findings to apply"));
|
|
340
|
-
lines.push(
|
|
341
|
-
theme.fg(
|
|
342
|
-
"muted",
|
|
343
|
-
`Found ${candidates.length} candidates (${safeCandidates.length} safe, ${confirmCandidates.length} confirm, ${reviewCandidates.length} review)`,
|
|
344
|
-
),
|
|
345
|
-
);
|
|
346
|
-
lines.push("");
|
|
347
|
-
lines.push(...renderList(width));
|
|
348
|
-
lines.push("");
|
|
349
|
-
lines.push(
|
|
350
|
-
theme.fg(
|
|
351
|
-
"muted",
|
|
352
|
-
`Selected: ${selectedSet.size} • ↑↓ navigate • space toggle • a select all • enter confirm • esc cancel`,
|
|
353
|
-
),
|
|
354
|
-
);
|
|
355
|
-
return lines;
|
|
356
|
-
},
|
|
357
|
-
invalidate() {},
|
|
358
|
-
handleInput(data: string) {
|
|
359
|
-
if (matchesKey(data, Key.enter)) {
|
|
360
|
-
const results = Array.from(selectedSet).map((i) => selectableItems[i].candidate);
|
|
361
|
-
done(results);
|
|
362
|
-
return;
|
|
363
|
-
}
|
|
364
|
-
if (matchesKey(data, Key.escape)) {
|
|
365
|
-
done([]);
|
|
366
|
-
return;
|
|
367
|
-
}
|
|
368
|
-
if (matchesKey(data, Key.space)) {
|
|
369
|
-
// Toggle current selection
|
|
370
|
-
if (selectedSet.has(cursorPos)) {
|
|
371
|
-
selectedSet.delete(cursorPos);
|
|
372
|
-
} else {
|
|
373
|
-
selectedSet.add(cursorPos);
|
|
374
|
-
}
|
|
375
|
-
tui.requestRender();
|
|
376
|
-
return;
|
|
377
|
-
}
|
|
378
|
-
if (matchesKey(data, "a")) {
|
|
379
|
-
// Select/deselect all
|
|
380
|
-
if (selectedSet.size === selectableItems.length) {
|
|
381
|
-
selectedSet.clear();
|
|
382
|
-
} else {
|
|
383
|
-
for (let i = 0; i < selectableItems.length; i++) {
|
|
384
|
-
selectedSet.add(i);
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
tui.requestRender();
|
|
388
|
-
return;
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// Navigation
|
|
392
|
-
if (matchesKey(data, Key.down)) {
|
|
393
|
-
cursorPos = Math.min(selectableItems.length - 1, cursorPos + 1);
|
|
394
|
-
// Ensure cursor is within visible window
|
|
395
|
-
const displayIdx = selectableItems[cursorPos].index;
|
|
396
|
-
if (displayIdx >= scrollOffset + maxVisible) {
|
|
397
|
-
scrollOffset = displayIdx - maxVisible + 1;
|
|
398
|
-
}
|
|
399
|
-
tui.requestRender();
|
|
400
|
-
return;
|
|
401
|
-
}
|
|
402
|
-
if (matchesKey(data, Key.up)) {
|
|
403
|
-
cursorPos = Math.max(0, cursorPos - 1);
|
|
404
|
-
// Ensure cursor is within visible window
|
|
405
|
-
const displayIdx = selectableItems[cursorPos].index;
|
|
406
|
-
if (displayIdx < scrollOffset) {
|
|
407
|
-
// Scroll up to show the item, and include section header if it's just above
|
|
408
|
-
scrollOffset = Math.max(0, displayIdx - 1);
|
|
409
|
-
}
|
|
410
|
-
tui.requestRender();
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
if (matchesKey(data, Key.home)) {
|
|
414
|
-
cursorPos = 0;
|
|
415
|
-
scrollOffset = 0;
|
|
416
|
-
tui.requestRender();
|
|
417
|
-
return;
|
|
418
|
-
}
|
|
419
|
-
if (matchesKey(data, Key.end)) {
|
|
420
|
-
cursorPos = selectableItems.length - 1;
|
|
421
|
-
const lastDisplayIdx = selectableItems[cursorPos].index;
|
|
422
|
-
scrollOffset = Math.max(0, lastDisplayIdx - maxVisible + 1);
|
|
423
|
-
tui.requestRender();
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
},
|
|
427
|
-
};
|
|
428
|
-
});
|
|
429
|
-
|
|
430
|
-
return result ?? [];
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
async function applyFindings(
|
|
434
|
-
ctx: ExtensionCommandContext,
|
|
435
|
-
selected: SimplifyResult[],
|
|
436
|
-
): Promise<void> {
|
|
437
|
-
if (selected.length === 0) {
|
|
438
|
-
ctx.ui.notify("No findings selected to apply", "info");
|
|
439
|
-
return;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
const safeItems = selected.filter((c) => c.risk === "safe");
|
|
443
|
-
const confirmItems = selected.filter((c) => c.risk === "confirm");
|
|
444
|
-
|
|
445
|
-
const cleanupPrompt = `# Apply Review Findings
|
|
446
|
-
|
|
447
|
-
Apply the following findings. Each item includes a bracketed action (e.g. \`[delete]\`, \`[refactor]\`, \`[parallelize]\`, \`[inline]\`) — follow that action, not a blanket delete.
|
|
448
|
-
|
|
449
|
-
${selected.map((c) => `- ${c.file} (${c.lines || "?"}): ${c.reason} [${c.action}]`).join("\n")}
|
|
450
|
-
|
|
451
|
-
For each item:
|
|
452
|
-
1. Read the file to find the exact location
|
|
453
|
-
2. Apply only the specified change (not surrounding code unless instructed)
|
|
454
|
-
3. For refactor/inline/parallelize: preserve behavior; if the change has visible side effects, stop and report
|
|
455
|
-
4. If the change affects other code, stop and report the issue
|
|
456
|
-
|
|
457
|
-
After applying all changes:
|
|
458
|
-
- Run \`npm test\` or equivalent; if there are no tests, verify the files parse/type-check
|
|
459
|
-
- Report what changed, test results, and any items skipped with reasons`;
|
|
460
|
-
|
|
461
|
-
ctx.ui.notify(
|
|
462
|
-
`Applying ${selected.length} findings (${safeItems.length} safe, ${confirmItems.length} confirmed)`,
|
|
463
|
-
"info",
|
|
464
|
-
);
|
|
465
|
-
|
|
466
|
-
pi.sendUserMessage(cleanupPrompt);
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
pi.registerCommand("simplify", {
|
|
470
|
-
description: "Review changed code for reuse, quality, and efficiency, then apply fixes",
|
|
471
|
-
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
472
|
-
if (!ctx.hasUI) {
|
|
473
|
-
ctx.ui.notify("Simplify requires interactive mode", "error");
|
|
474
|
-
return;
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
if (!ctx.isIdle()) {
|
|
478
|
-
ctx.ui.notify(
|
|
479
|
-
"Cannot run simplify while agent is busy. Wait for current task to complete.",
|
|
480
|
-
"warning",
|
|
481
|
-
);
|
|
482
|
-
return;
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
// Check if in git repo
|
|
486
|
-
const { code } = await pi.exec("git", ["rev-parse", "--git-dir"]);
|
|
487
|
-
if (code !== 0) {
|
|
488
|
-
ctx.ui.notify("Not a git repository", "error");
|
|
489
|
-
return;
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
// Check if there are changes
|
|
493
|
-
const { stdout: gitStatus } = await pi.exec("git", ["status", "--porcelain"]);
|
|
494
|
-
if (!gitStatus.trim()) {
|
|
495
|
-
ctx.ui.notify("No git changes found. Simplify reviews uncommitted changes.", "info");
|
|
496
|
-
return;
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
ctx.ui.notify("Analyzing code for review findings...", "info");
|
|
500
|
-
|
|
501
|
-
// Build prompt with optional focus
|
|
502
|
-
let fullPrompt = SIMPLIFY_PROMPT;
|
|
503
|
-
if (args.trim()) {
|
|
504
|
-
fullPrompt += `\n\n## Additional Focus\n\n${args.trim()}`;
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
// Reset capture buffer, then send prompt and wait.
|
|
508
|
-
// message_end events append to assistantTextBuffer during the turn.
|
|
509
|
-
//
|
|
510
|
-
// Wait for the queued analysis turn to actually begin before waiting for
|
|
511
|
-
// idle; otherwise waitForIdle() can return immediately while the agent is
|
|
512
|
-
// still idle and the queued prompt has not started yet.
|
|
513
|
-
assistantTextBuffer = "";
|
|
514
|
-
const turnStarted = new Promise<void>((r) => {
|
|
515
|
-
resolvePendingTurnStart = r;
|
|
516
|
-
});
|
|
517
|
-
|
|
518
|
-
pi.sendUserMessage(fullPrompt);
|
|
519
|
-
|
|
520
|
-
const started = await Promise.race<boolean>([
|
|
521
|
-
turnStarted.then(() => true),
|
|
522
|
-
new Promise<boolean>((r) => setTimeout(() => r(false), 10000)),
|
|
523
|
-
]);
|
|
524
|
-
if (!started) {
|
|
525
|
-
resolvePendingTurnStart = null;
|
|
526
|
-
ctx.ui.notify("Analysis did not start within 10 seconds. Please try again.", "warning");
|
|
527
|
-
return;
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
await ctx.waitForIdle();
|
|
531
|
-
const analysisText = assistantTextBuffer;
|
|
532
|
-
|
|
533
|
-
if (!analysisText) {
|
|
534
|
-
ctx.ui.notify("Could not read analysis — no response captured.", "error");
|
|
535
|
-
return;
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
const candidates = parseCandidatesJSON(analysisText);
|
|
539
|
-
|
|
540
|
-
if (candidates === null) {
|
|
541
|
-
ctx.ui.notify(
|
|
542
|
-
"Could not parse review findings — the model did not return the expected JSON block.",
|
|
543
|
-
"warning",
|
|
544
|
-
);
|
|
545
|
-
return;
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
if (candidates.length === 0) {
|
|
549
|
-
ctx.ui.notify("No review findings found!", "info");
|
|
550
|
-
return;
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
ctx.ui.notify(`Found ${candidates.length} findings. Select findings to apply...`, "info");
|
|
554
|
-
|
|
555
|
-
// Show selector
|
|
556
|
-
const selected = await showCandidateSelector(ctx, candidates);
|
|
557
|
-
|
|
558
|
-
if (!selected || selected.length === 0) {
|
|
559
|
-
ctx.ui.notify("Apply findings cancelled", "info");
|
|
560
|
-
return;
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
// Apply selected findings
|
|
564
|
-
await applyFindings(ctx, selected);
|
|
565
|
-
},
|
|
566
|
-
});
|
|
567
|
-
|
|
568
|
-
pi.registerCommand("simplify-quick", {
|
|
569
|
-
description: "Quick cleanup of obviously safe items (debug code, unused exports)",
|
|
570
|
-
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
571
|
-
if (!ctx.hasUI) {
|
|
572
|
-
ctx.ui.notify("Simplify requires interactive mode", "error");
|
|
573
|
-
return;
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
if (!ctx.isIdle()) {
|
|
577
|
-
ctx.ui.notify("Agent is busy. Try again after current task.", "warning");
|
|
578
|
-
return;
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
const quickPrompt = `# Quick Cleanup
|
|
582
|
-
|
|
583
|
-
Find and delete ONLY the most obviously safe cleanup items:
|
|
584
|
-
|
|
585
|
-
1. \`console.log\`, \`console.warn\`, \`console.error\` statements
|
|
586
|
-
2. \`debugger\` statements
|
|
587
|
-
3. Unused \`import\` statements (imported but never used)
|
|
588
|
-
4. Empty \`catch\` blocks (just \`catch (e) {}\`)
|
|
589
|
-
5. Unused \`const\`/\`let\`/\`var\` declarations
|
|
590
|
-
|
|
591
|
-
DO NOT delete:
|
|
592
|
-
- Commented-out code
|
|
593
|
-
- Over-engineered abstractions
|
|
594
|
-
- Duplicate logic
|
|
595
|
-
- Anything that might be needed
|
|
596
|
-
|
|
597
|
-
For each item found:
|
|
598
|
-
1. Confirm it's truly unused by searching for references
|
|
599
|
-
2. Delete only the specific lines
|
|
600
|
-
3. Report what was deleted
|
|
601
|
-
|
|
602
|
-
Return a summary of what was deleted.`;
|
|
603
|
-
|
|
604
|
-
ctx.ui.notify("Running quick cleanup...", "info");
|
|
605
|
-
pi.sendUserMessage(quickPrompt, { deliverAs: "followUp" });
|
|
606
|
-
},
|
|
607
|
-
});
|
|
15
|
+
registerSimplifyWorkflow(pi);
|
|
608
16
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geminixiang/pi-simplify",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.7",
|
|
4
4
|
"description": "Simplify: Review changed code for reuse, quality, and efficiency",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package"
|
|
@@ -19,7 +19,9 @@
|
|
|
19
19
|
"fmt:check": "oxfmt --check"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@
|
|
22
|
+
"@earendil-works/pi-coding-agent": ">=0.74.0",
|
|
23
|
+
"@earendil-works/pi-tui": ">=0.74.0",
|
|
24
|
+
"typebox": "^1.1.38"
|
|
23
25
|
},
|
|
24
26
|
"devDependencies": {
|
|
25
27
|
"oxfmt": "^0.45.0",
|
package/prompt.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export const SIMPLIFY_PROMPT = `# Simplify: Review Changed Code for Reuse, Quality, and Efficiency
|
|
2
|
+
|
|
3
|
+
You are a code review assistant. Review the changed code along three axes — **Reuse**, **Quality**, and **Efficiency** — and surface concrete fixes.
|
|
4
|
+
|
|
5
|
+
Match the user's language for candidate reasons and summaries; if the user's request is in Chinese, write the candidate \`reason\` fields in Chinese.
|
|
6
|
+
|
|
7
|
+
## What to Find
|
|
8
|
+
|
|
9
|
+
### A. Reuse (Confirm Before Replacing)
|
|
10
|
+
|
|
11
|
+
Before flagging, **search the codebase** (utility directories, shared modules, files adjacent to the change) for existing helpers. Quote the existing symbol you'd use.
|
|
12
|
+
|
|
13
|
+
- **Duplicates an existing function**: a newly written helper does what an existing one already does
|
|
14
|
+
- **Inline logic that has a utility**: hand-rolled string manipulation, manual path handling, custom env checks, ad-hoc type guards
|
|
15
|
+
- **Reinvented framework primitive**: re-implementing something the language/stdlib/framework already provides
|
|
16
|
+
|
|
17
|
+
### B. Quality
|
|
18
|
+
|
|
19
|
+
#### B1. Dead Code (Safe to Delete)
|
|
20
|
+
- Unused exports, orphan files, zombie variables, empty try/catch/if blocks
|
|
21
|
+
|
|
22
|
+
#### B2. Debug Remnants (Safe to Delete)
|
|
23
|
+
- \`console.log\` / \`console.warn\` / \`console.error\`, \`debugger\`, temporary feature flags, stale TODO comments
|
|
24
|
+
|
|
25
|
+
#### B3. Commented-out Code (Review)
|
|
26
|
+
- Old logic left in comments, disabled features, uncustomized templates
|
|
27
|
+
|
|
28
|
+
#### B4. Over-engineering (Confirm)
|
|
29
|
+
- Abstractions created "for future use" but unused, single-call-site helpers that should be inlined, useless indirection
|
|
30
|
+
|
|
31
|
+
#### B5. Hacky Patterns (Confirm)
|
|
32
|
+
- **Redundant state**: state that duplicates other state, cached values that could be derived, observers that could be direct calls
|
|
33
|
+
- **Parameter sprawl**: piling new parameters onto a function instead of restructuring
|
|
34
|
+
- **Copy-paste with variation**: near-duplicate blocks that should share an abstraction
|
|
35
|
+
- **Leaky abstractions**: exposing internals or breaking existing boundaries
|
|
36
|
+
- **Stringly-typed code**: raw strings where an existing constant/enum/union exists
|
|
37
|
+
- **Unnecessary wrapper elements**: JSX/DOM wrappers that add no layout value
|
|
38
|
+
- **Nested conditionals**: ternary chains or if/else nested 3+ levels deep — flatten with early returns or a lookup table
|
|
39
|
+
- **Useless comments**: comments restating WHAT the code does, narrating the change, or referencing the task/caller — keep only non-obvious WHY
|
|
40
|
+
|
|
41
|
+
### C. Efficiency (Confirm)
|
|
42
|
+
|
|
43
|
+
- **Unnecessary work**: redundant computations, repeated file reads, duplicate API calls, N+1 patterns
|
|
44
|
+
- **Missed concurrency**: independent operations run sequentially when they could run in parallel
|
|
45
|
+
- **Hot-path bloat**: blocking work added to startup or per-request/per-render hot paths
|
|
46
|
+
- **Recurring no-op updates**: state writes inside loops/intervals/handlers that fire unconditionally — add a change-detection guard
|
|
47
|
+
- **Unnecessary existence checks**: pre-checking file/resource existence before operating (TOCTOU) — operate directly and handle the error
|
|
48
|
+
- **Memory**: unbounded data structures, missing cleanup, event listener leaks
|
|
49
|
+
- **Overly broad operations**: reading whole files when a slice would do, loading all items when filtering for one
|
|
50
|
+
|
|
51
|
+
## How to Analyze
|
|
52
|
+
|
|
53
|
+
1. Run \`git diff\` to see what changed.
|
|
54
|
+
2. For each change, classify as **Essential** / **Residual** / **Legacy** (don't flag legacy code unless the diff touches it).
|
|
55
|
+
3. For each finding:
|
|
56
|
+
- Identify exact file and line(s)
|
|
57
|
+
- Assign **category** (reuse / quality / efficiency) and **risk**
|
|
58
|
+
- State the concrete fix (which existing utility to call, which lines to delete, how to parallelize, etc.)
|
|
59
|
+
|
|
60
|
+
## Risk Levels
|
|
61
|
+
|
|
62
|
+
- **safe**: Definitely apply (dead code, debug remnants)
|
|
63
|
+
- **confirm**: Apply after user confirms (reuse swaps, over-engineering, hacky patterns, efficiency fixes)
|
|
64
|
+
- **review**: User should look first (commented-out code, ambiguous cases)
|
|
65
|
+
|
|
66
|
+
## Rules
|
|
67
|
+
|
|
68
|
+
1. When in doubt, mark as "confirm" or "review" — don't change without consent.
|
|
69
|
+
2. For reuse findings, name the existing symbol/file you'd swap to.
|
|
70
|
+
3. For efficiency findings, briefly justify the win (e.g., "N+1 → single query", "sequential awaits → Promise.all").
|
|
71
|
+
4. Don't flag necessary code just because it's simple.
|
|
72
|
+
5. Respect existing abstraction boundaries.
|
|
73
|
+
6. Be especially careful with:
|
|
74
|
+
- Error handling code
|
|
75
|
+
- Security-related logic
|
|
76
|
+
- Code that looks "unused" but is called via reflection/eval
|
|
77
|
+
- Database migration files
|
|
78
|
+
|
|
79
|
+
## Output Format (REQUIRED)
|
|
80
|
+
|
|
81
|
+
When analysis is complete, call the \`simplify_candidates\` tool exactly once as your final action. Put ALL candidates in that tool call.
|
|
82
|
+
|
|
83
|
+
Field notes:
|
|
84
|
+
- \`category\` — one of: "reuse", "quality", "efficiency"
|
|
85
|
+
- \`risk\` — one of: "safe", "confirm", "review"
|
|
86
|
+
- \`file\` — repository-relative path, no backticks, no markdown
|
|
87
|
+
- \`lines\` — line number or range ("42" or "42-57"); empty string if unknown
|
|
88
|
+
- \`reason\` — single plain-text sentence stating the concrete fix
|
|
89
|
+
- \`action\` — one of: "delete", "inline", "refactor", "parallelize"
|
|
90
|
+
|
|
91
|
+
If there are no candidates, call \`simplify_candidates\` with an empty \`candidates\` array.
|
|
92
|
+
Do NOT write a prose-only final answer; the extension relies on the tool result.
|
|
93
|
+
`;
|
package/selector.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { getSelectListTheme, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import {
|
|
3
|
+
matchesKey,
|
|
4
|
+
Key,
|
|
5
|
+
SelectList,
|
|
6
|
+
wrapTextWithAnsi,
|
|
7
|
+
type SelectItem,
|
|
8
|
+
} from "@earendil-works/pi-tui";
|
|
9
|
+
|
|
10
|
+
import type { Action, SimplifyResult } from "./types.js";
|
|
11
|
+
|
|
12
|
+
const RISK_CONFIG = {
|
|
13
|
+
safe: { label: "Safe to apply" },
|
|
14
|
+
confirm: { label: "Needs confirmation" },
|
|
15
|
+
review: { label: "Needs review" },
|
|
16
|
+
} as const;
|
|
17
|
+
|
|
18
|
+
const ACTION_LABEL: Record<Action, string> = {
|
|
19
|
+
delete: "Delete code",
|
|
20
|
+
inline: "Inline code",
|
|
21
|
+
refactor: "Refactor code",
|
|
22
|
+
parallelize: "Run work in parallel",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export async function showCandidateSelector(
|
|
26
|
+
ctx: ExtensionCommandContext,
|
|
27
|
+
candidates: SimplifyResult[],
|
|
28
|
+
): Promise<SimplifyResult[]> {
|
|
29
|
+
if (candidates.length === 0) return [];
|
|
30
|
+
|
|
31
|
+
const safeCandidates = candidates.filter((c) => c.risk === "safe");
|
|
32
|
+
const confirmCandidates = candidates.filter((c) => c.risk === "confirm");
|
|
33
|
+
const reviewCandidates = candidates.filter((c) => c.risk === "review");
|
|
34
|
+
|
|
35
|
+
const sections = [
|
|
36
|
+
{ key: "safe" as const, items: safeCandidates },
|
|
37
|
+
{ key: "confirm" as const, items: confirmCandidates },
|
|
38
|
+
{ key: "review" as const, items: reviewCandidates },
|
|
39
|
+
]
|
|
40
|
+
.map(({ key, items }) => ({ key, items, config: RISK_CONFIG[key], total: items.length }))
|
|
41
|
+
.filter((s) => s.total > 0);
|
|
42
|
+
|
|
43
|
+
const selectableItems = sections.flatMap((section) =>
|
|
44
|
+
section.items.map((candidate) => ({ section, candidate })),
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
const listItems: SelectItem[] = selectableItems.map(({ section, candidate }, index) => ({
|
|
48
|
+
value: String(index),
|
|
49
|
+
label: "",
|
|
50
|
+
description: `${section.config.label} · ${ACTION_LABEL[candidate.action]}`,
|
|
51
|
+
}));
|
|
52
|
+
|
|
53
|
+
const selectedSet = new Set<number>();
|
|
54
|
+
selectableItems.forEach(({ candidate }, index) => {
|
|
55
|
+
if (candidate.risk === "safe") selectedSet.add(index);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const maxVisible = 8;
|
|
59
|
+
let cursorPos = 0;
|
|
60
|
+
|
|
61
|
+
const getSelectListStartIndex = (selectedIndex: number) =>
|
|
62
|
+
Math.max(
|
|
63
|
+
0,
|
|
64
|
+
Math.min(selectedIndex - Math.floor(maxVisible / 2), selectableItems.length - maxVisible),
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
const result = await ctx.ui.custom<SimplifyResult[]>((tui, theme, _keybindings, done) => {
|
|
68
|
+
const updateListLabel = (index: number) => {
|
|
69
|
+
const item = listItems[index];
|
|
70
|
+
const { candidate } = selectableItems[index];
|
|
71
|
+
const checkbox = selectedSet.has(index) ? "[x]" : "[ ]";
|
|
72
|
+
const location = candidate.lines ? `${candidate.file}:${candidate.lines}` : candidate.file;
|
|
73
|
+
item.label = `${checkbox} ${location}`;
|
|
74
|
+
};
|
|
75
|
+
const updateAllListLabels = () => listItems.forEach((_item, index) => updateListLabel(index));
|
|
76
|
+
|
|
77
|
+
updateAllListLabels();
|
|
78
|
+
|
|
79
|
+
const selectList = new SelectList(listItems, maxVisible, getSelectListTheme());
|
|
80
|
+
selectList.onSelectionChange = (item) => {
|
|
81
|
+
cursorPos = Number(item.value);
|
|
82
|
+
};
|
|
83
|
+
selectList.onCancel = () => done([]);
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
render(width: number) {
|
|
87
|
+
selectList.setSelectedIndex(cursorPos);
|
|
88
|
+
|
|
89
|
+
const lines: string[] = [];
|
|
90
|
+
lines.push(theme.bold("Simplify: Select findings to apply"));
|
|
91
|
+
lines.push(
|
|
92
|
+
theme.fg(
|
|
93
|
+
"muted",
|
|
94
|
+
`Found ${candidates.length} candidates (${safeCandidates.length} safe, ${confirmCandidates.length} confirm, ${reviewCandidates.length} review)`,
|
|
95
|
+
),
|
|
96
|
+
);
|
|
97
|
+
lines.push("");
|
|
98
|
+
|
|
99
|
+
const listLines = selectList.render(width);
|
|
100
|
+
const selectedLineIndex = cursorPos - getSelectListStartIndex(cursorPos);
|
|
101
|
+
const current = selectableItems[cursorPos]?.candidate;
|
|
102
|
+
for (const [lineIndex, line] of listLines.entries()) {
|
|
103
|
+
lines.push(line);
|
|
104
|
+
if (lineIndex !== selectedLineIndex || !current) continue;
|
|
105
|
+
|
|
106
|
+
const detailIndent = " ";
|
|
107
|
+
const detailPrefix = `${detailIndent}│ `;
|
|
108
|
+
const location = current.lines ? `${current.file}:${current.lines}` : current.file;
|
|
109
|
+
lines.push(theme.fg("borderMuted", `${detailIndent}┌─ recommendation`));
|
|
110
|
+
lines.push(
|
|
111
|
+
...wrapTextWithAnsi(current.reason, Math.max(1, width - detailPrefix.length)).map(
|
|
112
|
+
(wrappedLine) => theme.fg("muted", `${detailPrefix}${wrappedLine}`),
|
|
113
|
+
),
|
|
114
|
+
);
|
|
115
|
+
lines.push(theme.fg("muted", `${detailPrefix}`));
|
|
116
|
+
lines.push(theme.fg("muted", `${detailPrefix}File: ${location}`));
|
|
117
|
+
lines.push(
|
|
118
|
+
theme.fg("muted", `${detailPrefix}Review: ${RISK_CONFIG[current.risk].label}`),
|
|
119
|
+
);
|
|
120
|
+
lines.push(theme.fg("muted", `${detailPrefix}Kind: ${current.category}`));
|
|
121
|
+
lines.push(theme.fg("muted", `${detailPrefix}Fix: ${ACTION_LABEL[current.action]}`));
|
|
122
|
+
lines.push(theme.fg("borderMuted", `${detailIndent}└─ space selects this fix`));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
lines.push("");
|
|
126
|
+
lines.push(
|
|
127
|
+
theme.fg(
|
|
128
|
+
"muted",
|
|
129
|
+
`Selected: ${selectedSet.size} • ↑↓ navigate • space toggle • a select all • enter confirm • esc cancel`,
|
|
130
|
+
),
|
|
131
|
+
);
|
|
132
|
+
return lines;
|
|
133
|
+
},
|
|
134
|
+
invalidate() {
|
|
135
|
+
selectList.invalidate();
|
|
136
|
+
},
|
|
137
|
+
handleInput(data: string) {
|
|
138
|
+
if (matchesKey(data, Key.enter)) {
|
|
139
|
+
const results = Array.from(selectedSet).map((i) => selectableItems[i].candidate);
|
|
140
|
+
done(results);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (matchesKey(data, Key.escape)) {
|
|
144
|
+
done([]);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (matchesKey(data, Key.space)) {
|
|
148
|
+
if (selectedSet.has(cursorPos)) {
|
|
149
|
+
selectedSet.delete(cursorPos);
|
|
150
|
+
} else {
|
|
151
|
+
selectedSet.add(cursorPos);
|
|
152
|
+
}
|
|
153
|
+
updateListLabel(cursorPos);
|
|
154
|
+
tui.requestRender();
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (matchesKey(data, "a")) {
|
|
158
|
+
if (selectedSet.size === selectableItems.length) {
|
|
159
|
+
selectedSet.clear();
|
|
160
|
+
} else {
|
|
161
|
+
for (let i = 0; i < selectableItems.length; i++) selectedSet.add(i);
|
|
162
|
+
}
|
|
163
|
+
updateAllListLabels();
|
|
164
|
+
tui.requestRender();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const previousCursorPos = cursorPos;
|
|
169
|
+
selectList.handleInput(data);
|
|
170
|
+
if (cursorPos !== previousCursorPos) tui.requestRender();
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
return result ?? [];
|
|
176
|
+
}
|
package/types.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type Category = "reuse" | "quality" | "efficiency";
|
|
2
|
+
export type Risk = "safe" | "confirm" | "review";
|
|
3
|
+
export type Action = "delete" | "inline" | "refactor" | "parallelize";
|
|
4
|
+
|
|
5
|
+
export type SimplifyResult = {
|
|
6
|
+
category: Category;
|
|
7
|
+
file: string;
|
|
8
|
+
lines: string;
|
|
9
|
+
reason: string;
|
|
10
|
+
risk: Risk;
|
|
11
|
+
action: Action;
|
|
12
|
+
};
|
package/workflow.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import {
|
|
2
|
+
defineTool,
|
|
3
|
+
type ExtensionAPI,
|
|
4
|
+
type ExtensionCommandContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { Type } from "typebox";
|
|
7
|
+
|
|
8
|
+
import { SIMPLIFY_PROMPT } from "./prompt.js";
|
|
9
|
+
import { showCandidateSelector } from "./selector.js";
|
|
10
|
+
import type { SimplifyResult } from "./types.js";
|
|
11
|
+
|
|
12
|
+
const categorySchema = Type.Union([
|
|
13
|
+
Type.Literal("reuse"),
|
|
14
|
+
Type.Literal("quality"),
|
|
15
|
+
Type.Literal("efficiency"),
|
|
16
|
+
]);
|
|
17
|
+
const riskSchema = Type.Union([
|
|
18
|
+
Type.Literal("safe"),
|
|
19
|
+
Type.Literal("confirm"),
|
|
20
|
+
Type.Literal("review"),
|
|
21
|
+
]);
|
|
22
|
+
const actionSchema = Type.Union([
|
|
23
|
+
Type.Literal("delete"),
|
|
24
|
+
Type.Literal("inline"),
|
|
25
|
+
Type.Literal("refactor"),
|
|
26
|
+
Type.Literal("parallelize"),
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
function registerSimplifyCandidatesTool(
|
|
30
|
+
pi: ExtensionAPI,
|
|
31
|
+
state: {
|
|
32
|
+
getResolver: () => ((candidates: SimplifyResult[]) => void) | null;
|
|
33
|
+
clearResolver: () => void;
|
|
34
|
+
setLatestCandidates: (candidates: SimplifyResult[]) => void;
|
|
35
|
+
},
|
|
36
|
+
) {
|
|
37
|
+
const parameters = Type.Object({
|
|
38
|
+
candidates: Type.Array(
|
|
39
|
+
Type.Object({
|
|
40
|
+
category: categorySchema,
|
|
41
|
+
risk: riskSchema,
|
|
42
|
+
file: Type.String({
|
|
43
|
+
description: "Repository-relative path",
|
|
44
|
+
minLength: 1,
|
|
45
|
+
pattern: "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$",
|
|
46
|
+
}),
|
|
47
|
+
lines: Type.String({ description: "Line number or range, or empty string if unknown" }),
|
|
48
|
+
reason: Type.String({ description: "Concrete fix in one sentence" }),
|
|
49
|
+
action: actionSchema,
|
|
50
|
+
}),
|
|
51
|
+
),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
pi.registerTool(
|
|
55
|
+
defineTool({
|
|
56
|
+
name: "simplify_candidates",
|
|
57
|
+
label: "Simplify Candidates",
|
|
58
|
+
description:
|
|
59
|
+
"Return the complete candidate list for /simplify. Use as the final action after analyzing changed code.",
|
|
60
|
+
promptSnippet: "Return structured cleanup candidates for /simplify as a terminating result",
|
|
61
|
+
promptGuidelines: [
|
|
62
|
+
"Use simplify_candidates exactly once as the final action when the /simplify command asks for cleanup candidates.",
|
|
63
|
+
],
|
|
64
|
+
parameters,
|
|
65
|
+
async execute(_toolCallId, params) {
|
|
66
|
+
const candidates: SimplifyResult[] = params.candidates;
|
|
67
|
+
const resolve = state.getResolver();
|
|
68
|
+
if (!resolve) {
|
|
69
|
+
return {
|
|
70
|
+
content: [
|
|
71
|
+
{
|
|
72
|
+
type: "text" as const,
|
|
73
|
+
text: "Ignored simplify candidates because no /simplify analysis is pending.",
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
details: {
|
|
77
|
+
ignored: true,
|
|
78
|
+
candidates: [],
|
|
79
|
+
byRisk: { safe: 0, confirm: 0, review: 0 },
|
|
80
|
+
},
|
|
81
|
+
terminate: true,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
state.setLatestCandidates(candidates);
|
|
86
|
+
state.clearResolver();
|
|
87
|
+
resolve(candidates);
|
|
88
|
+
|
|
89
|
+
const byRisk = {
|
|
90
|
+
safe: candidates.filter((c) => c.risk === "safe").length,
|
|
91
|
+
confirm: candidates.filter((c) => c.risk === "confirm").length,
|
|
92
|
+
review: candidates.filter((c) => c.risk === "review").length,
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
content: [
|
|
97
|
+
{
|
|
98
|
+
type: "text" as const,
|
|
99
|
+
text: `Captured ${candidates.length} simplify candidates (${byRisk.safe} safe, ${byRisk.confirm} confirm, ${byRisk.review} review).`,
|
|
100
|
+
},
|
|
101
|
+
],
|
|
102
|
+
details: { ignored: false, candidates, byRisk },
|
|
103
|
+
terminate: true,
|
|
104
|
+
};
|
|
105
|
+
},
|
|
106
|
+
}),
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function applyFindings(
|
|
111
|
+
ctx: ExtensionCommandContext,
|
|
112
|
+
selected: SimplifyResult[],
|
|
113
|
+
pi: ExtensionAPI,
|
|
114
|
+
) {
|
|
115
|
+
if (selected.length === 0) {
|
|
116
|
+
ctx.ui.notify("No findings selected to apply", "info");
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const safeItems = selected.filter((c) => c.risk === "safe");
|
|
121
|
+
const confirmItems = selected.filter((c) => c.risk === "confirm");
|
|
122
|
+
|
|
123
|
+
const cleanupPrompt = `# Apply Review Findings
|
|
124
|
+
|
|
125
|
+
Apply the following findings. Each item includes a bracketed action (e.g. \`[delete]\`, \`[refactor]\`, \`[parallelize]\`, \`[inline]\`) — follow that action, not a blanket delete.
|
|
126
|
+
|
|
127
|
+
${selected.map((c) => `- ${c.file} (${c.lines || "?"}): ${c.reason} [${c.action}]`).join("\n")}
|
|
128
|
+
|
|
129
|
+
For each item:
|
|
130
|
+
1. Read the file to find the exact location
|
|
131
|
+
2. Apply only the specified change (not surrounding code unless instructed)
|
|
132
|
+
3. For refactor/inline/parallelize: preserve behavior; if the change has visible side effects, stop and report
|
|
133
|
+
4. If the change affects other code, stop and report the issue
|
|
134
|
+
|
|
135
|
+
After applying all changes:
|
|
136
|
+
- Run \`npm test\` or equivalent; if there are no tests, verify the files parse/type-check
|
|
137
|
+
- Report what changed, test results, and any items skipped with reasons`;
|
|
138
|
+
|
|
139
|
+
ctx.ui.notify(
|
|
140
|
+
`Applying ${selected.length} findings (${safeItems.length} safe, ${confirmItems.length} confirmed)`,
|
|
141
|
+
"info",
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
pi.sendUserMessage(cleanupPrompt);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function registerSimplifyWorkflow(pi: ExtensionAPI) {
|
|
148
|
+
let resolvePendingTurnStart: (() => void) | null = null;
|
|
149
|
+
let resolvePendingCandidatesTool: ((candidates: SimplifyResult[]) => void) | null = null;
|
|
150
|
+
let latestToolCandidates: SimplifyResult[] | null = null;
|
|
151
|
+
|
|
152
|
+
pi.on("turn_start", () => {
|
|
153
|
+
if (!resolvePendingTurnStart) return;
|
|
154
|
+
const resolve = resolvePendingTurnStart;
|
|
155
|
+
resolvePendingTurnStart = null;
|
|
156
|
+
resolve();
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
registerSimplifyCandidatesTool(pi, {
|
|
160
|
+
getResolver: () => resolvePendingCandidatesTool,
|
|
161
|
+
clearResolver: () => {
|
|
162
|
+
resolvePendingCandidatesTool = null;
|
|
163
|
+
},
|
|
164
|
+
setLatestCandidates: (candidates) => {
|
|
165
|
+
latestToolCandidates = candidates;
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
pi.registerCommand("simplify", {
|
|
170
|
+
description: "Review changed code for reuse, quality, and efficiency, then apply fixes",
|
|
171
|
+
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
172
|
+
if (!ctx.hasUI) {
|
|
173
|
+
ctx.ui.notify("Simplify requires interactive mode", "error");
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!ctx.isIdle()) {
|
|
178
|
+
ctx.ui.notify(
|
|
179
|
+
"Cannot run simplify while agent is busy. Wait for current task to complete.",
|
|
180
|
+
"warning",
|
|
181
|
+
);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const { code } = await pi.exec("git", ["rev-parse", "--git-dir"]);
|
|
186
|
+
if (code !== 0) {
|
|
187
|
+
ctx.ui.notify("Not a git repository", "error");
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const { stdout: gitStatus } = await pi.exec("git", ["status", "--porcelain"]);
|
|
192
|
+
if (!gitStatus.trim()) {
|
|
193
|
+
ctx.ui.notify("No git changes found. Simplify reviews uncommitted changes.", "info");
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
ctx.ui.notify("Analyzing code for review findings...", "info");
|
|
198
|
+
|
|
199
|
+
let fullPrompt = SIMPLIFY_PROMPT;
|
|
200
|
+
if (args.trim()) fullPrompt += `\n\n## Additional Focus\n\n${args.trim()}`;
|
|
201
|
+
|
|
202
|
+
latestToolCandidates = null;
|
|
203
|
+
const turnStarted = new Promise<void>((r) => {
|
|
204
|
+
resolvePendingTurnStart = r;
|
|
205
|
+
});
|
|
206
|
+
const toolResult = new Promise<SimplifyResult[]>((r) => {
|
|
207
|
+
resolvePendingCandidatesTool = r;
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
pi.sendUserMessage(fullPrompt);
|
|
211
|
+
|
|
212
|
+
const started = await Promise.race<boolean>([
|
|
213
|
+
turnStarted.then(() => true),
|
|
214
|
+
new Promise<boolean>((r) => setTimeout(() => r(false), 10000)),
|
|
215
|
+
]);
|
|
216
|
+
if (!started) {
|
|
217
|
+
resolvePendingTurnStart = null;
|
|
218
|
+
resolvePendingCandidatesTool = null;
|
|
219
|
+
ctx.ui.notify("Analysis did not start within 10 seconds. Please try again.", "warning");
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
await ctx.waitForIdle();
|
|
224
|
+
|
|
225
|
+
const candidates =
|
|
226
|
+
latestToolCandidates ??
|
|
227
|
+
(await Promise.race<SimplifyResult[] | null>([
|
|
228
|
+
toolResult,
|
|
229
|
+
new Promise<null>((r) => setTimeout(() => r(null), 100)),
|
|
230
|
+
]));
|
|
231
|
+
resolvePendingCandidatesTool = null;
|
|
232
|
+
|
|
233
|
+
if (candidates === null) {
|
|
234
|
+
ctx.ui.notify(
|
|
235
|
+
"Could not read review findings — the model did not call simplify_candidates.",
|
|
236
|
+
"warning",
|
|
237
|
+
);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
if (candidates.length === 0) {
|
|
242
|
+
ctx.ui.notify("No review findings found!", "info");
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
ctx.ui.notify(`Found ${candidates.length} findings. Select findings to apply...`, "info");
|
|
247
|
+
|
|
248
|
+
const selected = await showCandidateSelector(ctx, candidates);
|
|
249
|
+
if (!selected || selected.length === 0) {
|
|
250
|
+
ctx.ui.notify("Apply findings cancelled", "info");
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
await applyFindings(ctx, selected, pi);
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
}
|