anvil-engineering-workbench 1.0.1 → 1.0.4

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 (53) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +20 -11
  3. package/SECURITY.md +1 -1
  4. package/dist/cli.js +276 -183
  5. package/dist/cli.js.map +1 -1
  6. package/dist/core/agent-config-release.js +1 -1
  7. package/dist/core/agent-config-versioning.js +1 -1
  8. package/dist/core/agent-evaluation-intelligence.js +1 -1
  9. package/dist/core/agent-evolution.js +1 -1
  10. package/dist/core/agent-experiment-studio.js +2 -2
  11. package/dist/core/agent-optimization.js +1 -1
  12. package/dist/core/agent-security-audit.js +1 -1
  13. package/dist/core/architecture-map.js +181 -20
  14. package/dist/core/architecture-map.js.map +1 -1
  15. package/dist/core/benchmark-engine.js +1 -1
  16. package/dist/core/benchmark-matrix.js +1 -1
  17. package/dist/core/benchmark-regression.js +1 -1
  18. package/dist/core/change-intelligence.js +1 -1
  19. package/dist/core/code-intelligence.js +1 -1
  20. package/dist/core/code-review.js +1 -1
  21. package/dist/core/dashboard-server.js +48 -44
  22. package/dist/core/dashboard-server.js.map +1 -1
  23. package/dist/core/dependency-impact.js +1 -1
  24. package/dist/core/dependency-intelligence.js +1 -1
  25. package/dist/core/doctor.d.ts +6 -0
  26. package/dist/core/doctor.js +175 -19
  27. package/dist/core/doctor.js.map +1 -1
  28. package/dist/core/engineering-risk.js +1 -1
  29. package/dist/core/git-intelligence.js +1 -1
  30. package/dist/core/intelligence-timeline.js +1 -1
  31. package/dist/core/patch-validation.js +1 -1
  32. package/dist/core/project-cleaner.d.ts +78 -0
  33. package/dist/core/project-cleaner.js +847 -0
  34. package/dist/core/project-cleaner.js.map +1 -0
  35. package/dist/core/project-health.js +1 -1
  36. package/dist/core/project-inspector.js +2 -2
  37. package/dist/core/quality-audit.js +2 -2
  38. package/dist/core/regression-intelligence.js +1 -1
  39. package/dist/core/remediation-planner.js +4 -4
  40. package/dist/core/review-history.js +1 -1
  41. package/dist/core/sandbox-cleanup-audit.js +2 -2
  42. package/dist/core/sandbox-compliance.js +1 -1
  43. package/dist/core/sandbox-lifecycle.js +3 -3
  44. package/dist/core/sandbox-policy.js +1 -1
  45. package/dist/core/sandbox-runtime.js +1 -1
  46. package/dist/core/skill-registry.js +1 -1
  47. package/dist/core/verification.js +1 -1
  48. package/dist/index.d.ts +2 -1
  49. package/dist/index.js +2 -1
  50. package/dist/index.js.map +1 -1
  51. package/dist/mcp/server.js +38 -1
  52. package/dist/mcp/server.js.map +1 -1
  53. package/package.json +11 -3
@@ -0,0 +1,847 @@
1
+ import { readdir, readFile, stat, unlink, rm, writeFile, mkdir, copyFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { isExcludedScanDirectory } from "./workspace-scan-policy.js";
6
+ import { mapArchitecture } from "./architecture-map.js";
7
+ const execFileAsync = promisify(execFile);
8
+ const OS_JUNK = new Set([
9
+ ".ds_store",
10
+ "thumbs.db",
11
+ "desktop.ini",
12
+ "ehthumbs.db",
13
+ "ehthumbs_vista.db"
14
+ ]);
15
+ function classifyJunkFile(basename, relPath) {
16
+ const lower = basename.toLowerCase();
17
+ // OS Clutter
18
+ if (OS_JUNK.has(lower) || lower.startsWith("._")) {
19
+ return { category: "os", reason: "Operating system metadata clutter" };
20
+ }
21
+ // Logs
22
+ if (/^(npm-debug|yarn-debug|yarn-error|pnpm-debug|lerna-debug)\.log/i.test(basename) ||
23
+ (lower.endsWith(".log") && !relPath.startsWith(".anvil/") && !relPath.startsWith(".forge/"))) {
24
+ return { category: "log", reason: "Debug or error log leftover" };
25
+ }
26
+ // Temporary & incomplete downloads
27
+ if (lower.endsWith(".tmp") ||
28
+ lower.endsWith(".temp") ||
29
+ lower.endsWith(".crdownload") ||
30
+ lower.endsWith(".part") ||
31
+ lower.endsWith(".aria2") ||
32
+ lower.endsWith(".download")) {
33
+ return { category: lower.endsWith(".crdownload") || lower.endsWith(".part") || lower.endsWith(".aria2") || lower.endsWith(".download") ? "download" : "temporary", reason: "Incomplete download or temporary artifact" };
34
+ }
35
+ // Editor clutter
36
+ if (lower.endsWith("~") || lower.endsWith(".swp") || lower.endsWith(".swo") || lower.endsWith(".bak") || lower.endsWith(".orig") || lower.endsWith(".rej")) {
37
+ return { category: "editor", reason: "Editor backup, swap, or merge residue" };
38
+ }
39
+ // Python bytecode & caches
40
+ if (lower.endsWith(".pyc") || lower.endsWith(".pyo") || lower.endsWith(".pyd")) {
41
+ return { category: "cache", reason: "Compiled Python bytecode artifact" };
42
+ }
43
+ // Java / JVM compiled class files
44
+ if (lower.endsWith(".class")) {
45
+ return { category: "cache", reason: "Compiled Java bytecode class file" };
46
+ }
47
+ // C / C++ / Rust / Windows object and debug files
48
+ if (lower.endsWith(".o") || lower.endsWith(".obj") || lower.endsWith(".pdb") || lower.endsWith(".ilk") || lower.endsWith(".idb")) {
49
+ return { category: "cache", reason: "Native object or debug symbol artifact" };
50
+ }
51
+ // Go test runner binaries
52
+ if (lower.endsWith(".test") && !relPath.includes("/")) {
53
+ return { category: "cache", reason: "Compiled Go test runner binary" };
54
+ }
55
+ // Transient build caches
56
+ if (basename === ".eslintcache" || basename === ".stylelintcache" || basename === ".tsbuildinfo.cache") {
57
+ return { category: "cache", reason: "Regenerable linter/compiler cache file" };
58
+ }
59
+ return null;
60
+ }
61
+ async function scanJunk(root, rel = "", items = [], emptyDirs = []) {
62
+ const fullDir = path.join(root, rel);
63
+ let entries;
64
+ try {
65
+ entries = await readdir(fullDir, { withFileTypes: true });
66
+ }
67
+ catch {
68
+ return { items, emptyDirs };
69
+ }
70
+ // If directory is completely empty and not root
71
+ if (entries.length === 0 && rel && !isExcludedScanDirectory(path.basename(rel))) {
72
+ emptyDirs.push(rel.split(path.sep).join("/"));
73
+ return { items, emptyDirs };
74
+ }
75
+ for (const entry of entries) {
76
+ const relChild = rel ? path.join(rel, entry.name) : entry.name;
77
+ const normalizedRel = relChild.split(path.sep).join("/");
78
+ const fullPath = path.join(root, relChild);
79
+ if (entry.isDirectory()) {
80
+ const dirLower = entry.name.toLowerCase();
81
+ if (dirLower === "__pycache__" ||
82
+ dirLower === ".pytest_cache" ||
83
+ dirLower === ".mypy_cache" ||
84
+ dirLower === ".ruff_cache" ||
85
+ dirLower === ".ipynb_checkpoints") {
86
+ try {
87
+ const dirStat = await stat(fullPath);
88
+ items.push({
89
+ path: normalizedRel,
90
+ absolutePath: fullPath,
91
+ category: "cache",
92
+ reason: "Python runtime or test cache directory (regenerable)",
93
+ sizeBytes: dirStat.size || 4096,
94
+ isDirectory: true
95
+ });
96
+ }
97
+ catch {
98
+ // Ignore stat error
99
+ }
100
+ continue;
101
+ }
102
+ if (isExcludedScanDirectory(entry.name)) {
103
+ // Special case: coverage directories can be considered cache junk if present at root
104
+ if (entry.name === "coverage" || entry.name === ".nyc_output") {
105
+ try {
106
+ const dirStat = await stat(fullPath);
107
+ items.push({
108
+ path: normalizedRel,
109
+ absolutePath: fullPath,
110
+ category: "cache",
111
+ reason: "Test coverage report output (regenerable)",
112
+ sizeBytes: dirStat.size || 4096,
113
+ isDirectory: true
114
+ });
115
+ }
116
+ catch {
117
+ // Ignore stat error
118
+ }
119
+ }
120
+ continue;
121
+ }
122
+ await scanJunk(root, relChild, items, emptyDirs);
123
+ }
124
+ else if (entry.isFile()) {
125
+ const classification = classifyJunkFile(entry.name, normalizedRel);
126
+ if (classification) {
127
+ try {
128
+ const fileStat = await stat(fullPath);
129
+ items.push({
130
+ path: normalizedRel,
131
+ absolutePath: fullPath,
132
+ category: classification.category,
133
+ reason: classification.reason,
134
+ sizeBytes: fileStat.size,
135
+ isDirectory: false
136
+ });
137
+ }
138
+ catch {
139
+ // Ignore stat failure
140
+ }
141
+ }
142
+ }
143
+ }
144
+ return { items, emptyDirs };
145
+ }
146
+ function parseNamedImports(namedBlock) {
147
+ return namedBlock
148
+ .split(",")
149
+ .map(spec => spec.trim())
150
+ .filter(Boolean)
151
+ .map(spec => {
152
+ const isType = /^type\s+/.test(spec);
153
+ const cleanSpec = spec.replace(/^type\s+/, "").trim();
154
+ const parts = cleanSpec.split(/\s+as\s+/).map(p => p.trim());
155
+ if (parts.length === 2 && parts[0] && parts[1]) {
156
+ return { importedName: parts[0], localName: parts[1], isType };
157
+ }
158
+ const single = parts[0] ?? cleanSpec;
159
+ return { importedName: single, localName: single, isType };
160
+ });
161
+ }
162
+ export function autoFixCodeContent(content, filePath) {
163
+ const fixes = [];
164
+ let updated = content;
165
+ // 1. Whitespace normalization: remove trailing spaces
166
+ const lines = updated.split("\n");
167
+ let trailingWhitespaceRemoved = false;
168
+ const cleanedLines = lines.map(line => {
169
+ const stripped = line.replace(/[ \t\r]+$/, "");
170
+ if (stripped !== line.replace(/\r$/, "")) {
171
+ trailingWhitespaceRemoved = true;
172
+ }
173
+ return stripped;
174
+ });
175
+ if (trailingWhitespaceRemoved) {
176
+ updated = cleanedLines.join("\n");
177
+ fixes.push({
178
+ file: filePath,
179
+ type: "whitespace",
180
+ detail: "Trimmed trailing whitespace from lines",
181
+ applied: true
182
+ });
183
+ }
184
+ // 2. Blank line normalization (collapse 3+ consecutive newlines to 2)
185
+ if (/\n{3,}/.test(updated)) {
186
+ updated = updated.replace(/\n{3,}/g, "\n\n");
187
+ fixes.push({
188
+ file: filePath,
189
+ type: "blank-lines",
190
+ detail: "Collapsed excessive consecutive blank lines",
191
+ applied: true
192
+ });
193
+ }
194
+ // 3. Ensure single trailing newline
195
+ if (updated.length > 0 && !updated.endsWith("\n")) {
196
+ updated += "\n";
197
+ }
198
+ // 4. Safe unused named imports removal for JS/TS source files
199
+ const ext = path.extname(filePath).toLowerCase();
200
+ if ([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"].includes(ext)) {
201
+ const importRegex = /^import\s+(?:type\s+)?\{([^}]+)\}\s+from\s+["']([^"']+)["'];?\r?$/gm;
202
+ let match;
203
+ // We do replacement passes
204
+ let codePass = updated;
205
+ let importFixCount = 0;
206
+ while ((match = importRegex.exec(updated)) !== null) {
207
+ const fullStatement = match[0];
208
+ const rawSpecifiers = match[1];
209
+ const fromPath = match[2];
210
+ if (!rawSpecifiers || !fromPath)
211
+ continue;
212
+ const specifiers = parseNamedImports(rawSpecifiers);
213
+ if (specifiers.length === 0)
214
+ continue;
215
+ // Check occurrences of each localName in the rest of the file (excluding this import statement)
216
+ const contentWithoutImport = updated.slice(0, match.index) + updated.slice(match.index + fullStatement.length);
217
+ const survivingSpecifiers = [];
218
+ const removedSpecifiers = [];
219
+ for (const spec of specifiers) {
220
+ // Whole identifier boundary check for localName
221
+ const escaped = spec.localName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
222
+ const wordRegex = new RegExp(`\\b${escaped}\\b`);
223
+ if (wordRegex.test(contentWithoutImport)) {
224
+ const formatted = spec.importedName === spec.localName
225
+ ? (spec.isType ? `type ${spec.localName}` : spec.localName)
226
+ : (spec.isType ? `type ${spec.importedName} as ${spec.localName}` : `${spec.importedName} as ${spec.localName}`);
227
+ survivingSpecifiers.push(formatted);
228
+ }
229
+ else {
230
+ removedSpecifiers.push(spec.localName);
231
+ }
232
+ }
233
+ if (removedSpecifiers.length > 0) {
234
+ importFixCount += removedSpecifiers.length;
235
+ if (survivingSpecifiers.length === 0) {
236
+ // Entire import is unused -> remove the line
237
+ codePass = codePass.replace(fullStatement + "\n", "").replace(fullStatement, "");
238
+ }
239
+ else {
240
+ // Partially unused -> retain surviving
241
+ const isType = fullStatement.startsWith("import type");
242
+ const newStatement = `import ${isType ? "type " : ""}{ ${survivingSpecifiers.join(", ")} } from "${fromPath}";`;
243
+ codePass = codePass.replace(fullStatement, newStatement);
244
+ }
245
+ fixes.push({
246
+ file: filePath,
247
+ type: "unused-import",
248
+ detail: `Removed unused named import(s): ${removedSpecifiers.join(", ")} from "${fromPath}"`,
249
+ applied: true
250
+ });
251
+ }
252
+ }
253
+ if (importFixCount > 0) {
254
+ updated = codePass;
255
+ }
256
+ }
257
+ // 5. Safe unused import removal for Python source files
258
+ if ([".py", ".pyw"].includes(ext)) {
259
+ const pyImportRegex = /^from\s+([.\w]+)\s+import\s+([^#\r\n]+)/gm;
260
+ let match;
261
+ let codePass = updated;
262
+ let importFixCount = 0;
263
+ while ((match = pyImportRegex.exec(updated)) !== null) {
264
+ const fullStatement = match[0];
265
+ const fromModule = match[1];
266
+ const rawSpecifiers = match[2];
267
+ if (!fromModule || !rawSpecifiers)
268
+ continue;
269
+ if (rawSpecifiers.trim() === "*")
270
+ continue;
271
+ const specs = rawSpecifiers.split(",").map(s => s.trim()).filter(Boolean);
272
+ const parsed = specs.map(s => {
273
+ const parts = s.split(/\s+as\s+/).map(p => p.trim());
274
+ return {
275
+ importedName: parts[0] || s,
276
+ localName: parts[1] || parts[0] || s,
277
+ raw: s
278
+ };
279
+ });
280
+ const contentWithoutImport = updated.slice(0, match.index) + updated.slice(match.index + fullStatement.length);
281
+ const surviving = [];
282
+ const removed = [];
283
+ for (const spec of parsed) {
284
+ const escaped = spec.localName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
285
+ const wordRegex = new RegExp(`\\b${escaped}\\b`);
286
+ if (wordRegex.test(contentWithoutImport)) {
287
+ surviving.push(spec.raw);
288
+ }
289
+ else {
290
+ removed.push(spec.localName);
291
+ }
292
+ }
293
+ if (removed.length > 0) {
294
+ importFixCount += removed.length;
295
+ if (surviving.length === 0) {
296
+ codePass = codePass.replace(fullStatement + "\n", "").replace(fullStatement, "");
297
+ }
298
+ else {
299
+ const newStatement = `from ${fromModule} import ${surviving.join(", ")}`;
300
+ codePass = codePass.replace(fullStatement, newStatement);
301
+ }
302
+ fixes.push({
303
+ file: filePath,
304
+ type: "unused-import",
305
+ detail: `Removed unused Python import(s): ${removed.join(", ")} from "${fromModule}"`,
306
+ applied: true
307
+ });
308
+ }
309
+ }
310
+ if (importFixCount > 0) {
311
+ updated = codePass;
312
+ }
313
+ }
314
+ return { newContent: updated, fixes };
315
+ }
316
+ async function createBackupSnapshot(root, junkToDelete, emptyDirsToDelete, filesToModify) {
317
+ if (junkToDelete.length === 0 && emptyDirsToDelete.length === 0 && filesToModify.length === 0) {
318
+ return null;
319
+ }
320
+ const backupId = `backup-${Date.now()}`;
321
+ const backupRoot = path.join(root, ".anvil", "backups", backupId);
322
+ const filesBackupDir = path.join(backupRoot, "files");
323
+ const modifiedBackupDir = path.join(backupRoot, "modified");
324
+ await mkdir(filesBackupDir, { recursive: true });
325
+ await mkdir(modifiedBackupDir, { recursive: true });
326
+ const manifest = {
327
+ backupId,
328
+ timestamp: new Date().toISOString(),
329
+ root,
330
+ deletedFiles: [],
331
+ deletedDirs: [...emptyDirsToDelete],
332
+ modifiedFiles: []
333
+ };
334
+ // 1. Back up junk files before deletion
335
+ for (let i = 0; i < junkToDelete.length; i++) {
336
+ const item = junkToDelete[i];
337
+ if (item.isDirectory)
338
+ continue;
339
+ try {
340
+ const backupRel = `junk_${i}_${path.basename(item.path)}`;
341
+ const backupDest = path.join(filesBackupDir, backupRel);
342
+ await copyFile(item.absolutePath, backupDest);
343
+ manifest.deletedFiles.push({
344
+ relPath: item.path,
345
+ backupRelative: backupRel,
346
+ sizeBytes: item.sizeBytes
347
+ });
348
+ }
349
+ catch {
350
+ // Ignore copy error
351
+ }
352
+ }
353
+ // 2. Back up files before code fixes
354
+ for (let i = 0; i < filesToModify.length; i++) {
355
+ const item = filesToModify[i];
356
+ try {
357
+ const backupRel = `mod_${i}_${path.basename(item.file)}`;
358
+ const backupDest = path.join(modifiedBackupDir, backupRel);
359
+ await writeFile(backupDest, item.originalContent, "utf8");
360
+ manifest.modifiedFiles.push({
361
+ relPath: item.file,
362
+ backupRelative: backupRel
363
+ });
364
+ }
365
+ catch {
366
+ // Ignore
367
+ }
368
+ }
369
+ const manifestPath = path.join(backupRoot, "manifest.json");
370
+ await writeFile(manifestPath, JSON.stringify(manifest, null, 2), "utf8");
371
+ const latestPath = path.join(root, ".anvil", "backups", "latest.json");
372
+ await writeFile(latestPath, JSON.stringify({ backupId, timestamp: manifest.timestamp, backupRoot }, null, 2), "utf8");
373
+ return backupId;
374
+ }
375
+ export async function undoLastClean(inputPath) {
376
+ const root = path.resolve(inputPath);
377
+ const latestPath = path.join(root, ".anvil", "backups", "latest.json");
378
+ let pointer = null;
379
+ try {
380
+ const raw = await readFile(latestPath, "utf8");
381
+ pointer = JSON.parse(raw);
382
+ }
383
+ catch {
384
+ return {
385
+ root,
386
+ backupId: "",
387
+ restoredAt: new Date().toISOString(),
388
+ restoredFiles: [],
389
+ restoredDirs: [],
390
+ revertedCodeFixes: [],
391
+ errors: ["No previous ANVIL clean/fix backup found in this workspace."]
392
+ };
393
+ }
394
+ const backupRoot = pointer.backupRoot || path.join(root, ".anvil", "backups", pointer.backupId);
395
+ const manifestPath = path.join(backupRoot, "manifest.json");
396
+ let manifest;
397
+ try {
398
+ const raw = await readFile(manifestPath, "utf8");
399
+ manifest = JSON.parse(raw);
400
+ }
401
+ catch {
402
+ return {
403
+ root,
404
+ backupId: pointer.backupId,
405
+ restoredAt: new Date().toISOString(),
406
+ restoredFiles: [],
407
+ restoredDirs: [],
408
+ revertedCodeFixes: [],
409
+ errors: [`Backup manifest not found or corrupted at ${manifestPath}`]
410
+ };
411
+ }
412
+ const restoredFiles = [];
413
+ const restoredDirs = [];
414
+ const revertedCodeFixes = [];
415
+ const errors = [];
416
+ // Restore modified code files
417
+ const modifiedBackupDir = path.join(backupRoot, "modified");
418
+ for (const item of manifest.modifiedFiles) {
419
+ try {
420
+ const src = path.join(modifiedBackupDir, item.backupRelative);
421
+ const dest = path.join(root, item.relPath);
422
+ const fileContent = await readFile(src, "utf8");
423
+ await mkdir(path.dirname(dest), { recursive: true });
424
+ await writeFile(dest, fileContent, "utf8");
425
+ revertedCodeFixes.push(item.relPath);
426
+ }
427
+ catch (err) {
428
+ errors.push(`Could not restore modified file ${item.relPath}: ${err?.message || String(err)}`);
429
+ }
430
+ }
431
+ // Restore deleted files
432
+ const filesBackupDir = path.join(backupRoot, "files");
433
+ for (const item of manifest.deletedFiles) {
434
+ try {
435
+ const src = path.join(filesBackupDir, item.backupRelative);
436
+ const dest = path.join(root, item.relPath);
437
+ await mkdir(path.dirname(dest), { recursive: true });
438
+ await copyFile(src, dest);
439
+ restoredFiles.push(item.relPath);
440
+ }
441
+ catch (err) {
442
+ errors.push(`Could not restore deleted file ${item.relPath}: ${err?.message || String(err)}`);
443
+ }
444
+ }
445
+ // Restore empty directories
446
+ for (const relDir of manifest.deletedDirs) {
447
+ try {
448
+ const dest = path.join(root, relDir);
449
+ await mkdir(dest, { recursive: true });
450
+ restoredDirs.push(relDir);
451
+ }
452
+ catch (err) {
453
+ errors.push(`Could not re-create directory ${relDir}: ${err?.message || String(err)}`);
454
+ }
455
+ }
456
+ // Invalidate latest pointer so undo is not run twice on the same snapshot
457
+ try {
458
+ await rm(latestPath, { force: true });
459
+ }
460
+ catch { }
461
+ return {
462
+ root,
463
+ backupId: manifest.backupId,
464
+ restoredAt: new Date().toISOString(),
465
+ restoredFiles,
466
+ restoredDirs,
467
+ revertedCodeFixes,
468
+ errors
469
+ };
470
+ }
471
+ async function detectTestCommand(root) {
472
+ try {
473
+ const pkgRaw = await readFile(path.join(root, "package.json"), "utf8");
474
+ const pkg = JSON.parse(pkgRaw);
475
+ if (pkg.scripts && pkg.scripts.test && pkg.scripts.test !== 'echo "Error: no test specified" && exit 1') {
476
+ return process.platform === "win32" ? "npm.cmd" : "npm";
477
+ }
478
+ }
479
+ catch { }
480
+ try {
481
+ await stat(path.join(root, "Cargo.toml"));
482
+ return "cargo";
483
+ }
484
+ catch { }
485
+ try {
486
+ await stat(path.join(root, "pytest.ini"));
487
+ return "pytest";
488
+ }
489
+ catch { }
490
+ try {
491
+ await stat(path.join(root, "go.mod"));
492
+ return "go";
493
+ }
494
+ catch { }
495
+ return null;
496
+ }
497
+ export async function installPrecommitHook(inputPath) {
498
+ const root = path.resolve(inputPath);
499
+ const gitHooksDir = path.join(root, ".git", "hooks");
500
+ try {
501
+ await mkdir(gitHooksDir, { recursive: true });
502
+ const hookPath = path.join(gitHooksDir, "pre-commit");
503
+ const script = `#!/usr/bin/env sh
504
+ # ANVIL automated pre-commit quality gate
505
+ echo "[ANVIL] Running pre-commit clean & quality check..."
506
+ anvil clean --apply --json > /dev/null 2>&1 || true
507
+ `;
508
+ await writeFile(hookPath, script, { encoding: "utf8", mode: 0o755 });
509
+ return {
510
+ success: true,
511
+ hookPath,
512
+ detail: "Installed ANVIL pre-commit hook into .git/hooks/pre-commit"
513
+ };
514
+ }
515
+ catch (err) {
516
+ return {
517
+ success: false,
518
+ hookPath: path.join(gitHooksDir, "pre-commit"),
519
+ detail: `Failed to install pre-commit hook: ${err?.message || String(err)}`
520
+ };
521
+ }
522
+ }
523
+ export function formatUndoReport(result) {
524
+ const lines = [
525
+ "# ANVIL Workspace Rollback (Undo)",
526
+ "",
527
+ `- **Target:** \`${result.root}\``,
528
+ `- **Backup ID:** \`${result.backupId || "None"}\``,
529
+ `- **Restored at:** \`${result.restoredAt}\``,
530
+ `- **Reverted code fixes:** \`${result.revertedCodeFixes.length}\` files restored to original content`,
531
+ `- **Restored deleted files:** \`${result.restoredFiles.length}\` files recovered`,
532
+ `- **Restored directories:** \`${result.restoredDirs.length}\` directories re-created`,
533
+ ""
534
+ ];
535
+ if (result.revertedCodeFixes.length > 0) {
536
+ lines.push("## Reverted Code Fixes");
537
+ for (const f of result.revertedCodeFixes) {
538
+ lines.push(`- \`${f}\` (reverted)`);
539
+ }
540
+ lines.push("");
541
+ }
542
+ if (result.restoredFiles.length > 0) {
543
+ lines.push("## Restored Files");
544
+ for (const f of result.restoredFiles) {
545
+ lines.push(`- \`${f}\` (recovered from backup)`);
546
+ }
547
+ lines.push("");
548
+ }
549
+ if (result.errors.length > 0) {
550
+ lines.push("## Errors");
551
+ for (const e of result.errors) {
552
+ lines.push(`- ${e}`);
553
+ }
554
+ lines.push("");
555
+ }
556
+ if (result.errors.length === 0) {
557
+ lines.push("> [!NOTE] Workspace was successfully restored to its state prior to the last clean/fix operation.");
558
+ lines.push("");
559
+ }
560
+ return lines.join("\n");
561
+ }
562
+ export async function cleanProject(inputPath, options = {}) {
563
+ const root = path.resolve(inputPath);
564
+ const apply = Boolean(options.apply);
565
+ const fixCode = Boolean(options.fix);
566
+ const checkOrphans = options.checkOrphans !== false;
567
+ const verify = Boolean(options.verify);
568
+ const { items: junkItems, emptyDirs } = await scanJunk(root);
569
+ const orphanFiles = [];
570
+ const codeFixes = [];
571
+ const warnings = [];
572
+ let bytesReclaimed = 0;
573
+ let junkDeleted = 0;
574
+ for (const item of junkItems) {
575
+ bytesReclaimed += item.sizeBytes;
576
+ }
577
+ for (const emptyDir of emptyDirs) {
578
+ junkItems.push({
579
+ path: emptyDir,
580
+ absolutePath: path.join(root, emptyDir),
581
+ category: "empty-dir",
582
+ reason: "Empty directory leftover",
583
+ sizeBytes: 0,
584
+ isDirectory: true
585
+ });
586
+ }
587
+ // 1. Scan for orphan source files using architecture mapping
588
+ if (checkOrphans) {
589
+ try {
590
+ const arch = await mapArchitecture(root);
591
+ const incomingCounts = new Map();
592
+ for (const node of arch.nodes) {
593
+ incomingCounts.set(node.file, 0);
594
+ }
595
+ for (const edge of arch.edges) {
596
+ if (edge.kind === "internal") {
597
+ incomingCounts.set(edge.to, (incomingCounts.get(edge.to) || 0) + 1);
598
+ }
599
+ }
600
+ for (const node of arch.nodes) {
601
+ const incoming = incomingCounts.get(node.file) || 0;
602
+ if (node.role === "module" && incoming === 0) {
603
+ orphanFiles.push({
604
+ file: node.file,
605
+ lines: node.lines,
606
+ reason: "Source module with 0 incoming imports (unreferenced by mapped files)"
607
+ });
608
+ }
609
+ }
610
+ }
611
+ catch {
612
+ // Optional/heuristic
613
+ }
614
+ }
615
+ // 2. Prepare Code Auto-Repair
616
+ const filesToModify = [];
617
+ if (fixCode) {
618
+ try {
619
+ const collectSource = async (dir, rel = "") => {
620
+ const full = path.join(dir, rel);
621
+ let entries;
622
+ try {
623
+ entries = await readdir(full, { withFileTypes: true });
624
+ }
625
+ catch {
626
+ return [];
627
+ }
628
+ const res = [];
629
+ for (const e of entries) {
630
+ const childRel = rel ? path.join(rel, e.name) : e.name;
631
+ if (e.isDirectory() && !isExcludedScanDirectory(e.name)) {
632
+ res.push(...await collectSource(dir, childRel));
633
+ }
634
+ else if (e.isFile() && [
635
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
636
+ ".py", ".pyw",
637
+ ".go",
638
+ ".rs",
639
+ ".java", ".kt",
640
+ ".c", ".cpp", ".cc", ".cxx", ".h", ".hpp",
641
+ ".cs",
642
+ ".json", ".md"
643
+ ].includes(path.extname(e.name).toLowerCase())) {
644
+ res.push(childRel.split(path.sep).join("/"));
645
+ }
646
+ }
647
+ return res;
648
+ };
649
+ const sourceFiles = await collectSource(root);
650
+ for (const file of sourceFiles) {
651
+ const fullFilePath = path.join(root, file);
652
+ try {
653
+ const raw = await readFile(fullFilePath, "utf8");
654
+ const { newContent, fixes } = autoFixCodeContent(raw, file);
655
+ if (fixes.length > 0) {
656
+ codeFixes.push(...fixes);
657
+ filesToModify.push({ file, fullFilePath, originalContent: raw, newContent, fixes });
658
+ }
659
+ }
660
+ catch {
661
+ // File read error
662
+ }
663
+ }
664
+ }
665
+ catch (err) {
666
+ warnings.push(`Code repair pass encountered an error: ${err?.message || String(err)}`);
667
+ }
668
+ }
669
+ // 3. Execution (if apply: true)
670
+ let backupId;
671
+ let verification;
672
+ if (apply) {
673
+ // A. Create snapshot backup before modifying or deleting anything
674
+ try {
675
+ const bid = await createBackupSnapshot(root, junkItems, emptyDirs, filesToModify);
676
+ if (bid)
677
+ backupId = bid;
678
+ }
679
+ catch (err) {
680
+ warnings.push(`Could not create rollback backup: ${err?.message || String(err)}`);
681
+ }
682
+ // B. Delete junk files and empty directories
683
+ for (const item of junkItems) {
684
+ try {
685
+ if (item.isDirectory) {
686
+ await rm(item.absolutePath, { recursive: true, force: true });
687
+ }
688
+ else {
689
+ await unlink(item.absolutePath);
690
+ }
691
+ junkDeleted++;
692
+ }
693
+ catch (err) {
694
+ warnings.push(`Failed to delete ${item.path}: ${err?.message || String(err)}`);
695
+ }
696
+ }
697
+ // C. Write code fixes
698
+ for (const item of filesToModify) {
699
+ try {
700
+ await writeFile(item.fullFilePath, item.newContent, "utf8");
701
+ }
702
+ catch (err) {
703
+ warnings.push(`Failed to write code fix to ${item.file}: ${err?.message || String(err)}`);
704
+ }
705
+ }
706
+ // D. Self-Healing Verification Loop
707
+ if (verify) {
708
+ const testCmd = options.testCommand || await detectTestCommand(root);
709
+ if (testCmd) {
710
+ try {
711
+ let stdout = "";
712
+ const execOpts = { cwd: root, timeout: 60000, shell: process.platform === "win32" };
713
+ if (testCmd.includes("npm")) {
714
+ const res = await execFileAsync(testCmd, ["test"], execOpts);
715
+ stdout = res.stdout;
716
+ }
717
+ else if (testCmd === "cargo") {
718
+ const res = await execFileAsync("cargo", ["test"], execOpts);
719
+ stdout = res.stdout;
720
+ }
721
+ else if (testCmd === "pytest") {
722
+ const res = await execFileAsync("pytest", [], execOpts);
723
+ stdout = res.stdout;
724
+ }
725
+ else if (testCmd === "go") {
726
+ const res = await execFileAsync("go", ["test", "./..."], execOpts);
727
+ stdout = res.stdout;
728
+ }
729
+ verification = {
730
+ enabled: true,
731
+ passed: true,
732
+ rolledBack: false,
733
+ command: testCmd,
734
+ output: stdout.trim().slice(0, 500)
735
+ };
736
+ }
737
+ catch (testErr) {
738
+ // Tests failed! Auto-rollback to restore original workspace
739
+ await undoLastClean(root);
740
+ verification = {
741
+ enabled: true,
742
+ passed: false,
743
+ rolledBack: true,
744
+ command: testCmd,
745
+ error: `Project tests failed after code repairs: ${testErr?.message || String(testErr)}. Workspace was automatically restored.`
746
+ };
747
+ warnings.push("Verification failed! Workspace was automatically rolled back to prevent regression.");
748
+ }
749
+ }
750
+ else {
751
+ warnings.push("No automated test suite detected in workspace to verify changes.");
752
+ }
753
+ }
754
+ }
755
+ const codeFixesApplied = (apply && (!verification || !verification.rolledBack)) ? codeFixes.length : 0;
756
+ return {
757
+ root,
758
+ generatedAt: new Date().toISOString(),
759
+ applied: apply,
760
+ dryRun: !apply,
761
+ backupId,
762
+ verification,
763
+ junkItems,
764
+ orphanFiles,
765
+ codeFixes,
766
+ stats: {
767
+ junkFound: junkItems.length,
768
+ junkDeleted: (apply && (!verification || !verification.rolledBack)) ? junkDeleted : 0,
769
+ bytesReclaimed,
770
+ codeFixesFound: codeFixes.length,
771
+ codeFixesApplied,
772
+ orphanFilesFound: orphanFiles.length
773
+ },
774
+ warnings
775
+ };
776
+ }
777
+ function formatBytes(bytes) {
778
+ if (bytes < 1024)
779
+ return `${bytes} B`;
780
+ if (bytes < 1024 * 1024)
781
+ return `${(bytes / 1024).toFixed(1)} KB`;
782
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
783
+ }
784
+ export function formatCleanReport(result) {
785
+ const modeText = result.applied ? "**APPLIED** (Deleted junk & saved fixes)" : "**DRY RUN** (Preview only — pass `--apply` to execute)";
786
+ const lines = [
787
+ "# ANVIL Workspace Clean & Repair",
788
+ "",
789
+ `- **Target:** \`${result.root}\``,
790
+ `- **Status:** ${modeText}`,
791
+ `- **Junk items:** \`${result.stats.junkFound}\` found (${formatBytes(result.stats.bytesReclaimed)} space)${result.applied ? ` · \`${result.stats.junkDeleted}\` deleted` : ""}`,
792
+ `- **Code auto-fixes:** \`${result.stats.codeFixesFound}\` available${result.applied ? ` · \`${result.stats.codeFixesApplied}\` applied` : ""}`,
793
+ `- **Orphan files detected:** \`${result.stats.orphanFilesFound}\``,
794
+ ...(result.backupId ? [`- **Rollback backup:** \`${result.backupId}\` (Run \`anvil undo\` to restore anytime)`] : []),
795
+ ...(result.verification ? [(result.verification.passed ? `- **Self-Healing Verification:** PASSED (\`${result.verification.command}\`)` : `- **Self-Healing Verification:** FAILED -> AUTO-ROLLED BACK (\`${result.verification.command}\`)`)] : []),
796
+ `- **Timestamp:** \`${result.generatedAt}\``,
797
+ ""
798
+ ];
799
+ if (result.junkItems.length > 0) {
800
+ lines.push("## Farzi & Junk Artifacts");
801
+ for (const item of result.junkItems.slice(0, 50)) {
802
+ lines.push(`- \`[${item.category.toUpperCase()}]\` \`${item.path}\` (${formatBytes(item.sizeBytes)}) — ${item.reason}`);
803
+ }
804
+ if (result.junkItems.length > 50) {
805
+ lines.push(`- *...and ${result.junkItems.length - 50} more items.*`);
806
+ }
807
+ lines.push("");
808
+ }
809
+ else {
810
+ lines.push("## Farzi & Junk Artifacts", "- No OS, editor, download, or log clutter detected. Workspace is clean!", "");
811
+ }
812
+ if (result.codeFixes.length > 0) {
813
+ lines.push("## Code Auto-Fixes");
814
+ for (const fix of result.codeFixes.slice(0, 30)) {
815
+ lines.push(`- \`[${fix.type.toUpperCase()}]\` \`${fix.file}\`: ${fix.detail}`);
816
+ }
817
+ if (result.codeFixes.length > 30) {
818
+ lines.push(`- *...and ${result.codeFixes.length - 30} more code fixes.*`);
819
+ }
820
+ lines.push("");
821
+ }
822
+ if (result.orphanFiles.length > 0) {
823
+ lines.push("## Orphan & Unreferenced Source Modules");
824
+ lines.push("> [!NOTE] These files exist in the project but are never imported or linked by other modules. Review them to decide if they should be pruned.");
825
+ for (const orphan of result.orphanFiles.slice(0, 20)) {
826
+ lines.push(`- \`${orphan.file}\` (${orphan.lines} lines) — ${orphan.reason}`);
827
+ }
828
+ if (result.orphanFiles.length > 20) {
829
+ lines.push(`- *...and ${result.orphanFiles.length - 20} more unreferenced files.*`);
830
+ }
831
+ lines.push("");
832
+ }
833
+ if (result.warnings.length > 0) {
834
+ lines.push("## Warnings");
835
+ for (const w of result.warnings) {
836
+ lines.push(`- ${w}`);
837
+ }
838
+ lines.push("");
839
+ }
840
+ if (result.dryRun) {
841
+ lines.push("> [!TIP] Run `anvil clean . --apply` to delete junk files, or `anvil clean . --apply --fix` to clean clutter AND auto-repair code issues.");
842
+ lines.push("");
843
+ }
844
+ lines.push("_Generated by ANVIL Workspace Cleaner._");
845
+ return lines.join("\n");
846
+ }
847
+ //# sourceMappingURL=project-cleaner.js.map