@geminixiang/pi-simplify 0.0.10 → 0.1.0

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/CHANGELOG.md CHANGED
@@ -6,6 +6,28 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.1.0] - 2026-06-03
10
+
11
+ ### Added
12
+
13
+ - Add `/code-smell` command: finds structural problems with programmatic checks (debug remnants, commented-out code, duplication, complex functions) plus agent review across complexity, duplication, coupling, state, errors, performance, and maintainability smell families.
14
+ - Programmatic scanner runs deterministically before agent review; findings are verified by reading files before surfacing them.
15
+ - Interactive findings selector: ranked by severity, auto-selects high-severity / high-confidence items, shows cause-effect chain inline.
16
+
17
+ ### Fixed
18
+
19
+ - Skip redundant `## Scope` section in the agent prompt when scanning the repository root.
20
+
21
+ ### Changed
22
+
23
+ - Reorganise source into `src/simplify/` and `src/code-smell/` subdirectories.
24
+
25
+ ## [0.0.11] - 2026-06-03
26
+
27
+ ### Changed
28
+
29
+ - Add thin-wrapper review heuristics so `/simplify` flags rename-only wrappers, pass-through factories, single-call-site helpers, duplicated write APIs, and test-only exports only when they create real maintenance cost.
30
+
9
31
  ## [0.0.10] - 2026-05-30
10
32
 
11
33
  ### Changed
package/README.md CHANGED
@@ -16,6 +16,8 @@ After implementing a feature, your code often accumulates:
16
16
 
17
17
  `/simplify` finds these and removes them.
18
18
 
19
+ `/code-smell` goes deeper — it runs programmatic checks plus agent review to surface structural problems like coupling, error handling gaps, and performance issues.
20
+
19
21
  ## Installation
20
22
 
21
23
  ```sh
@@ -24,6 +26,32 @@ pi install npm:@geminixiang/pi-simplify
24
26
 
25
27
  ## Usage
26
28
 
29
+ ### Code Smell Analysis
30
+
31
+ ```
32
+ /code-smell
33
+ ```
34
+
35
+ Opens a scope selector. Choose to scan the repository or specific paths.
36
+
37
+ Runs programmatic checks (debug remnants, commented-out code, duplication, complex functions) then agent review across seven smell families:
38
+
39
+ - **Complexity** - long functions, deep nesting, mixed responsibilities
40
+ - **Duplication** - copy-paste blocks, repeated condition chains
41
+ - **Coupling** - cross-layer reach-through, boundary violations
42
+ - **State** - redundant derived state, multiple sources of truth
43
+ - **Errors** - swallowed errors, empty catches, inconsistent mapping
44
+ - **Performance** - N+1 loops, sequential independent awaits
45
+ - **Maintainability** - debug remnants, TODO/HACK markers, stringly-typed constants
46
+
47
+ Findings are ranked by severity. Select which to fix and the agent applies small, behavior-preserving cleanups.
48
+
49
+ ```
50
+ /code-smell src lib
51
+ ```
52
+
53
+ Scans specific paths directly.
54
+
27
55
  ### Full Simplify
28
56
 
29
57
  ```
@@ -53,6 +81,15 @@ Analyzes the specified folders/files as a snapshot (not a diff), even when there
53
81
  /simplify focus on removing debug code
54
82
  ```
55
83
 
84
+ ## Commands
85
+
86
+ | Command | Purpose |
87
+ | --- | --- |
88
+ | `/simplify` | Delete excess after a feature: dead code, debug remnants, thin wrappers |
89
+ | `/simplify folder <paths>` | Same as above but snapshot mode (no git diff needed) |
90
+ | `/code-smell` | Find structural problems: coupling, complexity, error handling, performance |
91
+ | `/code-smell <paths>` | Scan specific paths for code smells |
92
+
56
93
  ## Comparison with pi-review
57
94
 
58
95
  | | pi-review | pi-simplify |
package/index.ts CHANGED
@@ -1,16 +1,15 @@
1
1
  /**
2
2
  * pi-simplify: Code Review & Cleanup Extension for pi
3
3
  *
4
- * Reviews changed code for reuse, quality, and efficiency:
5
- * - Reuse: replace newly-written code with existing utilities
6
- * - Quality: dead code, debug remnants, commented-out code, over-engineering, duplicate logic
7
- * - Efficiency: redundant work, missed concurrency, hot-path bloat, memory leaks
4
+ * /simplify — reviews changed code for reuse, quality, and efficiency
5
+ * /code-smell — finds structural problems with programmatic checks and agent review
8
6
  */
9
7
 
10
8
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
-
12
- import { registerSimplifyWorkflow } from "./workflow.js";
9
+ import { registerCodeSmellWorkflow } from "./src/code-smell/workflow.js";
10
+ import { registerSimplifyWorkflow } from "./src/simplify/workflow.js";
13
11
 
14
12
  export default function simplifyExtension(pi: ExtensionAPI) {
15
13
  registerSimplifyWorkflow(pi);
14
+ registerCodeSmellWorkflow(pi);
16
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geminixiang/pi-simplify",
3
- "version": "0.0.10",
3
+ "version": "0.1.0",
4
4
  "description": "Simplify: Review changed code for reuse, quality, and efficiency",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -0,0 +1,210 @@
1
+ import { readdir, readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import type { ProgrammaticCheck, SmellCategory, SmellSeverity } from "./types.js";
5
+
6
+ const DEFAULT_IGNORES = new Set([
7
+ ".git",
8
+ "node_modules",
9
+ "dist",
10
+ "build",
11
+ "coverage",
12
+ ".next",
13
+ ".turbo",
14
+ ".cache",
15
+ ]);
16
+
17
+ const TEXT_EXTENSIONS = new Set([
18
+ ".ts",
19
+ ".tsx",
20
+ ".js",
21
+ ".jsx",
22
+ ".mjs",
23
+ ".cjs",
24
+ ".py",
25
+ ".go",
26
+ ".rs",
27
+ ".java",
28
+ ".kt",
29
+ ".rb",
30
+ ".php",
31
+ ".cs",
32
+ ".swift",
33
+ ]);
34
+
35
+ type ScanOptions = {
36
+ cwd: string;
37
+ paths: string[];
38
+ maxFiles?: number;
39
+ };
40
+
41
+ type SourceFile = {
42
+ absolutePath: string;
43
+ relativePath: string;
44
+ text: string;
45
+ lines: string[];
46
+ };
47
+
48
+ async function collectFiles(root: string, target: string, out: string[], maxFiles: number) {
49
+ if (out.length >= maxFiles) return;
50
+ const absolute = path.resolve(root, target);
51
+ const info = await stat(absolute).catch(() => null);
52
+ if (!info) return;
53
+
54
+ if (info.isFile()) {
55
+ if (TEXT_EXTENSIONS.has(path.extname(absolute))) out.push(absolute);
56
+ return;
57
+ }
58
+
59
+ if (!info.isDirectory()) return;
60
+ const entries = await readdir(absolute, { withFileTypes: true }).catch(() => []);
61
+ for (const entry of entries) {
62
+ if (out.length >= maxFiles) return;
63
+ if (DEFAULT_IGNORES.has(entry.name)) continue;
64
+ await collectFiles(root, path.join(target, entry.name), out, maxFiles);
65
+ }
66
+ }
67
+
68
+ function lineRange(start: number, end?: number) {
69
+ return end && end !== start ? `${start}-${end}` : String(start);
70
+ }
71
+
72
+ function push(
73
+ findings: ProgrammaticCheck[],
74
+ args: Omit<ProgrammaticCheck, "severity" | "category"> & {
75
+ category: SmellCategory;
76
+ severity: SmellSeverity;
77
+ },
78
+ ) {
79
+ findings.push(args);
80
+ }
81
+
82
+ function scanFile(file: SourceFile): ProgrammaticCheck[] {
83
+ const findings: ProgrammaticCheck[] = [];
84
+ const counts = new Map<string, number[]>();
85
+ let functionStart: number | null = null;
86
+ let functionBraceDepth = 0;
87
+ let currentFunctionComplexity = 0;
88
+
89
+ file.lines.forEach((raw, index) => {
90
+ const lineNo = index + 1;
91
+ const line = raw.trim();
92
+ const normalized = line.replace(/\s+/g, " ");
93
+
94
+ if (normalized.length > 20 && !normalized.startsWith("//") && !normalized.startsWith("*")) {
95
+ const existing = counts.get(normalized) ?? [];
96
+ existing.push(lineNo);
97
+ counts.set(normalized, existing);
98
+ }
99
+
100
+ if (/\b(console\.(log|debug|warn|error)|debugger)\b/.test(line)) {
101
+ push(findings, {
102
+ id: "debug-remnant",
103
+ title: "Debug remnant",
104
+ category: "maintainability",
105
+ severity: line.includes("debugger") ? "high" : "medium",
106
+ file: file.relativePath,
107
+ lines: String(lineNo),
108
+ evidence: raw.trim(),
109
+ recommendation:
110
+ "Remove temporary logging/debug statements or replace with the project's structured logger if this is intentional.",
111
+ });
112
+ }
113
+
114
+ if (/^\/\/\s*(if|for|while|return|const|let|var|function|class|import|export)\b/.test(line)) {
115
+ push(findings, {
116
+ id: "commented-out-code",
117
+ title: "Commented-out code",
118
+ category: "maintainability",
119
+ severity: "low",
120
+ file: file.relativePath,
121
+ lines: String(lineNo),
122
+ evidence: raw.trim(),
123
+ recommendation:
124
+ "Delete stale commented code; git history is the source of old implementations.",
125
+ });
126
+ }
127
+
128
+ if (/\b(any|TODO|FIXME|HACK|XXX)\b/.test(line)) {
129
+ push(findings, {
130
+ id: "loose-or-temporary-marker",
131
+ title: "Loose type or temporary marker",
132
+ category: "maintainability",
133
+ severity: line.includes("any") ? "medium" : "low",
134
+ file: file.relativePath,
135
+ lines: String(lineNo),
136
+ evidence: raw.trim(),
137
+ recommendation:
138
+ "Replace temporary markers with a tracked issue or tighten the type/implementation now.",
139
+ });
140
+ }
141
+
142
+ if (/\b(if|for|while|catch|case|&&|\|\|)\b/.test(line)) currentFunctionComplexity += 1;
143
+ if (/\b(function|async function)\b|=>\s*\{/.test(line) && functionStart === null) {
144
+ functionStart = lineNo;
145
+ currentFunctionComplexity = 1;
146
+ functionBraceDepth = 0;
147
+ }
148
+ if (functionStart !== null) {
149
+ functionBraceDepth += (raw.match(/\{/g) ?? []).length;
150
+ functionBraceDepth -= (raw.match(/\}/g) ?? []).length;
151
+ if (functionBraceDepth <= 0 && lineNo > functionStart) {
152
+ if (lineNo - functionStart > 80 || currentFunctionComplexity > 12) {
153
+ push(findings, {
154
+ id: "large-complex-function",
155
+ title: "Large or complex function",
156
+ category: "complexity",
157
+ severity:
158
+ currentFunctionComplexity > 18 || lineNo - functionStart > 140 ? "high" : "medium",
159
+ file: file.relativePath,
160
+ lines: lineRange(functionStart, lineNo),
161
+ evidence: `${lineNo - functionStart + 1} lines, approximate branch count ${currentFunctionComplexity}`,
162
+ recommendation:
163
+ "Split orchestration from decisions; extract named helpers only around stable concepts, not arbitrary line chunks.",
164
+ });
165
+ }
166
+ functionStart = null;
167
+ }
168
+ }
169
+ });
170
+
171
+ for (const [line, occurrences] of counts) {
172
+ if (occurrences.length < 3) continue;
173
+ push(findings, {
174
+ id: "repeated-line",
175
+ title: "Repeated implementation line",
176
+ category: "duplication",
177
+ severity: occurrences.length >= 6 ? "medium" : "low",
178
+ file: file.relativePath,
179
+ lines: occurrences.slice(0, 6).join(","),
180
+ evidence: line,
181
+ recommendation:
182
+ "Check whether these repeated lines represent copy-paste logic that should share a helper or table-driven representation.",
183
+ });
184
+ }
185
+
186
+ return findings;
187
+ }
188
+
189
+ export async function runProgrammaticChecks(options: ScanOptions): Promise<ProgrammaticCheck[]> {
190
+ const maxFiles = options.maxFiles ?? 300;
191
+ const targets = options.paths.length > 0 ? options.paths : ["."];
192
+ const files: string[] = [];
193
+ for (const target of targets) await collectFiles(options.cwd, target, files, maxFiles);
194
+
195
+ const findings: ProgrammaticCheck[] = [];
196
+ for (const absolutePath of files) {
197
+ const text = await readFile(absolutePath, "utf8").catch(() => "");
198
+ if (!text) continue;
199
+ findings.push(
200
+ ...scanFile({
201
+ absolutePath,
202
+ relativePath: path.relative(options.cwd, absolutePath),
203
+ text,
204
+ lines: text.split(/\r?\n/),
205
+ }),
206
+ );
207
+ }
208
+
209
+ return findings;
210
+ }
@@ -0,0 +1,59 @@
1
+ export const CODE_SMELL_PROMPT = `# Code Smell: Find and Clean Structural Problems
2
+
3
+ You are a code smell reviewer. Find code that is likely to become costly to maintain, then propose small, behavior-preserving cleanups.
4
+
5
+ Match the user's language for all candidate fields; if the user's request is in Chinese, write \`smell\`, \`evidence\`, \`impact\`, and \`recommendation\` in Chinese.
6
+
7
+ ## Two Analysis Tracks
8
+
9
+ ### 1. Programmatic Checks
10
+
11
+ First call \`code_smell_scan\` for the requested paths (or the repository root if no paths are specified). Treat these results as leads, not truth. Verify each important finding by reading the relevant file before returning it.
12
+
13
+ ### 2. Agent/Skill Review
14
+
15
+ Then inspect code using these smell families:
16
+
17
+ - **Complexity**: long functions, mixed responsibilities, deep nesting, boolean flag control flow, branch-heavy conditionals
18
+ - **Duplication**: copy-paste blocks, repeated condition chains, parallel representations of the same concept
19
+ - **Coupling**: modules reaching through boundaries, feature code importing internals, circular-feeling dependencies
20
+ - **State**: redundant derived state, mutable globals, caches without invalidation, multiple sources of truth
21
+ - **Errors**: swallowed errors, empty catch blocks, broad catch that hides failures, inconsistent error mapping
22
+ - **Performance**: N+1 loops, repeated I/O, sequential awaits for independent work, hot-path blocking work
23
+ - **Maintainability**: debug remnants, commented-out code, TODO/HACK that hides required design, stringly-typed constants
24
+
25
+ ## Return Only Actionable Smells
26
+
27
+ Every returned smell must include a real cause-effect chain:
28
+
29
+ 1. \`smell\` — the root structural problem in the current code.
30
+ 2. \`evidence\` — the concrete code evidence: symbol, repeated pattern, line, or tool finding.
31
+ 3. \`impact\` — what gets worse if left unchanged: divergent behavior, missed errors, repeated edits, N+1 calls, test brittleness.
32
+ 4. \`recommendation\` — a small, behavior-preserving next step.
33
+
34
+ Do not flag subjective style issues. Do not recommend large rewrites unless a small first slice is clear.
35
+
36
+ ## Severity and Confidence
37
+
38
+ - \`severity\`: \`high\` if likely bug/perf/user impact, \`medium\` if maintenance cost is concrete, \`low\` if cleanup is useful but not urgent.
39
+ - \`confidence\`: \`high\` only after reading enough code to verify the smell; \`medium\` for strong tool-led hints; \`low\` only when the item is worth human inspection.
40
+
41
+ ## Output Format (REQUIRED)
42
+
43
+ When analysis is complete, call the \`code_smell_findings\` tool exactly once as your final action. Put ALL findings in that tool call.
44
+
45
+ Fields:
46
+ - \`category\`: one of \`complexity\`, \`duplication\`, \`coupling\`, \`state\`, \`errors\`, \`performance\`, \`maintainability\`
47
+ - \`severity\`: one of \`low\`, \`medium\`, \`high\`
48
+ - \`confidence\`: one of \`low\`, \`medium\`, \`high\`
49
+ - \`file\`: repository-relative path
50
+ - \`lines\`: line number/range or empty string
51
+ - \`smell\`: root problem
52
+ - \`evidence\`: concrete proof
53
+ - \`impact\`: real consequence if unchanged
54
+ - \`recommendation\`: small fix
55
+ - \`action\`: one of \`inspect\`, \`delete\`, \`inline\`, \`extract\`, \`refactor\`, \`guard\`
56
+
57
+ If there are no findings, call \`code_smell_findings\` with an empty \`findings\` array.
58
+ Do NOT write a prose-only final answer; the extension relies on the tool result.
59
+ `;
@@ -0,0 +1,157 @@
1
+ import {
2
+ getSelectListTheme,
3
+ keyHint,
4
+ rawKeyHint,
5
+ type ExtensionCommandContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { matchesKey, SelectList, wrapTextWithAnsi, type SelectItem } from "@earendil-works/pi-tui";
8
+
9
+ import type { CodeSmellFinding, SmellAction } from "./types.js";
10
+
11
+ const SEVERITY_CONFIG = {
12
+ high: { label: "High severity" },
13
+ medium: { label: "Medium severity" },
14
+ low: { label: "Low severity" },
15
+ } as const;
16
+
17
+ const ACTION_LABEL: Record<SmellAction, string> = {
18
+ inspect: "Inspect manually",
19
+ delete: "Delete code",
20
+ inline: "Inline code",
21
+ extract: "Extract helper",
22
+ refactor: "Refactor",
23
+ guard: "Add guard/check",
24
+ };
25
+
26
+ export async function showFindingSelector(
27
+ ctx: ExtensionCommandContext,
28
+ findings: CodeSmellFinding[],
29
+ ): Promise<CodeSmellFinding[]> {
30
+ if (findings.length === 0) return [];
31
+
32
+ const sorted = [...findings].sort((a, b) => {
33
+ const rank = { high: 0, medium: 1, low: 2 } as const;
34
+ return rank[a.severity] - rank[b.severity];
35
+ });
36
+
37
+ const listItems: SelectItem[] = sorted.map((finding, index) => ({
38
+ value: String(index),
39
+ label: "",
40
+ description: `${SEVERITY_CONFIG[finding.severity].label} · ${finding.confidence} confidence · ${ACTION_LABEL[finding.action]}`,
41
+ }));
42
+
43
+ const selectedSet = new Set<number>();
44
+ sorted.forEach((finding, index) => {
45
+ if (finding.severity === "high" && finding.confidence !== "low") selectedSet.add(index);
46
+ });
47
+
48
+ const maxVisible = 8;
49
+ let cursorPos = 0;
50
+ const getStartIndex = (selectedIndex: number) =>
51
+ Math.max(0, Math.min(selectedIndex - Math.floor(maxVisible / 2), sorted.length - maxVisible));
52
+
53
+ const result = await ctx.ui.custom<CodeSmellFinding[]>((tui, theme, keybindings, done) => {
54
+ const updateListLabel = (index: number) => {
55
+ const item = listItems[index];
56
+ const finding = sorted[index];
57
+ const checkbox = selectedSet.has(index) ? "[x]" : "[ ]";
58
+ const location = finding.lines ? `${finding.file}:${finding.lines}` : finding.file;
59
+ item.label = `${checkbox} ${location}`;
60
+ };
61
+ const updateAll = () => listItems.forEach((_item, index) => updateListLabel(index));
62
+ updateAll();
63
+
64
+ const selectList = new SelectList(listItems, maxVisible, getSelectListTheme());
65
+ selectList.onSelectionChange = (item) => {
66
+ cursorPos = Number(item.value);
67
+ };
68
+ selectList.onCancel = () => done([]);
69
+
70
+ const toggleCurrent = () => {
71
+ if (selectedSet.has(cursorPos)) selectedSet.delete(cursorPos);
72
+ else selectedSet.add(cursorPos);
73
+ updateListLabel(cursorPos);
74
+ tui.requestRender();
75
+ };
76
+
77
+ const toggleAll = () => {
78
+ if (selectedSet.size === sorted.length) selectedSet.clear();
79
+ else for (let i = 0; i < sorted.length; i++) selectedSet.add(i);
80
+ updateAll();
81
+ tui.requestRender();
82
+ };
83
+
84
+ return {
85
+ render(width: number) {
86
+ selectList.setSelectedIndex(cursorPos);
87
+ const lines: string[] = [];
88
+ lines.push(theme.bold("Code Smell: Select findings to clean"));
89
+ lines.push(theme.fg("muted", `Found ${findings.length} findings`));
90
+ lines.push("");
91
+
92
+ const listLines = selectList.render(width);
93
+ const selectedLineIndex = cursorPos - getStartIndex(cursorPos);
94
+ const current = sorted[cursorPos];
95
+ for (const [lineIndex, line] of listLines.entries()) {
96
+ lines.push(line);
97
+ if (lineIndex !== selectedLineIndex || !current) continue;
98
+
99
+ const detailIndent = " ";
100
+ const detailPrefix = `${detailIndent}│ `;
101
+ const wrapWidth = Math.max(1, width - detailPrefix.length);
102
+ const pushSection = (heading: string, body: string) => {
103
+ if (!body) return;
104
+ lines.push(theme.fg("borderMuted", `${detailIndent}┌─ ${heading}`));
105
+ lines.push(
106
+ ...wrapTextWithAnsi(body, wrapWidth).map((wrappedLine) =>
107
+ theme.fg("muted", `${detailPrefix}${wrappedLine}`),
108
+ ),
109
+ );
110
+ };
111
+
112
+ pushSection("Smell", current.smell);
113
+ pushSection("Evidence", current.evidence);
114
+ pushSection("Impact", current.impact);
115
+ pushSection("Recommendation", current.recommendation);
116
+ lines.push(theme.fg("muted", `${detailPrefix}Category: ${current.category}`));
117
+ lines.push(theme.fg("muted", `${detailPrefix}Action: ${ACTION_LABEL[current.action]}`));
118
+ lines.push(
119
+ theme.fg("borderMuted", `${detailIndent}└─ ${rawKeyHint("space", "selects this fix")}`),
120
+ );
121
+ }
122
+
123
+ lines.push("");
124
+ lines.push(
125
+ theme.fg(
126
+ "muted",
127
+ [
128
+ `Selected: ${selectedSet.size}`,
129
+ rawKeyHint("↑↓", "navigate"),
130
+ rawKeyHint("space", "toggle"),
131
+ rawKeyHint("a", "select all"),
132
+ keyHint("tui.select.confirm", "confirm"),
133
+ keyHint("tui.select.cancel", "cancel"),
134
+ ].join(" • "),
135
+ ),
136
+ );
137
+ return lines;
138
+ },
139
+ invalidate() {
140
+ selectList.invalidate();
141
+ },
142
+ handleInput(data: string) {
143
+ if (keybindings.matches(data, "tui.select.confirm")) {
144
+ return done(Array.from(selectedSet).map((i) => sorted[i]));
145
+ }
146
+ if (keybindings.matches(data, "tui.select.cancel")) return done([]);
147
+ if (matchesKey(data, "space")) return toggleCurrent();
148
+ if (matchesKey(data, "a")) return toggleAll();
149
+ const previous = cursorPos;
150
+ selectList.handleInput(data);
151
+ if (cursorPos !== previous) tui.requestRender();
152
+ },
153
+ };
154
+ });
155
+
156
+ return result ?? [];
157
+ }
@@ -0,0 +1,36 @@
1
+ export type SmellCategory =
2
+ | "complexity"
3
+ | "duplication"
4
+ | "coupling"
5
+ | "state"
6
+ | "errors"
7
+ | "performance"
8
+ | "maintainability";
9
+
10
+ export type SmellSeverity = "low" | "medium" | "high";
11
+ export type SmellConfidence = "low" | "medium" | "high";
12
+ export type SmellAction = "inspect" | "delete" | "inline" | "extract" | "refactor" | "guard";
13
+
14
+ export type CodeSmellFinding = {
15
+ category: SmellCategory;
16
+ severity: SmellSeverity;
17
+ confidence: SmellConfidence;
18
+ file: string;
19
+ lines: string;
20
+ smell: string;
21
+ evidence: string;
22
+ impact: string;
23
+ recommendation: string;
24
+ action: SmellAction;
25
+ };
26
+
27
+ export type ProgrammaticCheck = {
28
+ id: string;
29
+ title: string;
30
+ category: SmellCategory;
31
+ severity: SmellSeverity;
32
+ file: string;
33
+ lines: string;
34
+ evidence: string;
35
+ recommendation: string;
36
+ };
@@ -0,0 +1,334 @@
1
+ import {
2
+ defineTool,
3
+ DynamicBorder,
4
+ getSelectListTheme,
5
+ keyHint,
6
+ type ExtensionAPI,
7
+ type ExtensionCommandContext,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { Container, SelectList, Text, type SelectItem } from "@earendil-works/pi-tui";
10
+ import { Type } from "typebox";
11
+
12
+ import { runProgrammaticChecks } from "./checks.js";
13
+ import { CODE_SMELL_PROMPT } from "./prompt.js";
14
+ import { showFindingSelector } from "./selector.js";
15
+ import type { CodeSmellFinding } from "./types.js";
16
+
17
+ const categorySchema = Type.Union([
18
+ Type.Literal("complexity"),
19
+ Type.Literal("duplication"),
20
+ Type.Literal("coupling"),
21
+ Type.Literal("state"),
22
+ Type.Literal("errors"),
23
+ Type.Literal("performance"),
24
+ Type.Literal("maintainability"),
25
+ ]);
26
+ const severitySchema = Type.Union([
27
+ Type.Literal("low"),
28
+ Type.Literal("medium"),
29
+ Type.Literal("high"),
30
+ ]);
31
+ const confidenceSchema = Type.Union([
32
+ Type.Literal("low"),
33
+ Type.Literal("medium"),
34
+ Type.Literal("high"),
35
+ ]);
36
+ const actionSchema = Type.Union([
37
+ Type.Literal("inspect"),
38
+ Type.Literal("delete"),
39
+ Type.Literal("inline"),
40
+ Type.Literal("extract"),
41
+ Type.Literal("refactor"),
42
+ Type.Literal("guard"),
43
+ ]);
44
+
45
+ type Target = { paths: string[] };
46
+
47
+ function parsePaths(value: string): string[] {
48
+ return value
49
+ .split(/\s+/)
50
+ .map((item) => item.trim())
51
+ .filter((item) => item.length > 0);
52
+ }
53
+
54
+ async function showPathInput(ctx: ExtensionCommandContext): Promise<Target | null> {
55
+ const result = await ctx.ui.editor(
56
+ "Enter folders/files to scan (space-separated or one per line):",
57
+ ".",
58
+ );
59
+ const paths = parsePaths(result ?? "");
60
+ return paths.length > 0 ? { paths } : null;
61
+ }
62
+
63
+ async function showTargetSelector(ctx: ExtensionCommandContext): Promise<Target | null> {
64
+ const items: SelectItem[] = [
65
+ { value: "repo", label: "Scan repository", description: "Programmatic checks + agent review" },
66
+ { value: "paths", label: "Scan selected paths", description: "Folders/files only" },
67
+ ];
68
+
69
+ const result = await ctx.ui.custom<"repo" | "paths" | null>((tui, theme, _kb, done) => {
70
+ const container = new Container();
71
+ container.addChild(new DynamicBorder((str) => theme.fg("accent", str)));
72
+ container.addChild(new Text(theme.fg("accent", theme.bold("Select code smell scope"))));
73
+ const selectList = new SelectList(items, 6, getSelectListTheme());
74
+ selectList.onSelect = (item) => done(item.value as "repo" | "paths");
75
+ selectList.onCancel = () => done(null);
76
+ container.addChild(selectList);
77
+ container.addChild(
78
+ new Text(
79
+ `${keyHint("tui.select.confirm", "confirm")} ${keyHint("tui.select.cancel", "cancel")}`,
80
+ ),
81
+ );
82
+ container.addChild(new DynamicBorder((str) => theme.fg("accent", str)));
83
+ return {
84
+ render(width: number) {
85
+ return container.render(width);
86
+ },
87
+ invalidate() {
88
+ container.invalidate();
89
+ },
90
+ handleInput(data: string) {
91
+ selectList.handleInput(data);
92
+ tui.requestRender();
93
+ },
94
+ };
95
+ });
96
+
97
+ if (!result) return null;
98
+ if (result === "repo") return { paths: ["."] };
99
+ return showPathInput(ctx);
100
+ }
101
+
102
+ function registerScanTool(pi: ExtensionAPI) {
103
+ pi.registerTool(
104
+ defineTool({
105
+ name: "code_smell_scan",
106
+ label: "Code Smell Scan",
107
+ description: "Run programmatic code smell checks over repository paths.",
108
+ promptSnippet:
109
+ "Run deterministic checks for debug remnants, commented-out code, duplication, and complex functions",
110
+ promptGuidelines: [
111
+ "Use code_smell_scan before manual code smell review, then verify important findings by reading files.",
112
+ ],
113
+ parameters: Type.Object({
114
+ paths: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
115
+ maxFiles: Type.Optional(Type.Number({ minimum: 1, maximum: 1000 })),
116
+ }),
117
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
118
+ const findings = await runProgrammaticChecks({
119
+ cwd: ctx.cwd,
120
+ paths: params.paths ?? ["."],
121
+ maxFiles: params.maxFiles,
122
+ });
123
+ const bySeverity = {
124
+ high: findings.filter((f) => f.severity === "high").length,
125
+ medium: findings.filter((f) => f.severity === "medium").length,
126
+ low: findings.filter((f) => f.severity === "low").length,
127
+ };
128
+ return {
129
+ content: [
130
+ {
131
+ type: "text" as const,
132
+ text: `Found ${findings.length} programmatic code-smell leads.`,
133
+ },
134
+ ],
135
+ details: { findings, bySeverity },
136
+ };
137
+ },
138
+ }),
139
+ );
140
+ }
141
+
142
+ function registerFindingsTool(
143
+ pi: ExtensionAPI,
144
+ state: {
145
+ getResolver: () => ((findings: CodeSmellFinding[]) => void) | null;
146
+ clearResolver: () => void;
147
+ setLatestFindings: (findings: CodeSmellFinding[]) => void;
148
+ },
149
+ ) {
150
+ pi.registerTool(
151
+ defineTool({
152
+ name: "code_smell_findings",
153
+ label: "Code Smell Findings",
154
+ description:
155
+ "Return the complete finding list for /code-smell. Use as the final action after analysis.",
156
+ promptSnippet:
157
+ "Return structured code smell findings for /code-smell as a terminating result",
158
+ promptGuidelines: [
159
+ "Use code_smell_findings exactly once as the final action when the /code-smell command asks for findings.",
160
+ ],
161
+ parameters: Type.Object({
162
+ findings: Type.Array(
163
+ Type.Object({
164
+ category: categorySchema,
165
+ severity: severitySchema,
166
+ confidence: confidenceSchema,
167
+ file: Type.String({ minLength: 1, pattern: "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$" }),
168
+ lines: Type.String(),
169
+ smell: Type.String({ minLength: 1 }),
170
+ evidence: Type.String({ minLength: 1 }),
171
+ impact: Type.String({ minLength: 1 }),
172
+ recommendation: Type.String({ minLength: 1 }),
173
+ action: actionSchema,
174
+ }),
175
+ ),
176
+ }),
177
+ async execute(_toolCallId, params) {
178
+ const findings: CodeSmellFinding[] = params.findings;
179
+ const resolve = state.getResolver();
180
+ if (!resolve) {
181
+ return {
182
+ content: [
183
+ {
184
+ type: "text" as const,
185
+ text: "Ignored code smell findings because no /code-smell analysis is pending.",
186
+ },
187
+ ],
188
+ details: { ignored: true, findings: [] },
189
+ terminate: true,
190
+ };
191
+ }
192
+ state.setLatestFindings(findings);
193
+ state.clearResolver();
194
+ resolve(findings);
195
+ return {
196
+ content: [
197
+ { type: "text" as const, text: `Captured ${findings.length} code smell findings.` },
198
+ ],
199
+ details: { ignored: false, findings },
200
+ terminate: true,
201
+ };
202
+ },
203
+ }),
204
+ );
205
+ }
206
+
207
+ function buildPrompt(target: Target, focus?: string): string {
208
+ let prompt = CODE_SMELL_PROMPT;
209
+ const isRepoRoot = target.paths.length === 1 && target.paths[0] === ".";
210
+ if (!isRepoRoot)
211
+ prompt += `\n\n## Scope\n\nReview only these repository-relative paths: ${target.paths.join(", ")}.`;
212
+ if (focus?.trim()) prompt += `\n\n## Additional Focus\n\n${focus.trim()}`;
213
+ return prompt;
214
+ }
215
+
216
+ async function applyFindings(
217
+ ctx: ExtensionCommandContext,
218
+ selected: CodeSmellFinding[],
219
+ pi: ExtensionAPI,
220
+ ) {
221
+ if (selected.length === 0) {
222
+ ctx.ui.notify("No code smell findings selected", "info");
223
+ return;
224
+ }
225
+
226
+ const prompt = `# Clean Selected Code Smells\n\nApply small, behavior-preserving fixes for these selected findings:\n\n${selected
227
+ .map(
228
+ (f) =>
229
+ `- ${f.file} (${f.lines || "?"}) [${f.action}] ${f.category}/${f.severity}\n - Smell: ${f.smell}\n - Evidence: ${f.evidence}\n - Recommendation: ${f.recommendation}`,
230
+ )
231
+ .join(
232
+ "\n",
233
+ )}\n\nRules:\n1. Read each file before editing.\n2. Keep changes minimal and behavior-preserving.\n3. Skip any item whose fix is ambiguous and report why.\n4. Run relevant tests/type-check/lint after changes.\n5. Report changed files and verification output.`;
234
+
235
+ ctx.ui.notify(`Applying ${selected.length} selected code smell fixes`, "info");
236
+ pi.sendUserMessage(prompt);
237
+ }
238
+
239
+ export function registerCodeSmellWorkflow(pi: ExtensionAPI) {
240
+ let resolvePendingTurnStart: (() => void) | null = null;
241
+ let resolvePendingFindingsTool: ((findings: CodeSmellFinding[]) => void) | null = null;
242
+ let latestToolFindings: CodeSmellFinding[] | null = null;
243
+
244
+ pi.on("turn_start", () => {
245
+ if (!resolvePendingTurnStart) return;
246
+ const resolve = resolvePendingTurnStart;
247
+ resolvePendingTurnStart = null;
248
+ resolve();
249
+ });
250
+
251
+ registerScanTool(pi);
252
+ registerFindingsTool(pi, {
253
+ getResolver: () => resolvePendingFindingsTool,
254
+ clearResolver: () => {
255
+ resolvePendingFindingsTool = null;
256
+ },
257
+ setLatestFindings: (findings) => {
258
+ latestToolFindings = findings;
259
+ },
260
+ });
261
+
262
+ pi.registerCommand("code-smell", {
263
+ description:
264
+ "Find code smells with programmatic checks and agent review, then optionally clean them",
265
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
266
+ if (!ctx.hasUI) {
267
+ ctx.ui.notify("Code smell workflow requires interactive mode", "error");
268
+ return;
269
+ }
270
+ if (!ctx.isIdle()) {
271
+ ctx.ui.notify("Cannot run code-smell while agent is busy", "warning");
272
+ return;
273
+ }
274
+
275
+ const paths = parsePaths(args);
276
+ let target: Target | null = paths.length > 0 ? { paths } : null;
277
+ if (!target) target = await showTargetSelector(ctx);
278
+ if (!target) {
279
+ ctx.ui.notify("Code smell scan cancelled", "info");
280
+ return;
281
+ }
282
+
283
+ latestToolFindings = null;
284
+ const turnStarted = new Promise<void>((r) => {
285
+ resolvePendingTurnStart = r;
286
+ });
287
+ const toolResult = new Promise<CodeSmellFinding[]>((r) => {
288
+ resolvePendingFindingsTool = r;
289
+ });
290
+
291
+ ctx.ui.notify(`Analyzing code smells in ${target.paths.join(", ")}`, "info");
292
+ pi.sendUserMessage(buildPrompt(target));
293
+
294
+ const started = await Promise.race<boolean>([
295
+ turnStarted.then(() => true),
296
+ new Promise<boolean>((r) => setTimeout(() => r(false), 10000)),
297
+ ]);
298
+ if (!started) {
299
+ resolvePendingTurnStart = null;
300
+ resolvePendingFindingsTool = null;
301
+ ctx.ui.notify("Analysis did not start within 10 seconds", "warning");
302
+ return;
303
+ }
304
+
305
+ await ctx.waitForIdle();
306
+ const findings =
307
+ latestToolFindings ??
308
+ (await Promise.race<CodeSmellFinding[] | null>([
309
+ toolResult,
310
+ new Promise<null>((r) => setTimeout(() => r(null), 100)),
311
+ ]));
312
+ resolvePendingFindingsTool = null;
313
+
314
+ if (findings === null) {
315
+ ctx.ui.notify(
316
+ "Could not read findings — model did not call code_smell_findings",
317
+ "warning",
318
+ );
319
+ return;
320
+ }
321
+ if (findings.length === 0) {
322
+ ctx.ui.notify("No code smells found", "info");
323
+ return;
324
+ }
325
+
326
+ const selected = await showFindingSelector(ctx, findings);
327
+ if (!selected || selected.length === 0) {
328
+ ctx.ui.notify("Code smell cleanup cancelled", "info");
329
+ return;
330
+ }
331
+ await applyFindings(ctx, selected, pi);
332
+ },
333
+ });
334
+ }
@@ -25,8 +25,15 @@ Before flagging, **search the codebase** (utility directories, shared modules, f
25
25
  #### B3. Commented-out Code (Review)
26
26
  - Old logic left in comments, disabled features, uncustomized templates
27
27
 
28
- #### B4. Over-engineering (Confirm)
28
+ #### B4. Over-engineering / Thin Wrappers (Confirm)
29
29
  - Abstractions created "for future use" but unused, single-call-site helpers that should be inlined, useless indirection
30
+ - Thin wrappers that only rename another function or constructor without adding validation, policy, error handling, logging, or a stable public boundary
31
+ - Platform-specific wrapper modules that merely re-export generic session/config helpers under different names
32
+ - Method wrappers on classes that only delegate to a free function already available to callers
33
+ - Test-only exported helpers that can use the real internal/public helper directly instead
34
+ - Small formatting/command helpers whose name repeats a one-line call and have only one call site
35
+
36
+ **Thin-wrapper discipline:** prefer deleting the wrapper and calling the underlying primitive directly when the wrapper has no independent semantic responsibility. Keep the wrapper if it protects a public API, documents a domain boundary, centralizes cross-cutting behavior, or isolates an unstable dependency.
30
37
 
31
38
  #### B5. Hacky Patterns (Confirm)
32
39
  - **Redundant state**: state that duplicates other state, cached values that could be derived, observers that could be direct calls
@@ -57,6 +64,20 @@ Before flagging, **search the codebase** (utility directories, shared modules, f
57
64
  - Assign **category** (reuse / quality / efficiency) and **risk**
58
65
  - State the concrete fix (which existing utility to call, which lines to delete, how to parallelize, etc.)
59
66
 
67
+ ## Thin Wrapper Review Heuristics
68
+
69
+ When hunting simplification opportunities, explicitly scan for these patterns:
70
+
71
+ - **Rename-only wrapper:** \`foo()\` only calls \`bar()\` with the same inputs. Inline \`bar()\` unless \`foo\` is a real public/domain concept.
72
+ - **Constructor/factory wrapper:** \`createX(args)\` only returns \`new X(args)\`. Inline construction unless the factory selects implementations or enforces policy.
73
+ - **Scope-specific alias:** \`SlackThing\`/\`ConversationThing\` only wraps a generic helper. Delete it if the generic name is already clear at call sites.
74
+ - **Single-call-site helper:** a helper with one caller and no meaningful name compression. Inline it, especially for one-line formatting, parsing, or path helpers.
75
+ - **Duplicated write APIs:** several \`saveFooConfig\` functions patch different fields in the same file. Consolidate into one \`updateSettings(patch)\`-style API.
76
+ - **Test-only export:** exported solely so tests can call a thin wrapper. Test the underlying public helper or observable behavior instead.
77
+ - **Pass-through class method:** a class method only delegates to a module-level function and is not required by an interface. Remove the method or call the function directly.
78
+
79
+ Do **not** flag wrappers whose consequence is only "one extra line". Flag them when they create a real maintenance cost: multiple ways to do the same operation, unclear source of truth, misleading domain boundaries, duplicated tests for delegated behavior, or user/developer uncertainty about which API is authoritative.
80
+
60
81
  ## Risk Levels
61
82
 
62
83
  - **safe**: Definitely apply (dead code, debug remnants)
package/tsconfig.json CHANGED
@@ -6,6 +6,7 @@
6
6
  "strict": true,
7
7
  "esModuleInterop": true,
8
8
  "skipLibCheck": true,
9
- "outDir": "dist"
9
+ "outDir": "dist",
10
+ "rootDir": "."
10
11
  }
11
12
  }
File without changes
File without changes
File without changes