@a2f0/agent-tool 0.1.84 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.84",
3
+ "version": "0.1.85",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -31,14 +31,21 @@ to trace or couples unrelated domains adds slop instead of removing it.
31
31
 
32
32
  Start with `agent-tool deslop` (read-only):
33
33
 
34
- - `agent-tool deslop [path...] [--limit N] [--min-score N] [--include-tests] [--json]`
34
+ - `agent-tool deslop [path...] [--limit N] [--min-score N] [--include-tests] [--by-dir] [--json]`
35
35
  ranks tracked source files in the repository holding the working directory, or
36
- each named path's repository, by five signals: duplicated multi-line code
37
- blocks (`duplicate-block`), oversized files (`oversized-file`), long functions
38
- (`long-function`), lint/type suppression clusters (`suppressions`), and
39
- exported pass-through wrapper cascades (`thin-wrapper`).
40
- - Pass `--include-tests` when auditing test-suite and fixture duplication.
41
- - If the repository's pinned agent-tool lacks the command, run
36
+ each named path's repository, by seven signals: duplicated multi-line code
37
+ blocks (`duplicate-block`), structurally identical blocks with renamed
38
+ identifiers/literals (`parametric-clone`), oversized files (`oversized-file`),
39
+ long functions (`long-function`), lint/type suppression clusters
40
+ (`suppressions`), exported pass-through wrapper cascades (`thin-wrapper`), and
41
+ single-caller micro-files or non-index re-export shims (`micro-file`).
42
+ - Run `agent-tool deslop --by-dir --include-tests` first on any large repository
43
+ or monorepo to see directory-level duplication hotspots, test-to-source ratios,
44
+ and micro-file clusters before choosing slices.
45
+ - Pass `--include-tests` as a first-class phase, not an afterthought: test
46
+ helpers, copy-pasted fixtures, and overlapping test files are often the
47
+ largest, lowest-production-risk simplification targets in agent-built codebases.
48
+ - If the repository's pinned agent-tool lacks the command or flags, run
42
49
  `bunx --bun @a2f0/agent-tool@latest deslop`.
43
50
 
44
51
  The scanner finds leads, not verdicts. Pair it with the repository's existing
@@ -113,21 +120,69 @@ not re-propose it.
113
120
  `dist`) before trusting downstream tests. If behavior changed unintentionally,
114
121
  revert the candidate.
115
122
 
123
+ ## Test-suite and fixture consolidation phase
124
+
125
+ Treat `--include-tests` as a first-class simplification phase whenever a
126
+ repository has heavy test volume, high test-to-source ratios in `--by-dir`, or
127
+ large `test/helpers` directories:
128
+
129
+ 1. Survey test hotspots with `agent-tool deslop --by-dir --include-tests --json`.
130
+ 2. Target three high-yield, low-production-risk levers:
131
+ - **Shared builders and harness factories**: replace repeated multi-line
132
+ setup blocks across sibling test files (`duplicate-block` and
133
+ `parametric-clone`) with focused, explicit fixture builders.
134
+ - **Test-helper deduplication**: collapse parallel helper modules that build
135
+ the same domain graph with minor parameter differences.
136
+ - **Redundant case consolidation**: merge or delete demonstrably duplicate
137
+ test cases that exercise the exact same path and assertions without adding
138
+ unique coverage. Never drop security refusals, race/concurrency checks,
139
+ boundary-value cases, or dialect/adapter integration tests.
140
+ 3. Prove coverage parity: run the affected test suite before and after, verify
141
+ the same edge cases and failure modes remain guarded, and ship cohesive test
142
+ cleanup slices through `ship-pr`.
143
+
144
+ ## Campaign and multi-wave mode
145
+
146
+ Keep individual PRs reviewable (roughly 600–1,200 changed lines or one cohesive
147
+ module/theme per PR), because mega-PRs hide subtle lifecycle and closure
148
+ regressions. When asked to materially shrink a large repository or monorepo,
149
+ increase **wave throughput** rather than PR size:
150
+
151
+ 1. **Rank the full backlog first**: run `agent-tool deslop --by-dir --include-tests --json`
152
+ alongside dead-code (`knip`) and architecture checks, and group leads into
153
+ disjoint directory or lens slices (test helpers, high-ratio test directories,
154
+ sibling parametric clones, over-fragmented micro-files, dead surface area).
155
+ Order slices by `estimated net LOC removed x safety`.
156
+ 2. **Partition disjoint slices per wave**: assign non-overlapping directories or
157
+ modules to parallel workers (or run consecutive waves in one session) so
158
+ branches do not conflict and each PR stays cohesive and fast to review.
159
+ 3. **Ship every slice independently**: each slice gets its own baseline,
160
+ equivalence claim, verification, independent `cross-agent-review`, and
161
+ `ship-pr` merge. Do not stop after one tiny slice when the user requested a
162
+ broad reduction — continue through planned waves until the target scope or
163
+ high-yield backlog is exhausted.
164
+ 4. **Track cumulative progress**: keep per-PR accepted/deferred records in each
165
+ PR body and record remaining campaign slices in a tracking issue (when
166
+ authorized) or summary report. Do not commit a running ledger file into the
167
+ repository.
168
+
116
169
  ## Ship and self-improve
117
170
 
118
171
  - Work on a `refactor/<topic>` branch (`fix/<topic>` for split bug fixes) and
119
172
  ship with [ship-pr](../ship-pr/SKILL.md), including independent
120
173
  [cross-agent-review](../cross-agent-review/SKILL.md). Independent review
121
174
  catches subtle lifecycle, closure, and contract regressions that tests miss.
122
- - Keep PRs reviewable: target roughly 600 changed lines or one cohesive module
123
- or theme per PR rather than sweeping an entire package in one giant diff.
175
+ - Keep PRs reviewable: target roughly 600–1,200 changed lines or one cohesive
176
+ module or theme per PR rather than sweeping an entire package in one giant
177
+ diff. Use multi-wave campaigns for larger reductions.
124
178
  - Do not commit a running ledger file (such as `.codex/deslopify-ledger.md`)
125
179
  into the repository. Put the pass record directly in the PR body:
126
180
  - Accepted simplifications (lever, equivalence claim, files, verification, net
127
181
  LOC delta).
128
182
  - Candidates inspected and left alone or deferred, with reasons.
129
183
  - For multi-PR campaigns, track the remaining backlog in a GitHub issue via
130
- [open-issue](../open-issue/SKILL.md).
184
+ [open-issue](../open-issue/SKILL.md) (when explicitly requested) or in the
185
+ campaign summary report.
131
186
  - **Make the skill self-improving**:
132
187
  - When a pass uncovers a repository-specific idiom, trap, or file-budget
133
188
  constraint, record it in that repository's `AGENTS.md` or an inline comment
@@ -5,6 +5,24 @@ PR to `a2f0/agent-tool` when a pass discovers a trap, false positive, or scanner
5
5
  improvement that future repositories need; keep repository-specific conventions
6
6
  in that repository's `AGENTS.md`.
7
7
 
8
+ ## Scale reduction with multi-wave campaigns and test-suite consolidation, not mega-PRs
9
+
10
+ In `tearleads`, keeping single PRs focused avoided regressions, but stopping
11
+ after one or two ~100-line source tweaks could not outrun feature growth in a
12
+ 1.5M-line monorepo where nearly half the code lived in tests and `test/helpers`
13
+ and exact-line scanning missed parametric sibling clones. Separate PR size from
14
+ campaign throughput: survey with `agent-tool deslop --by-dir --include-tests`,
15
+ treat test-fixture consolidation as a first-class phase, and run multi-wave
16
+ campaigns over disjoint slices so each PR stays reviewable while cumulative
17
+ reductions scale.
18
+
19
+ ## Skip multi-line import blocks when scanning for clones
20
+
21
+ Single-line `import` filters miss the inner identifier lines of multi-line
22
+ `import { ... } from ...` statements, creating noisy clone matches across
23
+ unrelated modules. `agent-tool deslop` skips complete multi-line import and
24
+ re-export blocks before computing both exact and parametric clone windows.
25
+
8
26
  ## Do not commit a running ledger into the target repository
9
27
 
10
28
  Early passes in `tearleads` maintained `.codex/deslopify-ledger.md` inside the
@@ -19,7 +37,7 @@ Splitting `tearleads` `packages/client-sdk` one module or lever per PR (20
19
37
  file-split PRs, each cleanly reviewed) landed smoothly, whereas a 258-file
20
38
  package-wide `packages/app` PR hid two infinite-render loops and two Major
21
39
  closure/scoping regressions until independent cross-agent review caught them.
22
- Aim for one theme or module (~600 lines) per PR.
40
+ Aim for one theme or module (~600–1,200 lines) per PR.
23
41
 
24
42
  ## Independent review catches subtle lifecycle and closure regressions
25
43
 
@@ -9,11 +9,12 @@ avoid false positives that introduce regressions.
9
9
  | --- | --- | --- |
10
10
  | Dead code and unreachable branches | Unused exports/files (`knip`), private branch unreachable by types and callers, dead SSR guards in browser-only code | Delete after verifying dynamic imports, routes, config, build scripts, reflection, and deployment entry points |
11
11
  | Exact copy-paste blocks | Identical multi-line logic across files (`duplicate-block`) with matching inputs, error semantics, and side effects | Extract one shared helper once evaluation order, comparator semantics, and error messages match |
12
- | Parametric duplication and boilerplate shells | Repeated envelopes (throwing context hooks, route error epilogues, storage preference loaders, transaction preambles, thin document/component shells) differing only by explicit domain inputs | Extract a thin factory or envelope where domain behavior stays explicit at call sites; never add mode flags to paper over divergence |
12
+ | Parametric and structural clones | Structurally identical blocks with renamed identifiers or literals (`parametric-clone`) across sibling modules, handlers, or tests | Extract a thin typed helper or data-driven spec where domain differences stay explicit parameters; never add mode flags to paper over divergence |
13
+ | Over-fragmented micro-files | Tiny production modules (`micro-file`) with only 1 relative JS/TS importer or non-index re-export shims adding import/file-count overhead without enforcing a layer boundary | Verify non-relative callers first (path aliases, workspace package imports, non-JS importers, generated/oversized files are outside the relative-import scan), then fold back into the sole caller or delete the re-export shim while respecting public exports, dependency-graph rules, and file-size budgets |
13
14
  | Oversized multi-concern files | God-files (`oversized-file`, `long-function`) mixing validation, mapping, persistence, and orchestration | Split along acyclic seams: map call graph, home shared types to avoid cycles, keep public re-exports stable (and import locally if the parent still calls them), or use `Pick<Interface, ...>` part-objects for large object literals while keeping self-referencing methods in the parent |
14
15
  | Non-architectural thin wrappers | Pass-through functions (`thin-wrapper`) adding no logging, metrics, error wrapping, binding, or layer boundary | Inline or remove after checking public imports, exports maps, and dependency-graph layer rules |
15
16
  | Duplicate constants and config | Same literals repeated for one domain concept | Centralize when load order, tree shaking, environment overrides, and serialization stay identical |
16
- | Test-fixture and harness slop | Huge copy-pasted fixture literals (`deslop --include-tests`), or production fallback branches kept solely for test harnesses missing a provider | Extract focused test builders and fix test harnesses to provide required context explicitly |
17
+ | Test-fixture and harness slop | High test-to-source directories (`deslop --by-dir --include-tests`), copy-pasted fixture builders (`duplicate-block` / `parametric-clone`), overlapping test cases, or production fallback branches kept solely for test harnesses missing a provider | Extract focused shared test builders, collapse redundant helper modules and duplicate assertions while keeping every unique edge/security test, and fix test harnesses to provide required context explicitly |
17
18
  | Stale task-plan comments and shims | Comments narrating past AI steps or obsolete compatibility aliases no longer referenced | Delete stale narration and dead shims while preserving rationale comments explaining non-obvious invariants |
18
19
 
19
20
  ## Medium-Risk Candidates
package/src/cli.ts CHANGED
@@ -100,8 +100,8 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
100
100
  screenshots link [repo...] [--all] [--apply] [--supersede] [--json] Point .screenshots at the shared store
101
101
  screenshots capture [repo] [--apply] [--allow-dirty] [--json] [-- args...] Run the screenshots script under the store lock and record it
102
102
  graph check Import cycles and layer violations per agent-tool.json
103
- deslop [path...] [--limit N] [--min-score N] [--include-tests] [--json]
104
- Rank files by simplification leads (duplicates, size, wrappers, suppressions)
103
+ deslop [path...] [--limit N] [--min-score N] [--include-tests] [--by-dir] [--json]
104
+ Rank files and directories by simplification leads (duplicates, parametric clones, size, wrappers, micro-files, suppressions)
105
105
  state-machines [path...] [--limit N] [--min-score N] [--json] Rank files that look like implicit state machines
106
106
  seo probe [--page|--headers|--links|--sitemap] <host> [path...] Live search and preview metadata of a site
107
107
  space [checkout-or-path...] [--builds] [--deps] [--machine] [--include-busy] [--apply] [--json]
@@ -1,14 +1,16 @@
1
1
  /**
2
2
  * `agent-tool deslop`: ranks tracked source files by structural simplification
3
- * leads (duplicated blocks, oversized files, long functions, suppression
4
- * clusters, and thin-wrapper cascades). Read-only; it points a person or agent
5
- * at files worth inspecting and never edits anything.
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.
6
7
  */
7
8
  import { lstatSync, realpathSync, writeSync } from "node:fs";
8
9
  import path from "node:path";
9
10
  import { isolatedGit, toplevel } from "../system/checkouts";
10
11
  import { readRegularFile } from "../system/files";
11
12
  import {
13
+ type DeslopDirectoryReport,
12
14
  type DeslopFileReport,
13
15
  type DuplicateCluster,
14
16
  isGeneratedSource,
@@ -24,6 +26,7 @@ export interface DeslopOptions {
24
26
  readonly limit: number;
25
27
  readonly minScore: number;
26
28
  readonly includeTests: boolean;
29
+ readonly byDir: boolean;
27
30
  }
28
31
 
29
32
  export interface DeslopRepoReport {
@@ -33,6 +36,9 @@ export interface DeslopRepoReport {
33
36
  readonly files: DeslopFileReport[];
34
37
  readonly more: number;
35
38
  readonly duplicates: DuplicateCluster[];
39
+ readonly parametricDuplicates: DuplicateCluster[];
40
+ readonly directories?: DeslopDirectoryReport[];
41
+ readonly moreDirectories?: number;
36
42
  readonly error?: string;
37
43
  }
38
44
 
@@ -41,16 +47,18 @@ export interface DeslopTarget {
41
47
  readonly root: string;
42
48
  }
43
49
 
44
- export const USAGE = `Usage: agent-tool deslop [path...] [--limit N] [--min-score N] [--include-tests] [--json]
50
+ export const USAGE = `Usage: agent-tool deslop [path...] [--limit N] [--min-score N] [--include-tests] [--by-dir] [--json]
45
51
 
46
52
  Ranks tracked source files by simplification leads: duplicated code blocks,
47
- oversized files, long functions, lint/type suppression clusters, and exported
48
- thin-wrapper cascades. Read-only. Scans the repository holding the working
49
- directory, or the repository holding each named path.
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.
50
57
 
51
- --limit N files (and duplicate clusters) listed per repository (default 25; 0 lists all)
58
+ --limit N files, directories, and clone clusters listed per repository (default 25; 0 lists all)
52
59
  --min-score N skip files scoring below N (default 3)
53
60
  --include-tests include test and fixture files (skipped by default)
61
+ --by-dir include directory-level hotspot rankings and test/source ratios
54
62
  --json JSON output for agents`;
55
63
 
56
64
  function count(flag: string, value: string | undefined): number {
@@ -65,16 +73,18 @@ export function parseOptions(argv: string[]): DeslopOptions {
65
73
  let limit = 25;
66
74
  let minScore = 3;
67
75
  let includeTests = false;
76
+ let byDir = false;
68
77
  for (let index = 0; index < argv.length; index++) {
69
78
  const arg = argv[index]!;
70
79
  if (arg === "--json") json = true;
71
80
  else if (arg === "--include-tests") includeTests = true;
81
+ else if (arg === "--by-dir") byDir = true;
72
82
  else if (arg === "--limit") limit = count(arg, argv[++index]);
73
83
  else if (arg === "--min-score") minScore = count(arg, argv[++index]);
74
84
  else if (arg.startsWith("-")) throw new Error(`Unknown option ${arg}.`);
75
85
  else names.push(arg);
76
86
  }
77
- return { names, json, limit, minScore, includeTests };
87
+ return { names, json, limit, minScore, includeTests, byDir };
78
88
  }
79
89
 
80
90
  /**
@@ -121,15 +131,35 @@ export function readInside(realRoot: string, file: string): string | undefined {
121
131
  export function scanRepository(
122
132
  name: string,
123
133
  root: string,
124
- options: Pick<DeslopOptions, "limit" | "minScore" | "includeTests">,
134
+ options: Pick<DeslopOptions, "limit" | "minScore" | "includeTests"> & Partial<Pick<DeslopOptions, "byDir">>,
125
135
  ): DeslopRepoReport {
126
136
  const listed = isolatedGit(root, ["ls-files", "-z", "--cached"]);
127
- if (listed.status !== 0) return { name, root, scanned: 0, files: [], more: 0, duplicates: [], error: "git ls-files failed" };
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
+ }
128
149
  let realRoot: string;
129
150
  try {
130
151
  realRoot = realpathSync(root);
131
152
  } catch {
132
- return { name, root, scanned: 0, files: [], more: 0, duplicates: [], error: "repository path is unreadable" };
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
+ };
133
163
  }
134
164
 
135
165
  const sources: ScannedSource[] = [];
@@ -144,9 +174,13 @@ export function scanRepository(
144
174
  sources.push({ path: file, text, syntax });
145
175
  }
146
176
 
147
- const { files, duplicates } = scanSources(sources, options.minScore);
177
+ const { files, duplicates, parametricDuplicates, directories } = scanSources(sources, options.minScore, options.includeTests);
148
178
  const shownFiles = options.limit === 0 ? files : files.slice(0, options.limit);
149
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;
150
184
  return {
151
185
  name,
152
186
  root,
@@ -154,6 +188,10 @@ export function scanRepository(
154
188
  files: shownFiles,
155
189
  more: files.length - shownFiles.length,
156
190
  duplicates: shownDuplicates,
191
+ parametricDuplicates: shownParametric,
192
+ ...(shownDirectories
193
+ ? { directories: shownDirectories, moreDirectories: directories.length - shownDirectories.length }
194
+ : {}),
157
195
  };
158
196
  }
159
197
 
@@ -161,22 +199,40 @@ function describeSignal(signal: DeslopFileReport["signals"][number]): string {
161
199
  const lines = signal.lines.slice(0, 6).join(",") + (signal.lines.length > 6 ? ",..." : "");
162
200
  switch (signal.kind) {
163
201
  case "duplicate-block":
164
- return ` duplicate-block ${signal.count} lines with ${signal.details?.join(", ") ?? ""}`;
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(", ") ?? ""}`;
165
205
  case "oversized-file":
166
- return ` oversized-file ${signal.count} code lines`;
206
+ return ` oversized-file ${signal.count} code lines`;
167
207
  case "long-function":
168
- return ` long-function ${signal.details?.join(", ") ?? `${signal.count} functions`} (lines ${lines})`;
208
+ return ` long-function ${signal.details?.join(", ") ?? `${signal.count} functions`} (lines ${lines})`;
169
209
  case "suppressions":
170
- return ` suppressions ${signal.count} directives (lines ${lines})`;
210
+ return ` suppressions ${signal.count} directives (lines ${lines})`;
171
211
  case "thin-wrapper":
172
- return ` thin-wrapper ${signal.details?.join(", ") ?? `${signal.count} wrappers`} (lines ${lines})`;
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`}`;
173
215
  }
174
216
  }
175
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
+
176
227
  export function render(reports: DeslopRepoReport[]): string {
177
228
  const out: string[] = [];
178
229
  for (const repo of reports) {
179
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
+ }
180
236
  for (const file of repo.files) {
181
237
  out.push(` ${file.score.toString().padStart(3)} ${file.path}`, ...file.signals.map(describeSignal));
182
238
  }
@@ -188,6 +244,13 @@ export function render(reports: DeslopRepoReport[]): string {
188
244
  out.push(` ${cluster.lines.toString().padStart(3)} lines ${locs}`);
189
245
  }
190
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
+ }
191
254
  }
192
255
  out.push("", "Candidates are leads, not findings: read each file and apply the deslopify-refactor skill before changing it.");
193
256
  return out.join("\n");