@a2f0/agent-tool 0.1.83 → 0.1.85

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.
@@ -0,0 +1,287 @@
1
+ /**
2
+ * `agent-tool deslop`: ranks tracked source files by structural simplification
3
+ * leads (duplicated blocks, parametric clones, oversized files, long functions,
4
+ * suppression clusters, thin-wrapper cascades, and single-caller micro-files)
5
+ * and optional directory hotspots (`--by-dir`). Read-only; it points a person
6
+ * or agent at files worth inspecting and never edits anything.
7
+ */
8
+ import { lstatSync, realpathSync, writeSync } from "node:fs";
9
+ import path from "node:path";
10
+ import { isolatedGit, toplevel } from "../system/checkouts";
11
+ import { readRegularFile } from "../system/files";
12
+ import {
13
+ type DeslopDirectoryReport,
14
+ type DeslopFileReport,
15
+ type DuplicateCluster,
16
+ isGeneratedSource,
17
+ MAX_BYTES,
18
+ type ScannedSource,
19
+ scanSources,
20
+ sourceLanguage,
21
+ } from "./scan";
22
+
23
+ export interface DeslopOptions {
24
+ readonly names: string[];
25
+ readonly json: boolean;
26
+ readonly limit: number;
27
+ readonly minScore: number;
28
+ readonly includeTests: boolean;
29
+ readonly byDir: boolean;
30
+ }
31
+
32
+ export interface DeslopRepoReport {
33
+ readonly name: string;
34
+ readonly root: string;
35
+ readonly scanned: number;
36
+ readonly files: DeslopFileReport[];
37
+ readonly more: number;
38
+ readonly duplicates: DuplicateCluster[];
39
+ readonly parametricDuplicates: DuplicateCluster[];
40
+ readonly directories?: DeslopDirectoryReport[];
41
+ readonly moreDirectories?: number;
42
+ readonly error?: string;
43
+ }
44
+
45
+ export interface DeslopTarget {
46
+ readonly name: string;
47
+ readonly root: string;
48
+ }
49
+
50
+ export const USAGE = `Usage: agent-tool deslop [path...] [--limit N] [--min-score N] [--include-tests] [--by-dir] [--json]
51
+
52
+ Ranks tracked source files by simplification leads: duplicated code blocks,
53
+ parametric clones, oversized files, long functions, lint/type suppression
54
+ clusters, exported thin-wrapper cascades, and single-caller micro-files.
55
+ Read-only. Scans the repository holding the working directory, or the
56
+ repository holding each named path.
57
+
58
+ --limit N files, directories, and clone clusters listed per repository (default 25; 0 lists all)
59
+ --min-score N skip files scoring below N (default 3)
60
+ --include-tests include test and fixture files (skipped by default)
61
+ --by-dir include directory-level hotspot rankings and test/source ratios
62
+ --json JSON output for agents`;
63
+
64
+ function count(flag: string, value: string | undefined): number {
65
+ if (value === undefined || value.startsWith("--")) throw new Error(`${flag} needs a value.`);
66
+ if (!/^\d+$/.test(value)) throw new Error(`${flag} must be a non-negative integer.`);
67
+ return Number(value);
68
+ }
69
+
70
+ export function parseOptions(argv: string[]): DeslopOptions {
71
+ const names: string[] = [];
72
+ let json = false;
73
+ let limit = 25;
74
+ let minScore = 3;
75
+ let includeTests = false;
76
+ let byDir = false;
77
+ for (let index = 0; index < argv.length; index++) {
78
+ const arg = argv[index]!;
79
+ if (arg === "--json") json = true;
80
+ else if (arg === "--include-tests") includeTests = true;
81
+ else if (arg === "--by-dir") byDir = true;
82
+ else if (arg === "--limit") limit = count(arg, argv[++index]);
83
+ else if (arg === "--min-score") minScore = count(arg, argv[++index]);
84
+ else if (arg.startsWith("-")) throw new Error(`Unknown option ${arg}.`);
85
+ else names.push(arg);
86
+ }
87
+ return { names, json, limit, minScore, includeTests, byDir };
88
+ }
89
+
90
+ /**
91
+ * Repositories to scan: the one holding `cwd`, or the one holding each named
92
+ * path (relative to `invoked`), deduplicated by real root.
93
+ */
94
+ export function resolveTargets(cwd: string, names: string[], invoked = cwd): DeslopTarget[] {
95
+ if (names.length === 0) {
96
+ const here = toplevel(cwd);
97
+ if (!here) throw new Error(`${cwd} is not inside a git repository; name one`);
98
+ const real = realpathSync(here);
99
+ return [{ name: path.basename(real), root: real }];
100
+ }
101
+ const roots = names.map(name => {
102
+ const full = path.resolve(invoked, name);
103
+ const top = toplevel(full);
104
+ if (!top) throw new Error(`${name} is not a path inside a git repository`);
105
+ return realpathSync(top);
106
+ });
107
+ return [...new Set(roots)].map(root => ({ name: path.basename(root), root }));
108
+ }
109
+
110
+ /**
111
+ * Reads a tracked file only when neither it nor any parent inside `root` is a
112
+ * symlink, its size is bounded, and it stays inside `realRoot`.
113
+ */
114
+ export function readInside(realRoot: string, file: string): string | undefined {
115
+ if (file.split(/[\\/]/).includes("..")) return undefined;
116
+ const full = path.join(realRoot, file);
117
+ try {
118
+ const stat = lstatSync(full);
119
+ if (!stat.isFile() || stat.size > MAX_BYTES) return undefined;
120
+ const real = realpathSync(full);
121
+ if (real !== path.join(realRoot, path.normalize(file))) return undefined;
122
+ const read = readRegularFile(real);
123
+ if (read.status !== "file" || read.contents.length > MAX_BYTES || read.contents.includes("\u0000")) return undefined;
124
+ return read.contents;
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ }
129
+
130
+ /** Scans tracked source files in one repository without editing anything. */
131
+ export function scanRepository(
132
+ name: string,
133
+ root: string,
134
+ options: Pick<DeslopOptions, "limit" | "minScore" | "includeTests"> & Partial<Pick<DeslopOptions, "byDir">>,
135
+ ): DeslopRepoReport {
136
+ const listed = isolatedGit(root, ["ls-files", "-z", "--cached"]);
137
+ if (listed.status !== 0) {
138
+ return {
139
+ name,
140
+ root,
141
+ scanned: 0,
142
+ files: [],
143
+ more: 0,
144
+ duplicates: [],
145
+ parametricDuplicates: [],
146
+ error: "git ls-files failed",
147
+ };
148
+ }
149
+ let realRoot: string;
150
+ try {
151
+ realRoot = realpathSync(root);
152
+ } catch {
153
+ return {
154
+ name,
155
+ root,
156
+ scanned: 0,
157
+ files: [],
158
+ more: 0,
159
+ duplicates: [],
160
+ parametricDuplicates: [],
161
+ error: "repository path is unreadable",
162
+ };
163
+ }
164
+
165
+ const sources: ScannedSource[] = [];
166
+ for (const file of listed.stdout.split("\0")) {
167
+ if (!file) continue;
168
+ const initial = sourceLanguage(file, undefined, options.includeTests);
169
+ if (!initial) continue;
170
+ const text = readInside(realRoot, file);
171
+ if (text === undefined || isGeneratedSource(text)) continue;
172
+ const syntax = initial === "maybe" ? sourceLanguage(file, text.split("\n", 1)[0], options.includeTests) : initial;
173
+ if (!syntax || syntax === "maybe") continue;
174
+ sources.push({ path: file, text, syntax });
175
+ }
176
+
177
+ const { files, duplicates, parametricDuplicates, directories } = scanSources(sources, options.minScore, options.includeTests);
178
+ const shownFiles = options.limit === 0 ? files : files.slice(0, options.limit);
179
+ const shownDuplicates = options.limit === 0 ? duplicates : duplicates.slice(0, options.limit);
180
+ const shownParametric = options.limit === 0 ? parametricDuplicates : parametricDuplicates.slice(0, options.limit);
181
+ const shownDirectories = options.byDir
182
+ ? (options.limit === 0 ? directories : directories.slice(0, options.limit))
183
+ : undefined;
184
+ return {
185
+ name,
186
+ root,
187
+ scanned: sources.length,
188
+ files: shownFiles,
189
+ more: files.length - shownFiles.length,
190
+ duplicates: shownDuplicates,
191
+ parametricDuplicates: shownParametric,
192
+ ...(shownDirectories
193
+ ? { directories: shownDirectories, moreDirectories: directories.length - shownDirectories.length }
194
+ : {}),
195
+ };
196
+ }
197
+
198
+ function describeSignal(signal: DeslopFileReport["signals"][number]): string {
199
+ const lines = signal.lines.slice(0, 6).join(",") + (signal.lines.length > 6 ? ",..." : "");
200
+ switch (signal.kind) {
201
+ case "duplicate-block":
202
+ return ` duplicate-block ${signal.count} lines with ${signal.details?.join(", ") ?? ""}`;
203
+ case "parametric-clone":
204
+ return ` parametric-clone ${signal.count} lines with ${signal.details?.join(", ") ?? ""}`;
205
+ case "oversized-file":
206
+ return ` oversized-file ${signal.count} code lines`;
207
+ case "long-function":
208
+ return ` long-function ${signal.details?.join(", ") ?? `${signal.count} functions`} (lines ${lines})`;
209
+ case "suppressions":
210
+ return ` suppressions ${signal.count} directives (lines ${lines})`;
211
+ case "thin-wrapper":
212
+ return ` thin-wrapper ${signal.details?.join(", ") ?? `${signal.count} wrappers`} (lines ${lines})`;
213
+ case "micro-file":
214
+ return ` micro-file ${signal.details?.[0] ?? `${signal.count} code lines`}`;
215
+ }
216
+ }
217
+
218
+ function renderDirectoryRow(dir: DeslopDirectoryReport): string {
219
+ const ratio = dir.testRatio === null
220
+ ? (dir.testLines > 0 ? "test-only" : "-")
221
+ : `${Math.round(dir.testRatio * 100)}%`;
222
+ const dup = dir.duplicateLines + dir.parametricLines;
223
+ const micro = dir.microFiles > 0 ? ` micro:${dir.microFiles}` : "";
224
+ return ` ${dir.totalScore.toString().padStart(4)} src:${dir.sourceLines.toString().padStart(6)} (${dir.sourceFiles}f) test:${dir.testLines.toString().padStart(6)} (${dir.testFiles}f) ratio:${ratio.padStart(9)} dup:${dup.toString().padStart(5)}${micro} ${dir.directory}`;
225
+ }
226
+
227
+ export function render(reports: DeslopRepoReport[]): string {
228
+ const out: string[] = [];
229
+ for (const repo of reports) {
230
+ out.push(`${repo.name} (${repo.root}): ${repo.error ?? `${repo.files.length + repo.more} candidate files of ${repo.scanned} scanned`}`);
231
+ if (repo.directories && repo.directories.length > 0) {
232
+ out.push(" Directory hotspots:");
233
+ for (const dir of repo.directories) out.push(renderDirectoryRow(dir));
234
+ if (repo.moreDirectories) out.push(` ... ${repo.moreDirectories} more directories (raise --limit)`);
235
+ }
236
+ for (const file of repo.files) {
237
+ out.push(` ${file.score.toString().padStart(3)} ${file.path}`, ...file.signals.map(describeSignal));
238
+ }
239
+ if (repo.more) out.push(` ... ${repo.more} more (raise --limit)`);
240
+ if (repo.duplicates.length > 0) {
241
+ out.push(" Top duplicate blocks:");
242
+ for (const cluster of repo.duplicates) {
243
+ const locs = cluster.locations.map(loc => `${loc.path}:${loc.start}-${loc.end}`).join(" <-> ");
244
+ out.push(` ${cluster.lines.toString().padStart(3)} lines ${locs}`);
245
+ }
246
+ }
247
+ if (repo.parametricDuplicates.length > 0) {
248
+ out.push(" Top parametric clones:");
249
+ for (const cluster of repo.parametricDuplicates) {
250
+ const locs = cluster.locations.map(loc => `${loc.path}:${loc.start}-${loc.end}`).join(" <-> ");
251
+ out.push(` ${cluster.lines.toString().padStart(3)} lines ${locs}`);
252
+ }
253
+ }
254
+ }
255
+ out.push("", "Candidates are leads, not findings: read each file and apply the deslopify-refactor skill before changing it.");
256
+ return out.join("\n");
257
+ }
258
+
259
+ /** Exit status: 0, 1 when a repository could not be listed, 2 for usage errors. */
260
+ export function deslopCommand(
261
+ argv: string[],
262
+ cwd = process.cwd(),
263
+ print: (text: string) => void = text => { writeSync(1, `${text}\n`); },
264
+ invoked = cwd,
265
+ ): number {
266
+ if (argv.includes("--help") || argv.includes("-h")) {
267
+ print(USAGE);
268
+ return 0;
269
+ }
270
+ let options: DeslopOptions;
271
+ try {
272
+ options = parseOptions(argv);
273
+ } catch (error) {
274
+ print(`${(error as Error).message}\n\n${USAGE}`);
275
+ return 2;
276
+ }
277
+ let targets: DeslopTarget[];
278
+ try {
279
+ targets = resolveTargets(cwd, options.names, invoked);
280
+ } catch (error) {
281
+ print((error as Error).message);
282
+ return 2;
283
+ }
284
+ const reports = targets.map(target => scanRepository(target.name, target.root, options));
285
+ print(options.json ? JSON.stringify({ repos: reports }, null, 2) : render(reports));
286
+ return reports.some(report => report.error) ? 1 : 0;
287
+ }