@neuralaxis/vibedoctor 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.
Files changed (135) hide show
  1. package/LICENSE +232 -0
  2. package/README.md +280 -0
  3. package/dist/adapters/biome.d.ts +2 -0
  4. package/dist/adapters/biome.js +66 -0
  5. package/dist/adapters/coveragePy.d.ts +2 -0
  6. package/dist/adapters/coveragePy.js +56 -0
  7. package/dist/adapters/customDeadChain.d.ts +20 -0
  8. package/dist/adapters/customDeadChain.js +243 -0
  9. package/dist/adapters/customLeftovers.d.ts +2 -0
  10. package/dist/adapters/customLeftovers.js +244 -0
  11. package/dist/adapters/customRefactor.d.ts +2 -0
  12. package/dist/adapters/customRefactor.js +176 -0
  13. package/dist/adapters/deptry.d.ts +2 -0
  14. package/dist/adapters/deptry.js +59 -0
  15. package/dist/adapters/gitleaks.d.ts +2 -0
  16. package/dist/adapters/gitleaks.js +47 -0
  17. package/dist/adapters/index.d.ts +16 -0
  18. package/dist/adapters/index.js +35 -0
  19. package/dist/adapters/jest.d.ts +2 -0
  20. package/dist/adapters/jest.js +62 -0
  21. package/dist/adapters/jscpd.d.ts +2 -0
  22. package/dist/adapters/jscpd.js +59 -0
  23. package/dist/adapters/knip.d.ts +2 -0
  24. package/dist/adapters/knip.js +75 -0
  25. package/dist/adapters/lizard.d.ts +2 -0
  26. package/dist/adapters/lizard.js +45 -0
  27. package/dist/adapters/osvScanner.d.ts +2 -0
  28. package/dist/adapters/osvScanner.js +68 -0
  29. package/dist/adapters/pyright.d.ts +2 -0
  30. package/dist/adapters/pyright.js +52 -0
  31. package/dist/adapters/radon.d.ts +2 -0
  32. package/dist/adapters/radon.js +45 -0
  33. package/dist/adapters/ruff.d.ts +2 -0
  34. package/dist/adapters/ruff.js +71 -0
  35. package/dist/adapters/semgrep.d.ts +2 -0
  36. package/dist/adapters/semgrep.js +64 -0
  37. package/dist/adapters/shared.d.ts +23 -0
  38. package/dist/adapters/shared.js +2 -0
  39. package/dist/adapters/tsc.d.ts +2 -0
  40. package/dist/adapters/tsc.js +57 -0
  41. package/dist/adapters/vitest.d.ts +2 -0
  42. package/dist/adapters/vitest.js +62 -0
  43. package/dist/adapters/vulture.d.ts +2 -0
  44. package/dist/adapters/vulture.js +59 -0
  45. package/dist/agentPack/generateAgentPack.d.ts +48 -0
  46. package/dist/agentPack/generateAgentPack.js +219 -0
  47. package/dist/agentPack/policy.d.ts +19 -0
  48. package/dist/agentPack/policy.js +117 -0
  49. package/dist/agentPack/templates/index.d.ts +7 -0
  50. package/dist/agentPack/templates/index.js +134 -0
  51. package/dist/agentPack/templates/skills.d.ts +7 -0
  52. package/dist/agentPack/templates/skills.js +337 -0
  53. package/dist/cli/commands/agent.d.ts +22 -0
  54. package/dist/cli/commands/agent.js +57 -0
  55. package/dist/cli/commands/agentPlan.d.ts +1 -0
  56. package/dist/cli/commands/agentPlan.js +12 -0
  57. package/dist/cli/commands/baseline.d.ts +1 -0
  58. package/dist/cli/commands/baseline.js +8 -0
  59. package/dist/cli/commands/explain.d.ts +1 -0
  60. package/dist/cli/commands/explain.js +35 -0
  61. package/dist/cli/commands/fix.d.ts +1 -0
  62. package/dist/cli/commands/fix.js +19 -0
  63. package/dist/cli/commands/init.d.ts +1 -0
  64. package/dist/cli/commands/init.js +101 -0
  65. package/dist/cli/commands/report.d.ts +1 -0
  66. package/dist/cli/commands/report.js +25 -0
  67. package/dist/cli/commands/scan.d.ts +14 -0
  68. package/dist/cli/commands/scan.js +61 -0
  69. package/dist/cli/commands/setup.d.ts +35 -0
  70. package/dist/cli/commands/setup.js +326 -0
  71. package/dist/cli/commands/shared.d.ts +8 -0
  72. package/dist/cli/commands/shared.js +29 -0
  73. package/dist/cli/index.d.ts +2 -0
  74. package/dist/cli/index.js +148 -0
  75. package/dist/core/baseline.d.ts +7 -0
  76. package/dist/core/baseline.js +33 -0
  77. package/dist/core/config.d.ts +72 -0
  78. package/dist/core/config.js +236 -0
  79. package/dist/core/engine.d.ts +87 -0
  80. package/dist/core/engine.js +437 -0
  81. package/dist/core/finding.d.ts +40 -0
  82. package/dist/core/finding.js +141 -0
  83. package/dist/core/git.d.ts +3 -0
  84. package/dist/core/git.js +67 -0
  85. package/dist/core/paths.d.ts +7 -0
  86. package/dist/core/paths.js +104 -0
  87. package/dist/core/projectDetector.d.ts +17 -0
  88. package/dist/core/projectDetector.js +160 -0
  89. package/dist/core/scanPlanner.d.ts +11 -0
  90. package/dist/core/scanPlanner.js +47 -0
  91. package/dist/core/scoring.d.ts +8 -0
  92. package/dist/core/scoring.js +57 -0
  93. package/dist/core/toolRunner.d.ts +24 -0
  94. package/dist/core/toolRunner.js +130 -0
  95. package/dist/index.d.ts +7 -0
  96. package/dist/index.js +23 -0
  97. package/dist/mcp/server.d.ts +1 -0
  98. package/dist/mcp/server.js +141 -0
  99. package/dist/mcp/tools/explainFinding.d.ts +2 -0
  100. package/dist/mcp/tools/explainFinding.js +23 -0
  101. package/dist/mcp/tools/fixSafe.d.ts +2 -0
  102. package/dist/mcp/tools/fixSafe.js +15 -0
  103. package/dist/mcp/tools/getAgentPlan.d.ts +2 -0
  104. package/dist/mcp/tools/getAgentPlan.js +31 -0
  105. package/dist/mcp/tools/getReport.d.ts +2 -0
  106. package/dist/mcp/tools/getReport.js +26 -0
  107. package/dist/mcp/tools/index.d.ts +1 -0
  108. package/dist/mcp/tools/index.js +19 -0
  109. package/dist/mcp/tools/scanChanged.d.ts +2 -0
  110. package/dist/mcp/tools/scanChanged.js +23 -0
  111. package/dist/mcp/tools/scanFull.d.ts +2 -0
  112. package/dist/mcp/tools/scanFull.js +23 -0
  113. package/dist/mcp/tools/shared.d.ts +51 -0
  114. package/dist/mcp/tools/shared.js +126 -0
  115. package/dist/mcp/tools/verify.d.ts +2 -0
  116. package/dist/mcp/tools/verify.js +21 -0
  117. package/dist/reporters/agent.d.ts +3 -0
  118. package/dist/reporters/agent.js +48 -0
  119. package/dist/reporters/html.d.ts +2 -0
  120. package/dist/reporters/html.js +81 -0
  121. package/dist/reporters/json.d.ts +2 -0
  122. package/dist/reporters/json.js +18 -0
  123. package/dist/reporters/markdown.d.ts +2 -0
  124. package/dist/reporters/markdown.js +33 -0
  125. package/dist/reporters/sarif.d.ts +2 -0
  126. package/dist/reporters/sarif.js +38 -0
  127. package/dist/reporters/terminal.d.ts +2 -0
  128. package/dist/reporters/terminal.js +11 -0
  129. package/dist/rules/leftoverPatterns.d.ts +7 -0
  130. package/dist/rules/leftoverPatterns.js +10 -0
  131. package/dist/rules/refactorRules.d.ts +13 -0
  132. package/dist/rules/refactorRules.js +16 -0
  133. package/dist/rules/severityMap.d.ts +15 -0
  134. package/dist/rules/severityMap.js +33 -0
  135. package/package.json +72 -0
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.coveragePyAdapter = void 0;
7
+ const node_fs_1 = require("node:fs");
8
+ const node_os_1 = __importDefault(require("node:os"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const toolRunner_1 = require("../core/toolRunner");
11
+ exports.coveragePyAdapter = {
12
+ id: "coverage.py",
13
+ category: "tests",
14
+ async detect(project) {
15
+ return project.languages.includes("python");
16
+ },
17
+ async runStandalone(ctx) {
18
+ const reportFile = node_path_1.default.join(node_os_1.default.tmpdir(), `vibedoctor-coverage-py-${Date.now()}.json`);
19
+ const status = await (0, toolRunner_1.runCommand)({
20
+ cmd: "coverage",
21
+ args: ["json", "-q", "-o", reportFile],
22
+ cwd: ctx.root,
23
+ timeoutMs: 60_000
24
+ }, "Install coverage.py with: pipx install coverage or add coverage to your project.");
25
+ let findings = [];
26
+ try {
27
+ const parsed = JSON.parse(await node_fs_1.promises.readFile(reportFile, "utf8"));
28
+ const percent = parsed.totals?.percent_covered;
29
+ if (typeof percent === "number" && percent < ctx.config.checks.tests.minCoverage) {
30
+ findings.push({
31
+ id: "coverage.py:overall",
32
+ source: "coverage.py",
33
+ category: "tests",
34
+ severity: percent < ctx.config.checks.tests.minCoverage / 2 ? "high" : "medium",
35
+ confidence: "high",
36
+ title: "Python coverage below target",
37
+ message: `Coverage is ${percent}% which is below the configured minimum of ${ctx.config.checks.tests.minCoverage}%.`,
38
+ isNew: true,
39
+ isAutofixable: false,
40
+ safeToAutofix: false,
41
+ agentInstruction: "Add or strengthen Python tests before making broader refactors.",
42
+ tags: ["python", "coverage"],
43
+ scoreImpact: 0
44
+ });
45
+ }
46
+ }
47
+ catch {
48
+ findings = [];
49
+ }
50
+ finally {
51
+ await node_fs_1.promises.rm(reportFile, { force: true }).catch(() => undefined);
52
+ }
53
+ return { findings, status };
54
+ },
55
+ installHint: "Install coverage.py with: pipx install coverage or add coverage to your project."
56
+ };
@@ -0,0 +1,20 @@
1
+ import type { Finding } from "../core/finding";
2
+ import type { ProjectContext } from "../core/projectDetector";
3
+ type CodeNode = {
4
+ id: string;
5
+ type: "file" | "dependency" | "test";
6
+ file?: string;
7
+ name: string;
8
+ language: "python" | "javascript" | "typescript";
9
+ incoming: string[];
10
+ outgoing: string[];
11
+ tags: string[];
12
+ };
13
+ type DeadChainCandidate = {
14
+ files: string[];
15
+ confidence: "low" | "medium" | "high";
16
+ reasons: string[];
17
+ dependencies: string[];
18
+ };
19
+ export declare function detectDeadChains(project: ProjectContext, findings: Finding[]): Promise<Finding[]>;
20
+ export type { CodeNode, DeadChainCandidate };
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.detectDeadChains = detectDeadChains;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const paths_1 = require("../core/paths");
9
+ const SOURCE_FILE_PATTERN = /\.(ts|tsx|js|jsx|py)$/;
10
+ const JS_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
11
+ const PY_EXTENSIONS = [".py"];
12
+ function isTestFile(file) {
13
+ return /(^|\/)tests?\//.test(file) || /\.test\./.test(file) || /\.spec\./.test(file);
14
+ }
15
+ function detectLanguage(file) {
16
+ if (file.endsWith(".py")) {
17
+ return "python";
18
+ }
19
+ if (file.endsWith(".ts") || file.endsWith(".tsx")) {
20
+ return "typescript";
21
+ }
22
+ return "javascript";
23
+ }
24
+ function parseImports(file, content) {
25
+ const imports = new Set();
26
+ if (file.endsWith(".py")) {
27
+ for (const match of content.matchAll(/(?:from\s+([.\w]+)\s+import|import\s+([.\w]+))/g)) {
28
+ const value = match[1] ?? match[2];
29
+ if (value) {
30
+ imports.add(value);
31
+ }
32
+ }
33
+ return Array.from(imports);
34
+ }
35
+ for (const match of content.matchAll(/(?:import|export)\s+(?:[^"'`]+?\s+from\s+)?["'`]([^"'`]+)["'`]/g)) {
36
+ if (match[1]) {
37
+ imports.add(match[1]);
38
+ }
39
+ }
40
+ for (const match of content.matchAll(/require\(\s*["'`]([^"'`]+)["'`]\s*\)/g)) {
41
+ if (match[1]) {
42
+ imports.add(match[1]);
43
+ }
44
+ }
45
+ return Array.from(imports);
46
+ }
47
+ function resolveRelativeImport(fromFile, specifier, projectFiles, extensions) {
48
+ const baseDir = node_path_1.default.posix.dirname(fromFile);
49
+ const raw = node_path_1.default.posix.normalize(node_path_1.default.posix.join(baseDir, specifier));
50
+ const candidates = [
51
+ raw,
52
+ ...extensions.map((extension) => `${raw}${extension}`),
53
+ ...extensions.map((extension) => `${raw}/index${extension}`)
54
+ ];
55
+ return candidates.find((candidate) => projectFiles.has(candidate));
56
+ }
57
+ function resolvePythonImport(fromFile, specifier, projectFiles) {
58
+ if (specifier.startsWith(".")) {
59
+ const depth = specifier.match(/^\.+/)?.[0].length ?? 1;
60
+ const remainder = specifier.slice(depth);
61
+ let baseDir = node_path_1.default.posix.dirname(fromFile);
62
+ for (let index = 1; index < depth; index += 1) {
63
+ baseDir = node_path_1.default.posix.dirname(baseDir);
64
+ }
65
+ const relative = remainder.replaceAll(".", "/");
66
+ const directCandidates = [
67
+ node_path_1.default.posix.normalize(node_path_1.default.posix.join(baseDir, relative)),
68
+ node_path_1.default.posix.normalize(node_path_1.default.posix.join(baseDir, `${relative}.py`)),
69
+ node_path_1.default.posix.normalize(node_path_1.default.posix.join(baseDir, relative, "__init__.py"))
70
+ ];
71
+ return directCandidates.find((candidate) => projectFiles.has(candidate));
72
+ }
73
+ const dottedPath = specifier.replaceAll(".", "/");
74
+ return [`${dottedPath}.py`, `${dottedPath}/__init__.py`].find((candidate) => projectFiles.has(candidate));
75
+ }
76
+ async function buildGraph(project) {
77
+ const sourceFiles = (0, paths_1.filterPaths)(project.projectFiles, ["**/*"]).filter((file) => SOURCE_FILE_PATTERN.test(file));
78
+ const projectFileSet = new Set(sourceFiles);
79
+ const graph = new Map();
80
+ for (const file of sourceFiles) {
81
+ graph.set(file, {
82
+ id: file,
83
+ type: isTestFile(file) ? "test" : "file",
84
+ file,
85
+ name: node_path_1.default.posix.basename(file),
86
+ language: detectLanguage(file),
87
+ incoming: [],
88
+ outgoing: [],
89
+ tags: []
90
+ });
91
+ }
92
+ for (const file of sourceFiles) {
93
+ const content = await (0, paths_1.readTextIfExists)(node_path_1.default.join(project.root, file));
94
+ if (!content) {
95
+ continue;
96
+ }
97
+ const imports = parseImports(file, content);
98
+ const extensions = file.endsWith(".py") ? PY_EXTENSIONS : JS_EXTENSIONS;
99
+ for (const specifier of imports) {
100
+ let resolved;
101
+ if (file.endsWith(".py")) {
102
+ resolved = resolvePythonImport(file, specifier, projectFileSet);
103
+ }
104
+ else if (specifier.startsWith(".")) {
105
+ resolved = resolveRelativeImport(file, specifier, projectFileSet, extensions);
106
+ }
107
+ if (!resolved) {
108
+ continue;
109
+ }
110
+ const sourceNode = graph.get(file);
111
+ const targetNode = graph.get(resolved);
112
+ if (!sourceNode || !targetNode) {
113
+ continue;
114
+ }
115
+ sourceNode.outgoing.push(resolved);
116
+ targetNode.incoming.push(file);
117
+ }
118
+ }
119
+ return graph;
120
+ }
121
+ function collectEntrypoints(project, graph) {
122
+ const explicit = new Set(project.entryFiles.filter((file) => graph.has(file) && !isTestFile(file)));
123
+ for (const file of graph.keys()) {
124
+ if (/^src\/(index|main|app|server)\.(ts|tsx|js|jsx|py)$/.test(file)) {
125
+ explicit.add(file);
126
+ }
127
+ }
128
+ return Array.from(explicit);
129
+ }
130
+ function markReachable(graph, entrypoints) {
131
+ const reachable = new Set();
132
+ const queue = [...entrypoints];
133
+ while (queue.length > 0) {
134
+ const current = queue.shift();
135
+ if (reachable.has(current)) {
136
+ continue;
137
+ }
138
+ reachable.add(current);
139
+ const node = graph.get(current);
140
+ if (!node) {
141
+ continue;
142
+ }
143
+ for (const target of node.outgoing) {
144
+ if (!reachable.has(target)) {
145
+ queue.push(target);
146
+ }
147
+ }
148
+ }
149
+ return reachable;
150
+ }
151
+ function buildComponents(graph, unreachableSeeds) {
152
+ const visited = new Set();
153
+ const components = [];
154
+ for (const seed of unreachableSeeds) {
155
+ if (visited.has(seed)) {
156
+ continue;
157
+ }
158
+ const stack = [seed];
159
+ const component = [];
160
+ while (stack.length > 0) {
161
+ const current = stack.pop();
162
+ if (visited.has(current) || !unreachableSeeds.has(current)) {
163
+ continue;
164
+ }
165
+ visited.add(current);
166
+ component.push(current);
167
+ const node = graph.get(current);
168
+ if (!node) {
169
+ continue;
170
+ }
171
+ for (const edge of [...node.outgoing, ...node.incoming]) {
172
+ if (!visited.has(edge) && unreachableSeeds.has(edge)) {
173
+ stack.push(edge);
174
+ }
175
+ }
176
+ }
177
+ if (component.length > 0) {
178
+ components.push(component.sort());
179
+ }
180
+ }
181
+ return components;
182
+ }
183
+ function hasDynamicPattern(file) {
184
+ return /\.tsx?$/.test(file) ? /route|plugin|dynamic/i.test(file) : /manage|settings|celery/i.test(file);
185
+ }
186
+ function isPackageInitializer(file) {
187
+ return file.endsWith("/__init__.py") || file === "__init__.py";
188
+ }
189
+ async function detectDeadChains(project, findings) {
190
+ const graph = await buildGraph(project);
191
+ const entrypoints = collectEntrypoints(project, graph);
192
+ const reachable = markReachable(graph, entrypoints);
193
+ const deadCodeFiles = new Set(findings.filter((finding) => finding.category === "dead_code" && finding.file).map((finding) => finding.file));
194
+ const candidates = new Set();
195
+ for (const [file, node] of graph.entries()) {
196
+ if (node.type === "test") {
197
+ continue;
198
+ }
199
+ if (!reachable.has(file) && (deadCodeFiles.has(file) || node.incoming.every((incoming) => !reachable.has(incoming)))) {
200
+ candidates.add(file);
201
+ }
202
+ }
203
+ const components = buildComponents(graph, candidates);
204
+ const dependencyNames = findings
205
+ .filter((finding) => finding.category === "dependencies" && /unused dependency/i.test(finding.title))
206
+ .map((finding) => finding.message.split(" ")[0]);
207
+ return components
208
+ .filter((component) => component.length > 1 || deadCodeFiles.has(component[0]))
209
+ .map((component, index) => {
210
+ const testReferenced = component.some((file) => Array.from(graph.values()).some((node) => node.type === "test" && node.outgoing.includes(file)));
211
+ const dynamicRisk = component.some((file) => hasDynamicPattern(file));
212
+ const packageInitializer = component.some((file) => isPackageInitializer(file));
213
+ const confidence = packageInitializer || testReferenced ? "low" : dynamicRisk ? "medium" : "high";
214
+ const reasons = [
215
+ "No active entrypoint reaches this cluster.",
216
+ packageInitializer ? "One or more files are package initializers that may expose implicit package behavior." : undefined,
217
+ testReferenced ? "One or more files are referenced by tests." : "No tests reference this cluster.",
218
+ "The files mostly call each other inside the same isolated cluster."
219
+ ].filter((reason) => Boolean(reason));
220
+ const dependencies = dependencyNames.filter((dependency) => component.some((file) => file.includes(node_path_1.default.posix.basename(dependency))));
221
+ return {
222
+ id: `dead-chain:${index + 1}:${component[0]}`,
223
+ source: "custom-dead-chain",
224
+ category: "dead_code",
225
+ severity: confidence === "high" ? "medium" : "low",
226
+ confidence,
227
+ title: packageInitializer ? "Review-only dead chain candidate" : "Dead chain candidate",
228
+ message: `${component[0]}${component.length > 1 ? ` and ${component.length - 1} linked files` : ""} look isolated from active entrypoints${packageInitializer ? ", but package initializers require manual review" : ""}.`,
229
+ file: component[0],
230
+ isNew: true,
231
+ isAutofixable: false,
232
+ safeToAutofix: false,
233
+ agentInstruction: packageInitializer
234
+ ? `Review this chain manually before any deletion because it includes a Python package initializer:\n${component.map((file) => `- ${file}`).join("\n")}`
235
+ : `Review and, if unused at runtime, delete this chain as one unit:\n${component.map((file) => `- ${file}`).join("\n")}`,
236
+ tags: packageInitializer ? ["dead-chain", "review-only"] : ["dead-chain"],
237
+ evidence: {
238
+ snippet: `${reasons.join(" ")} Files: ${component.join(", ")}${dependencies.length > 0 ? ` Dependencies: ${dependencies.join(", ")}` : ""}`
239
+ },
240
+ scoreImpact: 0
241
+ };
242
+ });
243
+ }
@@ -0,0 +1,2 @@
1
+ import type { ToolAdapter } from "./shared";
2
+ export declare const customLeftoversAdapter: ToolAdapter;
@@ -0,0 +1,244 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.customLeftoversAdapter = void 0;
7
+ const node_path_1 = __importDefault(require("node:path"));
8
+ const paths_1 = require("../core/paths");
9
+ const leftoverPatterns_1 = require("../rules/leftoverPatterns");
10
+ const COMMENT_PREFIX = {
11
+ ".ts": "//",
12
+ ".tsx": "//",
13
+ ".js": "//",
14
+ ".jsx": "//",
15
+ ".py": "#"
16
+ };
17
+ function looksLikeCommentedCode(text) {
18
+ return /\b(const|let|var|function|class|return|def|import|from)\b/.test(text);
19
+ }
20
+ function shouldIgnoreComment(commentText) {
21
+ return /^changelog\b|^release notes?\b|^copyright\b|^migration\b|^history\b|^example\b/i.test(commentText.trim());
22
+ }
23
+ function shouldIgnoreLine(lineText) {
24
+ const t = lineText.trim().toLowerCase();
25
+ if (shouldIgnoreComment(t))
26
+ return true;
27
+ // Suppress matches in the detector's own documentation, policy text, templates, and pattern definitions
28
+ // (common source of self-FPs when scanning the VibeDoctor repo or similar "rules" code).
29
+ if (/(?:patterns|rules for|this detector|agent skills|vibedoctor.*(legacy|fallback|dead|leftovers))|do not (delete|remove).* (low|dead|legacy|compat)|"legacy"|'legacy'|leftover.*patterns|dead.chain|refactor.*readiness/i.test(t)) {
30
+ return true;
31
+ }
32
+ // Extra: suppress matches *inside the implementation of the detector itself* (self-referential examples, group names, fn bodies)
33
+ if (/fallback-branch|name-signal|flag-signal|commented-code|find(Comment|Name|Fallback|Flag)Matches|envGuardMatch|LEFTOVER_NAME|scanLegacyFallbacks|scanCommentedCode|shouldIgnoreLine/i.test(t)) {
34
+ return true;
35
+ }
36
+ // Suppress literal example words used inside the matcher source (the "hasFallbackSignal includes('legacy')" etc. lines)
37
+ if (/"legacy"|"fallback"|"compat"|"oldflow"|"LEGACY|OLD|FALLBACK|COMPAT/i.test(t) && /includes|hasFallbackSignal|hasControlFlow|lower\.includes/i.test(t)) {
38
+ return true;
39
+ }
40
+ // Prevent self-FPs on meta/explanatory comments we add about the detector itself (e.g. "this cleans the ... path", "addresses the previous", "treat as success", "normaliz")
41
+ if (/this (cleans|addresses|removes)|treat as (success|ok)|normali[sz]|legacy (score|handling|path)/i.test(t)) {
42
+ return true;
43
+ }
44
+ return false;
45
+ }
46
+ function findCommentMatches(file, content, scanComments, scanCommentedCode) {
47
+ const extension = node_path_1.default.extname(file);
48
+ const commentPrefix = COMMENT_PREFIX[extension];
49
+ if (!commentPrefix) {
50
+ return [];
51
+ }
52
+ const matches = [];
53
+ const lines = content.split(/\r?\n/);
54
+ for (const [index, line] of lines.entries()) {
55
+ const trimmed = line.trim();
56
+ const isComment = trimmed.startsWith(commentPrefix) || trimmed.startsWith("/*") || trimmed.startsWith("*");
57
+ if (!isComment) {
58
+ continue;
59
+ }
60
+ const commentText = trimmed.replace(/^\/\//, "").replace(/^#/, "").replace(/^\/\*/, "").replace(/^\*/, "").trim();
61
+ if (shouldIgnoreComment(commentText) || shouldIgnoreLine(commentText)) {
62
+ continue;
63
+ }
64
+ const lower = commentText.toLowerCase();
65
+ if (scanComments) {
66
+ for (const [group, patterns] of Object.entries(leftoverPatterns_1.LEFTOVER_PATTERNS)) {
67
+ for (const pattern of patterns) {
68
+ if (lower.includes(pattern)) {
69
+ matches.push({
70
+ group,
71
+ pattern,
72
+ file,
73
+ line: index + 1,
74
+ lineText: commentText,
75
+ confidence: "medium",
76
+ severity: "low"
77
+ });
78
+ }
79
+ }
80
+ }
81
+ }
82
+ if (scanCommentedCode && looksLikeCommentedCode(commentText)) {
83
+ matches.push({
84
+ group: "commented-code",
85
+ pattern: "commented code",
86
+ file,
87
+ line: index + 1,
88
+ lineText: commentText,
89
+ confidence: "high",
90
+ severity: "low"
91
+ });
92
+ }
93
+ }
94
+ return matches;
95
+ }
96
+ function findNameMatches(file, content) {
97
+ const lines = content.split(/\r?\n/);
98
+ const matches = [];
99
+ for (const [index, line] of lines.entries()) {
100
+ const lower = line.toLowerCase();
101
+ if (!/\b(function|class|const|let|var|export|def)\b/.test(lower)) {
102
+ continue;
103
+ }
104
+ if (shouldIgnoreLine(line)) {
105
+ continue;
106
+ }
107
+ for (const pattern of leftoverPatterns_1.LEFTOVER_NAME_PATTERNS) {
108
+ if (new RegExp(`\\b${pattern}[a-z0-9_]*`, "i").test(line)) {
109
+ matches.push({
110
+ group: "name-signal",
111
+ pattern,
112
+ file,
113
+ line: index + 1,
114
+ lineText: line.trim(),
115
+ confidence: "low", // lowered to reduce noise from legitimate transitional/compat names
116
+ severity: "low"
117
+ });
118
+ }
119
+ }
120
+ }
121
+ return matches;
122
+ }
123
+ function findFallbackMatches(file, content) {
124
+ const lines = content.split(/\r?\n/);
125
+ const matches = [];
126
+ for (const [index, line] of lines.entries()) {
127
+ const lower = line.toLowerCase();
128
+ if (shouldIgnoreLine(line)) {
129
+ continue;
130
+ }
131
+ const hasFallbackSignal = lower.includes("legacy") || lower.includes("fallback") || lower.includes("compat") || lower.includes("oldflow");
132
+ // Further tightened for real code (post-ouroboros scan):
133
+ // - Removed "return" (noisy on normal "return foo(fallback)" utils).
134
+ // - Stricter hasBranchControl: only true branch keywords (if/else etc) or actual ternary ( ? ... : ).
135
+ // This avoids matching ":" in TS param types like "fallback: AgentTarget[]" on declaration lines.
136
+ const hasBranchControl = /\b(if|else|catch|except|try|switch)\b/.test(lower) || (/\?/.test(lower) && /:/.test(lower));
137
+ if (hasFallbackSignal && hasBranchControl) {
138
+ const envGuardMatch = line.match(/\b([A-Z][A-Z0-9_]*(?:LEGACY|OLD|FALLBACK|COMPAT|V1)[A-Z0-9_]*)\b/);
139
+ matches.push({
140
+ group: "fallback-branch",
141
+ pattern: lower.includes("legacy") ? "legacy branch" : "fallback branch",
142
+ file,
143
+ line: index + 1,
144
+ lineText: line.trim(),
145
+ confidence: envGuardMatch ? "medium" : "high",
146
+ severity: "medium",
147
+ instruction: envGuardMatch
148
+ ? `Verify whether ${envGuardMatch[1]} is still a supported flag. If not, remove the fallback and update tests.`
149
+ : "Verify the fallback is still required; if not, remove it and update tests."
150
+ });
151
+ }
152
+ }
153
+ return matches;
154
+ }
155
+ function findFlagMatches(file, content) {
156
+ const lines = content.split(/\r?\n/);
157
+ const matches = [];
158
+ for (const [index, line] of lines.entries()) {
159
+ const trimmed = line.trim();
160
+ if (shouldIgnoreLine(line)) {
161
+ continue;
162
+ }
163
+ const envMatch = trimmed.match(/\b([A-Z][A-Z0-9_]*(?:LEGACY|OLD|FALLBACK|COMPAT|DEPRECATED|PREVIOUS|V1)[A-Z0-9_]*)\b/);
164
+ const featureFlagMatch = trimmed.match(/\b(?:legacy|old|fallback|compat|deprecated|previous)[A-Z][A-Za-z0-9]+\b/);
165
+ const signal = envMatch?.[1] ?? featureFlagMatch?.[0];
166
+ if (!signal) {
167
+ continue;
168
+ }
169
+ matches.push({
170
+ group: "flag-signal",
171
+ pattern: signal,
172
+ file,
173
+ line: index + 1,
174
+ lineText: trimmed,
175
+ confidence: "medium",
176
+ severity: "low",
177
+ instruction: `Confirm whether ${signal} is still an active environment variable or feature flag. Remove dead fallback wiring if not.`
178
+ });
179
+ }
180
+ return matches;
181
+ }
182
+ exports.customLeftoversAdapter = {
183
+ id: "custom-leftovers",
184
+ category: "leftovers",
185
+ async detect(_project, config) {
186
+ return config.checks.leftovers.enabled;
187
+ },
188
+ async runStandalone(ctx) {
189
+ const candidates = (0, paths_1.filterPaths)(ctx.project.projectFiles, ctx.config.paths.include, ctx.config.paths.exclude).filter((file) => /\.(ts|tsx|js|jsx|py)$/.test(file));
190
+ const findings = [];
191
+ for (const file of candidates) {
192
+ // Pragmatic self-FP reduction: the detector source and its pattern data files deliberately contain the
193
+ // vocabulary we detect. Skip them so scans of VibeDoctor (or similar "rules" repos) aren't dominated by noise.
194
+ if (/customLeftovers|leftoverPatterns|agentPack\/templates/.test(file)) {
195
+ continue;
196
+ }
197
+ const content = await (0, paths_1.readTextIfExists)(node_path_1.default.join(ctx.root, file));
198
+ if (!content) {
199
+ continue;
200
+ }
201
+ const leftoversCfg = ctx.config.checks.leftovers;
202
+ const matches = [
203
+ ...((leftoversCfg.scanComments || leftoversCfg.scanCommentedCode) ? findCommentMatches(file, content, leftoversCfg.scanComments, leftoversCfg.scanCommentedCode) : []),
204
+ ...findNameMatches(file, content),
205
+ ...findFlagMatches(file, content),
206
+ ...(leftoversCfg.scanLegacyFallbacks ? findFallbackMatches(file, content) : [])
207
+ ];
208
+ for (const match of matches) {
209
+ findings.push({
210
+ id: `leftover:${file}:${match.line}:${match.pattern}`,
211
+ source: "custom-leftovers",
212
+ category: "leftovers",
213
+ severity: match.severity ?? (match.group === "fallback-branch" ? "medium" : "low"),
214
+ confidence: match.confidence ?? (match.group === "commented-code" ? "high" : "medium"),
215
+ title: match.group === "commented-code"
216
+ ? "Commented-out code"
217
+ : match.group === "fallback-branch"
218
+ ? "Legacy fallback path appears present"
219
+ : match.group === "flag-signal"
220
+ ? "Legacy flag or env toggle"
221
+ : "Legacy or temporary marker",
222
+ message: match.lineText,
223
+ file,
224
+ startLine: match.line,
225
+ isNew: true,
226
+ isAutofixable: false,
227
+ safeToAutofix: false,
228
+ agentInstruction: match.instruction ??
229
+ (match.group === "fallback-branch"
230
+ ? "Verify the fallback is still required; if not, remove it and update tests."
231
+ : "Confirm the legacy note is still needed. Delete stale comments or code after verifying behavior."),
232
+ tags: ["leftovers", match.group],
233
+ evidence: {
234
+ snippet: match.lineText,
235
+ matchedPattern: match.pattern
236
+ },
237
+ scoreImpact: 0
238
+ });
239
+ }
240
+ }
241
+ return { findings };
242
+ },
243
+ installHint: "Built-in detector. No external install needed."
244
+ };
@@ -0,0 +1,2 @@
1
+ import type { ToolAdapter } from "./shared";
2
+ export declare const customRefactorAdapter: ToolAdapter;