'use strict'; const test = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), os = require('node:os'), path = require('node:path'), { execFileSync } = require('node:child_process'); const { OperationJournal } = require('../../src/modules/assistant/operation-journal.cjs'); const { CodeRepairRunner } = require('../../src/modules/assistant/code-repair.cjs'); function fixture(t, code = 'process.exit(0)') { const base = fs.mkdtempSync(path.join(os.tmpdir(), 'repair-test-')), repo = path.join(base, 'repo'), repairs = path.join(base, 'repairs'); fs.mkdirSync(repo); fs.mkdirSync(path.join(repo, 'src')); fs.writeFileSync(path.join(repo, 'src', 'app.cjs'), 'original'); const git = (...args) => execFileSync( 'git', ['-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', ...args], { cwd: repo, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }, ).trim(); git('init'); git('add', '.'); git('commit', '-m', 'baseline'); const journal = new OperationJournal({ file: path.join(base, 'audit.sqlite'), secrets: ['private-test-secret'], }); const runner = new CodeRepairRunner({ repoRoot: repo, repairRoot: repairs, journal, validator: { command: process.execPath, args: ['-e', code], timeoutMs: 5000 }, }); t.after(() => { journal.close(); fs.rmSync(base, { recursive: true, force: true }); }); return { base, repo, repairs, git, journal, runner }; } const request = { actor: 'admin', isAdmin: true, files: [{ path: 'src/app.cjs', content: 'changed' }], }; test('successful validation keeps active checkout untouched and leaves committed proposal', async (t) => { const f = fixture(t), baseline = f.git('rev-parse', 'HEAD'), r = await f.runner.run(request); assert.equal(r.status, 'ready_for_review'); assert.notEqual(r.resultCommit, baseline); assert.equal(f.git('rev-parse', 'HEAD'), baseline); assert.equal(fs.readFileSync(path.join(f.repo, 'src/app.cjs'), 'utf8'), 'original'); assert.equal(f.git('show', r.resultCommit + ':src/app.cjs'), 'changed'); assert.match(r.diff, /changed/); }); test('failed validation rolls isolated files back and retains proposal evidence', async (t) => { const f = fixture(t, 'process.exit(2)'), r = await f.runner.run(request); assert.equal(r.status, 'rolled_back'); assert.equal(fs.readFileSync(path.join(r.worktree, 'src/app.cjs'), 'utf8'), 'original'); assert.equal(f.git('show', r.resultCommit + ':src/app.cjs'), 'changed'); assert.equal(f.git('rev-parse', r.branch), r.resultCommit); }); test('rejects traversal, reserved files, credentials and non-admin callers before changes', async (t) => { const f = fixture(t); for (const name of [ 'src/../app.cjs', 'src/.git/config', 'src/node_modules/a.js', 'src/.env', 'src/output/a.js', 'package.json', 'src/CON.js', 'src/foo:bar.js', ]) await assert.rejects(f.runner.run({ ...request, files: [{ path: name, content: 'x' }] })); await assert.rejects(f.runner.run({ ...request, isAdmin: false })); assert.equal(f.git('status', '--porcelain'), ''); }); test('dirty active checkout is rejected', async (t) => { const f = fixture(t); fs.writeFileSync(path.join(f.repo, 'src/app.cjs'), 'unsaved'); await assert.rejects(f.runner.run(request), /dirty/i); }); test('journal redacts secrets, enforces actor scope and records restart uncertainty', (t) => { const f = fixture(t); f.journal.append({ operationId: 'one', actor: 'alice', step: 'repair', status: 'running', detail: 'token=abc private-test-secret', }); f.journal.append({ operationId: 'two', actor: 'bob', step: 'repair', status: 'done' }); assert.equal(f.journal.list({ actor: 'alice' }).length, 1); assert.equal(f.journal.list({ actor: 'root', isAdmin: true }).length, 2); assert.doesNotMatch( JSON.stringify(f.journal.list({ actor: 'alice' })), /abc|private-test-secret/, ); f.journal.recoverRunning(); assert.equal(f.journal.list({ actor: 'alice' })[0].status, 'needs_review'); assert.equal(f.journal.list({ actor: 'alice' }).length, 2); }); test('timeout is uncertain, never falsely reported as rollback', async (t) => { const f = fixture(t, 'setTimeout(()=>{},10000)'), r = await f.runner.run(request); assert.equal(r.status, 'needs_review'); assert.equal(r.recovery, 'manual_review'); assert.equal(fs.readFileSync(path.join(r.worktree, 'src/app.cjs'), 'utf8'), 'changed'); }); test('parallel requests cannot start a second repair', async (t) => { const f = fixture(t, 'setTimeout(()=>process.exit(0),150)'), pending = f.runner.run(request); await assert.rejects(f.runner.run(request), /already running/); assert.equal((await pending).status, 'ready_for_review'); }); test('symlink or junction source ancestors cannot be proposed', async (t) => { const f = fixture(t), external = path.join(f.base, 'external'); fs.mkdirSync(external); fs.writeFileSync(path.join(external, 'example.js'), 'outside'); fs.symlinkSync( external, path.join(f.repo, 'src', 'linked'), process.platform === 'win32' ? 'junction' : 'dir', ); f.git('add', '.'); f.git('commit', '-m', 'link'); await assert.rejects( f.runner.run({ ...request, files: [{ path: 'src/linked/example.js', content: 'bad' }] }), /Symlinks/, ); assert.equal(fs.readFileSync(path.join(external, 'example.js'), 'utf8'), 'outside'); }); test('validator tampering with worktree git pointer requires manual review without following it', async (t) => { const f = fixture( t, "require('node:fs').unlinkSync('.git');require('node:fs').writeFileSync('.git','gitdir: missing-git')", ), r = await f.runner.run(request); assert.equal(r.status, 'needs_review'); assert.equal(r.recovery, 'manual_review'); }); test('validator moving HEAD cannot produce a ready result for the original proposal', async (t) => { const f = fixture( t, "require('node:child_process').execFileSync('git',['-c','core.hooksPath=/dev/null','reset','--hard','HEAD~1'])", ), r = await f.runner.run(request); assert.equal(r.status, 'needs_review'); assert.equal(r.recovery, 'manual_review'); }); test('unrelated untracked drafts survive while proposal collision is rejected', async (t) => { const f = fixture(t); fs.mkdirSync(path.join(f.repo, 'docs')); fs.writeFileSync(path.join(f.repo, 'docs/draft.md'), 'user draft'); assert.equal((await f.runner.run(request)).status, 'ready_for_review'); assert.equal(fs.readFileSync(path.join(f.repo, 'docs/draft.md'), 'utf8'), 'user draft'); await assert.rejects( f.runner.run({ ...request, files: [{ path: 'docs/draft.md', content: 'overwrite' }] }), /untracked/i, ); }); test('source reads are bounded tracked allowlisted files with baseline and stale proposals rejected', async (t) => { const f = fixture(t), snapshot = f.runner.readSources(['src/app.cjs']); assert.equal(snapshot.baselineCommit, f.git('rev-parse', 'HEAD')); assert.deepEqual(snapshot.files, [{ path: 'src/app.cjs', content: 'original' }]); fs.writeFileSync(path.join(f.repo, 'src/draft.js'), 'untracked'); assert.throws(() => f.runner.readSources(['src/draft.js']), /tracked/i); await assert.rejects(f.runner.run({ ...request, expectedCommit: '0'.repeat(40) }), /stale/i); }); test('source reads do not silently truncate source code', (t) => { const f = fixture(t), content = '// example\n'.repeat(1000); fs.writeFileSync(path.join(f.repo, 'src/app.cjs'), content); f.git('add', '.'); f.git('commit', '-m', 'long source'); assert.equal(f.runner.readSources(['src/app.cjs']).files[0].content, content); }); test('journal prevents rewriting audit history and redacts quoted credentials', (t) => { const f = fixture(t); f.journal.append({ operationId: 'quoted', actor: 'alice', step: 'test', status: 'done', detail: '{"password":"sensitive-value"}', }); assert.doesNotMatch(JSON.stringify(f.journal.list({ actor: 'alice' })), /sensitive-value/); assert.throws(() => f.journal.db.exec('DELETE FROM operation_events'), /append-only/); assert.throws(() => f.journal.db.exec("UPDATE operation_events SET actor='bob'"), /append-only/); }); test( 'timeout terminates validator child and grandchild processes on Windows', { skip: process.platform !== 'win32' }, async (t) => { const f = fixture(t), receipt = path.join(f.base, 'pids.txt'); const grandchild = "require('node:fs').appendFileSync(" + JSON.stringify(receipt) + ",process.pid+'\\n');setInterval(()=>{},1000)"; const child = "require('node:fs').appendFileSync(" + JSON.stringify(receipt) + ",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e'," + JSON.stringify(grandchild) + "],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)"; f.runner.validator.args = [ '-e', "require('node:fs').appendFileSync(" + JSON.stringify(receipt) + ",process.pid+'\\n');require('node:child_process').spawn(process.execPath,['-e'," + JSON.stringify(child) + "],{stdio:'ignore',windowsHide:true});setInterval(()=>{},1000)", ]; f.runner.validator.timeoutMs = 2000; t.after(() => { if (fs.existsSync(receipt)) for (const pid of fs.readFileSync(receipt, 'utf8').trim().split(/\s+/).map(Number)) try { process.kill(pid); } catch {} }); const result = await f.runner.run(request), pids = fs.readFileSync(receipt, 'utf8').trim().split(/\s+/).map(Number); assert.equal(pids.length, 3); assert.equal(result.status, 'needs_review'); assert.equal(result.recovery, 'manual_review'); assert.equal(result.processCleanup.method, 'taskkill-tree'); assert.equal(result.processCleanup.commandSucceeded, true); assert.equal(result.processCleanup.rootExited, true); assert.ok(fs.existsSync(f.runner.lockPath)); for (const pid of pids) assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' }); }, ); test('validator cannot install rollback hooks unnoticed', async (t) => { const f = fixture( t, "require('node:fs').writeFileSync(require('node:path').join('..','.disabled-hooks','post-checkout'),'#!/bin/sh\\nexit 0\\n')", ), r = await f.runner.run(request); assert.equal(r.status, 'needs_review'); assert.ok(fs.existsSync(f.runner.lockPath)); }); test('source requiring redaction is rejected instead of returned as altered complete code', (t) => { const f = fixture(t); for (const content of [ 'module.exports={password:input.password};', 'const example="private-test-secret";', ]) { fs.writeFileSync(path.join(f.repo, 'src/app.cjs'), content); f.git('add', '.'); f.git('commit', '-m', 'source requiring review'); assert.throws(() => f.runner.readSources(['src/app.cjs']), /sensitive|redaction/i); } }); test('journal cursor pages older actor-scoped history without overlaps', (t) => { const f = fixture(t); for (let i = 0; i < 125; i++) { f.journal.append({ operationId: 'alice-operation', actor: 'alice', step: 'event', status: 'done', }); f.journal.append({ operationId: 'bob-operation', actor: 'bob', step: 'event', status: 'done' }); } const first = f.journal.list({ actor: 'alice' }); assert.equal(first.length, 100); const beforeId = first.at(-1).id, second = f.journal.list({ actor: 'alice', operationId: 'alice-operation', beforeId }); assert.equal(second.length, 25); assert.equal(new Set([...first, ...second].map((row) => row.id)).size, 125); assert.ok(second.every((row) => row.id < beforeId && row.actor === 'alice')); assert.deepEqual(f.journal.list({ actor: 'alice', operationId: 'bob-operation', beforeId }), []); for (const cursor of [0, -1, 1.5, '2', null, NaN, Number.MAX_SAFE_INTEGER + 1]) assert.throws(() => f.journal.list({ actor: 'alice', beforeId: cursor }), /cursor/i); }); test('repair journal names file changes, Git commit, validation and review steps', async (t) => { const f = fixture(t), r = await f.runner.run(request), steps = f.journal .list({ actor: request.actor }) .filter((e) => e.operationId === r.operationId) .map((e) => e.step); for (const step of ['prepare', 'files_written', 'commit', 'validate', 'review']) assert(steps.includes(step), step); }); test('long validation logs retain the final test summary in the audit record', async (t) => { const f = fixture(t, "console.log('x'.repeat(24000));console.log('FINAL_TEST_SUMMARY passed')"), r = await f.runner.run(request), last = f.journal .list({ actor: request.actor }) .find((e) => e.operationId === r.operationId && e.step === 'review'); assert.match(last.detail, /FINAL_TEST_SUMMARY passed/); }); test('explicit administrator-selected repository works without global safe-directory configuration', (t) => { const f = fixture(t); f.runner.env.GIT_TEST_ASSUME_DIFFERENT_OWNER = '1'; const read = f.runner.readSources(['src/app.cjs']); assert.equal(read.files[0].content, 'original'); });