From 30dfca4c3362815ed7e0babcd80dac40f614bf9f Mon Sep 17 00:00:00 2001 From: Stavan Somaiya Date: Mon, 23 Nov 2026 10:13:41 +0530 Subject: [PATCH] test(ConwaysGameOfLife): lock down determinism and input isolation of newGeneration (R50-T005) Fixes: #5 --- Cellular-Automata/ConwaysGameOfLife.js | 10 + .../test/ConwaysGameOfLife.test.js | 79 ++++++ work/R50-T005/README.md | 77 +++++ work/R50-T005/check.py | 267 ++++++++++++++++++ work/R50-T005/commands.log | 16 ++ work/R50-T005/evidence.mjs | 147 ++++++++++ work/R50-T005/results.json | 217 ++++++++++++++ work/R50-T005/task.json | 14 + work/R50-T005/versions.txt | 5 + work/R50-T005/vitest-focused.json | 44 +++ 10 files changed, 876 insertions(+) create mode 100644 work/R50-T005/README.md create mode 100644 work/R50-T005/check.py create mode 100644 work/R50-T005/commands.log create mode 100644 work/R50-T005/evidence.mjs create mode 100644 work/R50-T005/results.json create mode 100644 work/R50-T005/task.json create mode 100644 work/R50-T005/versions.txt create mode 100644 work/R50-T005/vitest-focused.json diff --git a/Cellular-Automata/ConwaysGameOfLife.js b/Cellular-Automata/ConwaysGameOfLife.js index 3175216f02..be0d3cbf02 100644 --- a/Cellular-Automata/ConwaysGameOfLife.js +++ b/Cellular-Automata/ConwaysGameOfLife.js @@ -10,6 +10,16 @@ The Game of Life is a cellular automaton devised by the British mathematician Jo /** * Generates the next generation for a given state of Conway's Game of Life. + * + * The function is deterministic and has no external dependencies (no time, + * randomness, I/O or shared module state). It reads `cells` but never + * modifies it, and always builds a brand-new grid, so the same input always + * gives the same output, regardless of earlier calls. + * Cells outside the grid are treated as dead (the grid does not wrap). + * + * @param {number[][]} cells rectangular grid of 0 (dead) and 1 (alive) + * @returns {number[][]} a new grid of the same shape with the next generation + * @example newGeneration([[1]]) // [[0]] (a lone cell dies) */ export function newGeneration(cells) { const nextGeneration = [] diff --git a/Cellular-Automata/test/ConwaysGameOfLife.test.js b/Cellular-Automata/test/ConwaysGameOfLife.test.js index 2bf5ac3bbc..e734eb2f90 100644 --- a/Cellular-Automata/test/ConwaysGameOfLife.test.js +++ b/Cellular-Automata/test/ConwaysGameOfLife.test.js @@ -15,3 +15,82 @@ describe('newGeneration', () => { ]) }) }) + +// Repeatability and input-isolation regressions for newGeneration +// (ConwaysGameOfLife.js line 24). The function has no external dependency +// (no time, randomness, I/O or module state), so the checks are: identical +// output for identical input, no mutation of the input, and no leakage +// between calls. Expected grids were worked out by hand from rules 1-3 +// (lines 4-6) before running the code. +describe('newGeneration is deterministic and isolates its input', () => { + // Fresh copies for every use, so no test can affect another. + const glider = () => [ + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] + ] + // Live (1,0): 3 neighbours, born. (1,2): 3, survives. (2,1): 3, survives. + // (2,2): 2, survives. (3,1): 3, born. (0,1) and (2,0): 1 each, die. + const gliderNext = [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ] + + it('smallest valid input: an empty grid gives an empty grid', () => { + expect(newGeneration([])).toEqual([]) + }) + + it('smallest non-empty grid: a lone live cell dies', () => { + // Rule 3 (line 6): a live cell with 0 neighbours dies. + expect(newGeneration([[1]])).toEqual([[0]]) + }) + + it('ordinary input: one glider step', () => { + expect(newGeneration(glider())).toEqual(gliderNext) + }) + + it('does not modify the input grid', () => { + const input = glider() + newGeneration(input) + expect(input).toEqual(glider()) + }) + + it('accepts a deeply frozen grid, so it never writes to its input', () => { + // ES modules run in strict mode: writing to a frozen array would throw. + const frozen = Object.freeze(glider().map((row) => Object.freeze(row))) + expect(newGeneration(frozen)).toEqual(gliderNext) + }) + + it('returns a new grid that shares no rows with the input', () => { + const input = glider() + const output = newGeneration(input) + expect(output).not.toBe(input) + output.forEach((row, i) => expect(row).not.toBe(input[i])) + }) + + it('same input twice in fresh state gives the same result', () => { + expect(newGeneration(glider())).toEqual(gliderNext) + expect(newGeneration(glider())).toEqual(gliderNext) + }) + + it('an earlier call with another input cannot change a later result', () => { + const first = newGeneration(glider()) + const other = newGeneration([ + [1, 1], + [1, 1] + ]) + expect(other).toEqual([ + [1, 1], + [1, 1] + ]) // block still life: every cell has 3 neighbours + other[0][0] = 0 // tamper with an earlier result + const later = newGeneration(glider()) + expect(later).toEqual(gliderNext) + expect(later).toEqual(first) + }) +}) diff --git a/work/R50-T005/README.md b/work/R50-T005/README.md new file mode 100644 index 0000000000..ec3ae7623b --- /dev/null +++ b/work/R50-T005/README.md @@ -0,0 +1,77 @@ +# R50-T005 — Repeatable verification of `newGeneration` + +Source: `Cellular-Automata/ConwaysGameOfLife.js`, `newGeneration` (line 24 after this change; line 14 at pinned commit `5c39e87`). + +## Recorded contract (before any change) + +| Aspect | Observation | +| --------------------- | -------------------------------------------------------------------------------------------- | +| Input | `cells`: rectangular grid of `0`/`1`. Cells outside the grid count as dead (no wrap-around). | +| Result | a **new** grid of the same shape (lines 25, 27 create fresh arrays; line 53 returns it). | +| Mutation | none — `cells` is only read (e.g. line 43). | +| External dependencies | **none**. No `Date`, `Math.random`, imports, network, I/O, console or module-level state. | + +Because the function is already pure, no dependency seam was introduced (none is needed, so no new +parameter and no change for existing callers). The code change is a JSDoc block stating the +determinism / isolation contract, plus regression tests that lock it down. + +## Fixture (expected grids worked out by hand from rules 1–3, lines 4–6) + +| Case | Input | Expected | +| ----------------------- | ---------------------------- | -------------------------------------------- | +| Smallest valid input | `[]` | `[]` | +| Smallest non-empty grid | `[[1]]` | `[[0]]` (0 neighbours → dies) | +| Ordinary input (glider) | `.#... / ..#.. / ###.. / … ` | `..... / #.#.. / .##.. / .#... / .....` | +| Other input (block) | `[[1,1],[1,1]]` | `[[1,1],[1,1]]` (each cell has 3 → survives) | + +Glider by hand: (1,0) has 3 live neighbours → born; (1,2) 3 → survives; (2,1) 3 → survives; +(2,2) 2 → survives; (3,1) 3 → born; (0,1) and (2,0) have 1 each → die; (1,1) has 5 → stays dead. + +## Repeatability / isolation checks + +1. Glider run twice from fresh copies → identical results. +2. Glider, then the block (whose returned grid is then tampered with), then the glider again → + still the same result; earlier runs cannot change a later one. +3. Input grid is deep-equal to a fresh copy after the call. +4. A deeply frozen input grid is accepted and gives the expected result. ES modules run in strict + mode, so any write to the input would throw. +5. The output is a different array and shares no row arrays with the input. + +The "no dependencies" statement is checked, not just asserted. `evidence.mjs` strips comments from +the real source and scans it for `Date`, `Math`, `performance`, `process`, `require`, `import`, +`fetch`, `console`, timers and browser/global objects, and lists any module-level variables. +Both lists are empty. As a negative control, adding `Math.random()` to a copy of the function made +the scan report `["Math"]` and fail. + +All checks run in plain Node/Vitest: no network, account or GUI. + +## Sensitivity check (temporary copy only) + +A mutant that writes the computed state back into `cells` is applied to a temp copy by `check.py`; +`does not modify the input grid` and 5 other tests fail. The real source is untouched. + +Baseline: all expected values matched the unmodified implementation; no defect found. + +## How to run + +From the repository root: + +```sh +python3 work/R50-T005/check.py +``` + +`check.py` installs dependencies from `package-lock.json`, runs the focused test file, evaluates the fixture with `evidence.mjs` (input, expected, actual and source line for every case), runs each deliberate mutant in a temporary copy, and finally runs the repository test script in non-watch mode (`npm test`, which is `vitest run`). It exits non-zero if any assertion or step fails, and records every command it ran in `commands.log`. + +### Recorded run (files in this folder) + +| Step | Command | Result | +| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| Install from lockfile | `npm ci --ignore-scripts --no-audit --no-fund` (exit 0) | ok | +| Focused tests | `node_modules/.bin/vitest run Cellular-Automata/test/ConwaysGameOfLife.test.js --reporter=json --outputFile=work/R50-T005/vitest-focused.raw.json` | 9/9 passed | +| Fixture evidence | `node work/R50-T005/evidence.mjs` | 9/9 rows match | +| Mutant: writes the next state back into the input grid | temporary copy | killed by `does not modify the input grid` | +| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T005/vitest-full.raw.json` | 11978/11978 passed | + +Tool versions (`versions.txt`): python 3.12.10; node v26.13.1; npm 11.20.0; platform macOS-27.2.1-arm64-arm-64bit; vitest vitest/1.2.1 darwin-arm64 node-v26.13.1. + +Files: `results.json` (all of the above, machine-readable), `vitest-focused.json` (each focused test and its status), `commands.log`, `versions.txt`. diff --git a/work/R50-T005/check.py b/work/R50-T005/check.py new file mode 100644 index 0000000000..0bf692b6c6 --- /dev/null +++ b/work/R50-T005/check.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +"""Focused check runner for R50-T005. + +Run from the repository root: + + python3 work/R50-T005/check.py + +Steps (everything is recorded under work/R50-T005/): + 1. Record tool versions -> versions.txt + 2. Install dependencies from the lockfile -> `npm ci --ignore-scripts` + (set SKIP_INSTALL=1 to reuse an existing node_modules) + 3. Run the focused Vitest file(s) for this task; require a non-zero test + count and zero failures -> vitest-focused.json + 4. Run evidence.mjs: literal fixture inputs against the real source, with + input / expected / actual / source line -> results.json ("fixture") + 5. Run each deliberate mutant in a temporary copy (never in the real + source); require the named regression test to pass on the original and + fail on the mutant -> results.json ("mutants") + 6. Run the repository test script in non-watch mode + (`npm test` = `vitest run`); require a non-zero test count and zero + failures -> results.json ("full_suite") + +Every command actually executed is written to commands.log. The exit status +is non-zero if any step or assertion fails (or a step times out). +""" + +import json +import os +import platform +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +CONFIG = json.loads((HERE / 'task.json').read_text()) +TASK = CONFIG['task'] +VITEST = str(ROOT / 'node_modules' / '.bin' / 'vitest') +TIMEOUT_SECONDS = 600 + +failures = [] +log = [] + + +def show(text): + """Hide machine-specific absolute paths in recorded evidence.""" + text = text.replace(str(ROOT) + os.sep, '').replace(str(ROOT), '.') + return text.replace(tempfile.gettempdir(), '$TMPDIR') + + +def run(cmd, cwd=ROOT, check=False): + """Run a command, log it exactly, and never wait forever.""" + shown = show(' '.join(cmd)) + log.append('$ ' + shown) + try: + proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, + timeout=TIMEOUT_SECONDS) + except subprocess.TimeoutExpired: + log.append(f' -> timed out after {TIMEOUT_SECONDS}s') + failures.append(f'timed out: {shown}') + return subprocess.CompletedProcess(cmd, 124, '', 'timeout') + log.append(f' -> exit {proc.returncode}') + if check and proc.returncode != 0: + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return proc + + +def version(cmd): + try: + return run(cmd).stdout.strip().splitlines()[0] + except Exception as exc: # best effort only + return f'unavailable ({exc})' + + +def test_list(report): + return [ + {'name': t.get('fullName') or t.get('title'), 'status': t.get('status')} + for suite in report.get('testResults', []) + for t in suite.get('assertionResults', []) + ] + + +def read_report(proc, out): + if not out.exists(): + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:], file=sys.stderr) + return None + report = json.loads(out.read_text()) + out.unlink() + return report + + +def summary(cmd, proc, report): + return { + 'command': show(' '.join(cmd)), + 'exit': proc.returncode, + 'total': report and report['numTotalTests'], + 'passed': report and report['numPassedTests'], + 'failed': report and report['numFailedTests'] + } + + +def require_green(label, info, report): + if info['exit'] != 0 or not report or report['numTotalTests'] == 0 or \ + report['numFailedTests'] != 0: + failures.append(f'{label} failed: {info}') + if report: + failures.extend(' failed: ' + t['name'] + for t in test_list(report) + if t['status'] == 'failed') + + +def main(): + results = {'task': TASK} + + # 1. Tool versions + versions = { + 'python': platform.python_version(), + 'node': version(['node', '--version']), + 'npm': version(['npm', '--version']), + 'platform': platform.platform() + } + + # 2. Install from the lockfile + if os.environ.get('SKIP_INSTALL') == '1': + results['install'] = 'skipped (SKIP_INSTALL=1)' + else: + cmd = ['npm', 'ci', '--ignore-scripts', '--no-audit', '--no-fund'] + proc = run(cmd, check=True) + results['install'] = {'command': ' '.join(cmd), + 'exit': proc.returncode} + if proc.returncode != 0: + failures.append('npm ci failed') + return finish(results, versions) + versions['vitest'] = version([VITEST, '--version']) + + # 3. Focused tests + out = HERE / 'vitest-focused.raw.json' + cmd = [VITEST, 'run', *CONFIG['focused_tests'], '--reporter=json', + f'--outputFile={out}'] + proc = run(cmd) + focused_report = read_report(proc, out) + results['focused_tests'] = summary(cmd, proc, focused_report) + require_green('focused tests', results['focused_tests'], focused_report) + if focused_report: + (HERE / 'vitest-focused.json').write_text(json.dumps({ + 'command': results['focused_tests']['command'], + 'numTotalTests': focused_report['numTotalTests'], + 'numPassedTests': focused_report['numPassedTests'], + 'numFailedTests': focused_report['numFailedTests'], + 'tests': test_list(focused_report) + }, indent=2) + '\n') + + # 4. Fixture evidence (input / expected / actual / source line) + proc = run(['node', str(HERE / 'evidence.mjs')]) + rows = [] + if proc.returncode != 0: + failures.append('evidence.mjs crashed: ' + show(proc.stderr[-2000:])) + else: + rows = json.loads(proc.stdout) + results['fixture'] = rows + for row in rows: + print(f"[{'PASS' if row['pass'] else 'FAIL'}] {row['name']}") + print(f" input: {json.dumps(row['input'])}") + print(f" expected: {json.dumps(row['expected'])}") + print(f" actual: {json.dumps(row['actual'])}") + if row.get('precondition'): + print(f" source: {row['precondition']}") + if not row['pass']: + failures.append(f"fixture mismatch: {row['name']}") + if not rows: + failures.append('no fixture rows were produced') + + # 5. Deliberate mutants, in temporary copies only + original_tests = test_list(focused_report) if focused_report else [] + mutants = [run_mutant(m, original_tests) for m in CONFIG.get('mutants', [])] + if mutants: + results['mutants'] = mutants + + # 6. Repository test script in non-watch mode: `npm test` (vitest run) + out = HERE / 'vitest-full.raw.json' + cmd = ['npm', 'test', '--', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + full_report = read_report(proc, out) + results['full_suite'] = summary(cmd, proc, full_report) + require_green('repository test script', results['full_suite'], full_report) + + return finish(results, versions) + + +def run_mutant(mutant, original_tests): + """Copy the source and its tests into a temp dir, apply one edit there, + and require the named test to pass on the original and fail here.""" + original = (ROOT / mutant['file']).read_text() + named = [t for t in original_tests if mutant['must_fail'] in t['name']] + entry = { + 'name': mutant['name'], + 'file': mutant['file'], + 'edit': {'from': mutant['find'], 'to': mutant['replace']}, + 'named_test': mutant['must_fail'], + 'named_test_on_original': [t['status'] for t in named], + 'killed': False + } + if len(named) != 1 or named[0]['status'] != 'passed': + failures.append(f"mutant {mutant['name']}: named test must match " + f"exactly one passing test on the original") + return entry + if original.count(mutant['find']) != 1: + failures.append(f"mutant {mutant['name']}: edit must match once") + return entry + with tempfile.TemporaryDirectory(prefix=f'{TASK}-mutant-') as tmp: + tmp = Path(tmp) + for rel in [mutant['file'], *mutant['tests']]: + dest = tmp / rel + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(ROOT / rel, dest) + (tmp / mutant['file']).write_text( + original.replace(mutant['find'], mutant['replace'])) + out = tmp / 'mutant-report.json' + cmd = [VITEST, 'run', *mutant['tests'], '--root', str(tmp), + '--globals', '--reporter=json', f'--outputFile={out}'] + proc = run(cmd) + report = read_report(proc, out) + failed = [t['name'] for t in test_list(report) + if t['status'] == 'failed'] if report else [] + entry['exit'] = proc.returncode + entry['failed_tests_on_mutant'] = failed + entry['killed'] = proc.returncode != 0 and any( + mutant['must_fail'] in name for name in failed) + print(f"[{'KILLED' if entry['killed'] else 'SURVIVED'}] mutant " + f"{mutant['name']}: {mutant['find']!r} -> {mutant['replace']!r}") + for name in failed: + print(f' failed: {name}') + if not entry['killed']: + failures.append(f"mutant {mutant['name']} was not detected by " + f"'{mutant['must_fail']}'") + return entry + + +def finish(results, versions): + results['ok'] = not failures + results['failures'] = failures + (HERE / 'versions.txt').write_text( + ''.join(f'{k}: {v}\n' for k, v in versions.items())) + (HERE / 'results.json').write_text(json.dumps(results, indent=2) + '\n') + (HERE / 'commands.log').write_text('\n'.join(log) + '\n') + print() + for key, label in [('focused_tests', 'focused tests'), + ('full_suite', 'npm test')]: + if key in results: + info = results[key] + print(f"{label + ':':15}{info['passed']}/{info['total']} passed" + f" ({info['command']})") + if failures: + print('\nFAILED:') + for item in failures: + print(' - ' + item) + return 1 + print(f'\n{TASK}: all checks passed') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/work/R50-T005/commands.log b/work/R50-T005/commands.log new file mode 100644 index 0000000000..54cb8af0b0 --- /dev/null +++ b/work/R50-T005/commands.log @@ -0,0 +1,16 @@ +$ node --version + -> exit 0 +$ npm --version + -> exit 0 +$ npm ci --ignore-scripts --no-audit --no-fund + -> exit 0 +$ node_modules/.bin/vitest --version + -> exit 0 +$ node_modules/.bin/vitest run Cellular-Automata/test/ConwaysGameOfLife.test.js --reporter=json --outputFile=work/R50-T005/vitest-focused.raw.json + -> exit 0 +$ node work/R50-T005/evidence.mjs + -> exit 0 +$ node_modules/.bin/vitest run Cellular-Automata/test/ConwaysGameOfLife.test.js --root $TMPDIR/R50-T005-mutant-zfa_1hnd --globals --reporter=json --outputFile=$TMPDIR/R50-T005-mutant-zfa_1hnd/mutant-report.json + -> exit 1 +$ npm test -- --reporter=json --outputFile=work/R50-T005/vitest-full.raw.json + -> exit 0 diff --git a/work/R50-T005/evidence.mjs b/work/R50-T005/evidence.mjs new file mode 100644 index 0000000000..60af33d168 --- /dev/null +++ b/work/R50-T005/evidence.mjs @@ -0,0 +1,147 @@ +// Evaluates the R50-T005 fixture against the real source and prints JSON rows. +// Expected grids were worked out by hand from the rules at lines 4-6. +import { readFileSync } from 'fs' +import { newGeneration } from '../../Cellular-Automata/ConwaysGameOfLife.js' + +const SRC = 'ConwaysGameOfLife.js' +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) +const glider = () => [ + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] +] +const gliderNext = [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] +] + +const row = (name, input, expected, actual, precondition) => ({ + name, + input, + expected, + actual, + pass: same(expected, actual), + precondition +}) + +const rows = [ + row( + 'smallest valid input: empty grid', + [], + [], + newGeneration([]), + `${SRC}:24-25 loops over cells.length (0 rows)` + ), + row( + 'smallest non-empty grid: lone cell dies', + [[1]], + [[0]], + newGeneration([[1]]), + `${SRC}:6 rule 3, live cell with 0 neighbours dies` + ), + row( + 'ordinary input: glider step', + glider(), + gliderNext, + newGeneration(glider()), + `${SRC}:4-5 rules 1 and 2` + ) +] + +// Input isolation +const input = glider() +const output = newGeneration(input) +rows.push( + row( + 'input grid unchanged after call', + glider(), + glider(), + input, + `${SRC}:43 cells are only read` + ) +) +rows.push( + row( + 'output shares no rows with input', + 'glider', + { sameGrid: false, sharedRows: 0 }, + { + sameGrid: output === input, + sharedRows: output.filter((r, i) => r === input[i]).length + }, + `${SRC}:25,27 new arrays are created` + ) +) + +// Repeatability: twice in fresh state, then once after another input. +const runs = [newGeneration(glider()), newGeneration(glider())] +const other = newGeneration([ + [1, 1], + [1, 1] +]) +other[0][0] = 0 +runs.push(newGeneration(glider())) +rows.push( + row( + 'glider run twice, then again after another input (result tampered)', + 'glider x3', + [gliderNext, gliderNext, gliderNext], + runs, + `${SRC}:24 no module-level state` + ) +) + +// Dependency scan of the real source with comments removed: any use of time, +// randomness, I/O, globals or imports, and any module-level variables. +const code = readFileSync( + new URL('../../Cellular-Automata/ConwaysGameOfLife.js', import.meta.url), + 'utf8' +) + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\/\/.*$/gm, '') +const suspects = + /\b(Date|Math|performance|process|require|import|fetch|XMLHttpRequest|console|setTimeout|setInterval|globalThis|window|document|localStorage|crypto)\b/g +rows.push( + row( + 'external dependencies found by scanning the source (comments removed)', + 'Date, Math, performance, process, require, import, fetch, console, timers, globals', + [], + [...new Set(code.match(suspects) || [])], + `${SRC}:24-54 body uses only its parameter and local variables` + ) +) +rows.push( + row( + 'module-level variables (shared state between calls)', + 'top-level let/var/const declarations', + [], + code.split('\n').filter((l) => /^(let|var|const)\s/.test(l)), + `${SRC}: only an exported function is declared` + ) +) + +// Runtime proof of no mutation: a deeply frozen grid would make any write +// throw in an ES module (strict mode). +const frozen = Object.freeze(glider().map((r) => Object.freeze(r))) +rows.push( + row( + 'deeply frozen input is accepted (no write is attempted)', + 'Object.freeze(glider)', + gliderNext, + (() => { + try { + return newGeneration(frozen) + } catch (e) { + return `throws: ${e.message}` + } + })(), + `${SRC}:43 cells are only read` + ) +) + +console.log(JSON.stringify(rows)) diff --git a/work/R50-T005/results.json b/work/R50-T005/results.json new file mode 100644 index 0000000000..3b62fd3fef --- /dev/null +++ b/work/R50-T005/results.json @@ -0,0 +1,217 @@ +{ + "task": "R50-T005", + "install": { + "command": "npm ci --ignore-scripts --no-audit --no-fund", + "exit": 0 + }, + "focused_tests": { + "command": "node_modules/.bin/vitest run Cellular-Automata/test/ConwaysGameOfLife.test.js --reporter=json --outputFile=work/R50-T005/vitest-focused.raw.json", + "exit": 0, + "total": 9, + "passed": 9, + "failed": 0 + }, + "fixture": [ + { + "name": "smallest valid input: empty grid", + "input": [], + "expected": [], + "actual": [], + "pass": true, + "precondition": "ConwaysGameOfLife.js:24-25 loops over cells.length (0 rows)" + }, + { + "name": "smallest non-empty grid: lone cell dies", + "input": [[1]], + "expected": [[0]], + "actual": [[0]], + "pass": true, + "precondition": "ConwaysGameOfLife.js:6 rule 3, live cell with 0 neighbours dies" + }, + { + "name": "ordinary input: glider step", + "input": [ + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "expected": [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "actual": [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "pass": true, + "precondition": "ConwaysGameOfLife.js:4-5 rules 1 and 2" + }, + { + "name": "input grid unchanged after call", + "input": [ + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "expected": [ + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "actual": [ + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "pass": true, + "precondition": "ConwaysGameOfLife.js:43 cells are only read" + }, + { + "name": "output shares no rows with input", + "input": "glider", + "expected": { + "sameGrid": false, + "sharedRows": 0 + }, + "actual": { + "sameGrid": false, + "sharedRows": 0 + }, + "pass": true, + "precondition": "ConwaysGameOfLife.js:25,27 new arrays are created" + }, + { + "name": "glider run twice, then again after another input (result tampered)", + "input": "glider x3", + "expected": [ + [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ] + ], + "actual": [ + [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ] + ], + "pass": true, + "precondition": "ConwaysGameOfLife.js:24 no module-level state" + }, + { + "name": "external dependencies found by scanning the source (comments removed)", + "input": "Date, Math, performance, process, require, import, fetch, console, timers, globals", + "expected": [], + "actual": [], + "pass": true, + "precondition": "ConwaysGameOfLife.js:24-54 body uses only its parameter and local variables" + }, + { + "name": "module-level variables (shared state between calls)", + "input": "top-level let/var/const declarations", + "expected": [], + "actual": [], + "pass": true, + "precondition": "ConwaysGameOfLife.js: only an exported function is declared" + }, + { + "name": "deeply frozen input is accepted (no write is attempted)", + "input": "Object.freeze(glider)", + "expected": [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "actual": [ + [0, 0, 0, 0, 0], + [1, 0, 1, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 0, 0, 0], + [0, 0, 0, 0, 0] + ], + "pass": true, + "precondition": "ConwaysGameOfLife.js:43 cells are only read" + } + ], + "mutants": [ + { + "name": "writes the next state back into the input grid", + "file": "Cellular-Automata/ConwaysGameOfLife.js", + "edit": { + "from": " nextGenerationRow.push(cellIsAlive ? 1 : 0)\n", + "to": " nextGenerationRow.push(cellIsAlive ? 1 : 0)\n if (i > 0) cells[i - 1][j] = nextGeneration[i - 1][j]\n" + }, + "named_test": "does not modify the input grid", + "named_test_on_original": ["passed"], + "killed": true, + "exit": 1, + "failed_tests_on_mutant": [ + " newGeneration should produce the next generation according to the rules", + " newGeneration is deterministic and isolates its input ordinary input: one glider step", + " newGeneration is deterministic and isolates its input does not modify the input grid", + " newGeneration is deterministic and isolates its input accepts a deeply frozen grid, so it never writes to its input", + " newGeneration is deterministic and isolates its input same input twice in fresh state gives the same result", + " newGeneration is deterministic and isolates its input an earlier call with another input cannot change a later result" + ] + } + ], + "full_suite": { + "command": "npm test -- --reporter=json --outputFile=work/R50-T005/vitest-full.raw.json", + "exit": 0, + "total": 11978, + "passed": 11978, + "failed": 0 + }, + "ok": true, + "failures": [] +} diff --git a/work/R50-T005/task.json b/work/R50-T005/task.json new file mode 100644 index 0000000000..9718305aad --- /dev/null +++ b/work/R50-T005/task.json @@ -0,0 +1,14 @@ +{ + "task": "R50-T005", + "focused_tests": ["Cellular-Automata/test/ConwaysGameOfLife.test.js"], + "mutants": [ + { + "name": "writes the next state back into the input grid", + "file": "Cellular-Automata/ConwaysGameOfLife.js", + "find": " nextGenerationRow.push(cellIsAlive ? 1 : 0)\n", + "replace": " nextGenerationRow.push(cellIsAlive ? 1 : 0)\n if (i > 0) cells[i - 1][j] = nextGeneration[i - 1][j]\n", + "tests": ["Cellular-Automata/test/ConwaysGameOfLife.test.js"], + "must_fail": "does not modify the input grid" + } + ] +} diff --git a/work/R50-T005/versions.txt b/work/R50-T005/versions.txt new file mode 100644 index 0000000000..b405ff9cb4 --- /dev/null +++ b/work/R50-T005/versions.txt @@ -0,0 +1,5 @@ +python: 3.12.10 +node: v26.13.1 +npm: 11.20.0 +platform: macOS-27.2.1-arm64-arm-64bit +vitest: vitest/1.2.1 darwin-arm64 node-v26.13.1 diff --git a/work/R50-T005/vitest-focused.json b/work/R50-T005/vitest-focused.json new file mode 100644 index 0000000000..b869cccfc2 --- /dev/null +++ b/work/R50-T005/vitest-focused.json @@ -0,0 +1,44 @@ +{ + "command": "node_modules/.bin/vitest run Cellular-Automata/test/ConwaysGameOfLife.test.js --reporter=json --outputFile=work/R50-T005/vitest-focused.raw.json", + "numTotalTests": 9, + "numPassedTests": 9, + "numFailedTests": 0, + "tests": [ + { + "name": " newGeneration should produce the next generation according to the rules", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input smallest valid input: an empty grid gives an empty grid", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input smallest non-empty grid: a lone live cell dies", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input ordinary input: one glider step", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input does not modify the input grid", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input accepts a deeply frozen grid, so it never writes to its input", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input returns a new grid that shares no rows with the input", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input same input twice in fresh state gives the same result", + "status": "passed" + }, + { + "name": " newGeneration is deterministic and isolates its input an earlier call with another input cannot change a later result", + "status": "passed" + } + ] +}