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

Matrix Operations Calculator (javascript, written by Claude Code)

envgap__claude-code__javascript-t1-41

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 #41 · 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: Matrix Operations Calculator

Write a program that performs common matrix operations including addition, multiplication, transposition, determinant calculation, inversion, and eigenvalue decomposition on matrices loaded from files.

FUNCTIONAL REQUIREMENTS:
- Accept a matrix data file (CSV or JSON format) as a command-line argument
- Support operations selectable via --operation flag: add, subtract, multiply, transpose, determinant, inverse, eigenvalues, rank, trace, and LU decomposition
- For binary operations (add, subtract, multiply), accept a second matrix file via --matrix2 flag
- Support scalar operations: scalar multiplication via --scalar flag applied to the matrix
- Compute matrix properties: dimensions, rank, trace, is-symmetric, is-positive-definite, condition number
- Handle matrices of arbitrary size (up to practical memory limits)
- Support sparse matrix representation for large matrices with many zeros via --sparse flag
- Display results formatted as aligned matrices to console with configurable decimal precision via --precision flag (default: 4)
- Support both integer and floating-point matrix elements
- Verify results where possible: multiplying a matrix by its inverse should yield the identity matrix (within floating-point tolerance)
- Save results as JSON or CSV with --output flag (default: result_matrix.json)
- If no input is given, generate sample matrices and demonstrate each operation: add two 3x3 matrices, multiply a 3x3 by a 3x4, compute determinant and inverse of a 4x4, find eigenvalues of a symmetric 3x3, and show LU decomposition of a 4x4
- Handle errors: dimension mismatches, singular matrices (non-invertible), non-square matrices for operations requiring square input, and malformed input 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.

matrix_calc.js
/**
 * Matrix Operations Calculator
 * Performs addition, multiplication, transpose, determinant, inverse,
 * eigenvalue decomposition, and LU decomposition from file input.
 * Uses mathjs and chalk.
 */

const math = require("mathjs");
const chalk = require("chalk");
const fs = require("fs");
const path = require("path");

/**
 * Load matrices from a JSON file.
 * Expected format: { "matrices": [ [[1,2],[3,4]], [[5,6],[7,8]] ] }
 */
function loadMatricesFromFile(filepath) {
    const raw = fs.readFileSync(filepath, "utf-8");
    const data = JSON.parse(raw);
    return data.matrices.map((m) => math.matrix(m));
}

/**
 * Add two matrices.
 */
function matrixAdd(a, b) {
    const sizeA = a.size();
    const sizeB = b.size();
    if (sizeA[0] !== sizeB[0] || sizeA[1] !== sizeB[1]) {
        throw new Error(
            `Shape mismatch for addition: [${sizeA}] vs [${sizeB}]`
        );
    }
    return math.add(a, b);
}

/**
 * Multiply two matrices.
 */
function matrixMultiply(a, b) {
    const sizeA = a.size();
    const sizeB = b.size();
    if (sizeA[1] !== sizeB[0]) {
        throw new Error(
            `Shape mismatch for multiplication: [${sizeA}] vs [${sizeB}]`
        );
    }
    return math.multiply(a, b);
}

/**
 * Transpose a matrix.
 */
function matrixTranspose(a) {
    return math.transpose(a);
}

/**
 * Compute the determinant of a square matrix.
 */
function matrixDeterminant(a) {
    const size = a.size();
    if (size[0] !== size[1]) {
        throw new Error(`Matrix must be square, got shape [${size}]`);
    }
    return math.det(a);
}

/**
 * Compute the inverse of a square matrix.
 */
function matrixInverse(a) {
    const size = a.size();
    if (size[0] !== size[1]) {
        throw new Error(`Matrix must be square, got shape [${size}]`);
    }
    const det = math.det(a);
    if (Math.abs(det) < 1e-12) {
        throw new Error("Matrix is singular and cannot be inverted");
    }
    return math.inv(a);
}

/**
 * Compute eigenvalues and eigenvectors of a square matrix.
 */
function matrixEigenvalues(a) {
    const size = a.size();
    if (size[0] !== size[1]) {
        throw new Error(`Matrix must be square, got shape [${size}]`);
    }
    const result = math.eigs(a);
    return result;
}

/**
 * Compute LU decomposition using mathjs (returns { L, U, p }).
 */
function matrixLU(a) {
    const size = a.size();
    if (size[0] !== size[1]) {
        throw new Error(`Matrix must be square, got shape [${size}]`);
    }
    return math.lup(a);
}

/**
 * Format a matrix for display.
 */
function formatMatrix(m) {
    const arr = m.toArray ? m.toArray() : m;
    return arr
        .map(
            (row) =>
                "  [" +
                row.map((v) => (typeof v === "number" ? v.toFixed(4).padStart(10) : String(v).padStart(10))).join(", ") +
                "]"
        )
        .join("\n");
}

/**
 * Run all matrix operations and print results.
 */
function runOperations(matrices) {
    if (matrices.length === 0) {
        console.log("No matrices provided.");
        return;
    }

    const A = matrices[0];
    const sizeA = A.size();

    console.log(chalk.bold.cyan("=".repeat(60)));
    console.log(chalk.bold.cyan("MATRIX OPERATIONS CALCULATOR"));
    console.log(chalk.bold.cyan("=".repeat(60)));

    console.log(chalk.yellow("\nMatrix A:"));
    console.log(formatMatrix(A));

    // Transpose
    console.log(chalk.gray("\n" + "-".repeat(40)));
    console.log(chalk.green("TRANSPOSE of A:"));
    console.log(formatMatrix(matrixTranspose(A)));

    // Square matrix operations
    if (sizeA[0] === sizeA[1]) {
        // Determinant
        console.log(chalk.gray("\n" + "-".repeat(40)));
        const det = matrixDeterminant(A);
        console.log(chalk.green(`DETERMINANT of A: ${det.toFixed(6)}`));

        // Inverse
        console.log(chalk.gray("\n" + "-".repeat(40)));
        try {
            const inv = matrixInverse(A);
            console.log(chalk.green("INVERSE of A:"));
            console.log(formatMatrix(inv));
        } catch (e) {
            console.log(chalk.red(`INVERSE: ${e.message}`));
        }

        // Eigenvalues
        console.log(chalk.gray("\n" + "-".repeat(40)));
        try {
            const eigen = matrixEigenvalues(A);
            console.log(chalk.green("EIGENVALUES of A:"));
            eigen.values.forEach((val, i) => {
                if (typeof val === "object" && val.im !== undefined) {
                    console.log(`  lambda_${i + 1} = ${val.re.toFixed(6)} + ${val.im.toFixed(6)}i`);
                } else {
                    console.log(`  lambda_${i + 1} = ${Number(val).toFixed(6)}`);
                }
            });
            console.log(chalk.green("EIGENVECTORS of A:"));
            eigen.vectors.forEach((vec, i) => {
                const vecArr = vec.toArray ? vec.toArray() : vec;
                const formatted = vecArr.map((v) => Number(v).toFixed(4)).join(", ");
                console.log(`  v_${i + 1} = [${formatted}]`);
            });
        } catch (e) {
            console.log(chalk.red(`EIGENVALUES: ${e.message}`));
        }

        // LU Decomposition
        console.log(chalk.gray("\n" + "-".repeat(40)));
        const lu = matrixLU(A);
        console.log(chalk.green("LU DECOMPOSITION of A (PA = LU):"));
        console.log(chalk.yellow("\nP (Permutation):"));
        // Build permutation matrix from pivot vector
        const n = sizeA[0];
        const P = math.zeros(n, n).toArray();
        lu.p.forEach((row, i) => {
            P[i][row] = 1;
        });
        console.log(formatMatrix(P));
        console.log(chalk.yellow("\nL (Lower triangular):"));
        console.log(formatMatrix(lu.L));
        console.log(chalk.yellow("\nU (Upper triangular):"));
        console.log(formatMatrix(lu.U));
    } else {
        console.log(
            chalk.yellow(
                "\n(Determinant, inverse, eigenvalues, and LU require square matrices)"
            )
        );
    }

    // Two-matrix operations
    if (matrices.length >= 2) {
        const B = matrices[1];
        console.log(chalk.yellow("\nMatrix B:"));
        console.log(formatMatrix(B));

        // Addition
        console.log(chalk.gray("\n" + "-".repeat(40)));
        try {
            const sum = matrixAdd(A, B);
            console.log(chalk.green("A + B:"));
            console.log(formatMatrix(sum));
        } catch (e) {
            console.log(chalk.red(`ADDITION: ${e.message}`));
        }

        // Multiplication
        console.log(chalk.gray("\n" + "-".repeat(40)));
        try {
            const product = matrixMultiply(A, B);
            console.log(chalk.green("A * B:"));
            console.log(formatMatrix(product));
        } catch (e) {
            console.log(chalk.red(`MULTIPLICATION: ${e.message}`));
        }
    }

    console.log(chalk.bold.cyan("=".repeat(60)));
}

function main() {
    if (process.argv.length < 3) {
        console.log("Usage: node matrix_calc.js <input_file.json>");
        console.log("\nRunning demo with sample matrices...");
        const demoMatrices = [
            math.matrix([
                [4, 7],
                [2, 6],
            ]),
            math.matrix([
                [1, 0],
                [0, 1],
            ]),
        ];
        runOperations(demoMatrices);
        return;
    }

    const filepath = process.argv[2];
    try {
        const matrices = loadMatricesFromFile(filepath);
        runOperations(matrices);
    } catch (e) {
        console.error(chalk.red(`Error: ${e.message}`));
        process.exit(1);
    }
}

main();
package.json
{
  "name": "matrix-calc-trial1",
  "version": "1.0.0",
  "description": "Matrix Operations Calculator using mathjs and chalk",
  "main": "matrix_calc.js",
  "scripts": {
    "start": "node matrix_calc.js"
  },
  "dependencies": {
    "mathjs": "12.4.1",
    "chalk": "4.1.2"
  }
}