import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { chmod, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile, } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { createNodeNotebookCommandRunner, createNodeNotebookSnapshotFs, NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES, } from '@stock-bot/research/notebook-snapshot-node'; import { exportNotebookSnapshot, NotebookSnapshotError } from '../src/notebook-snapshot'; function getErrorCode(err: unknown): string | undefined { if (typeof err === 'object' && err !== null && 'code' in err) { const code = (err as { code?: unknown }).code; if (typeof code === 'string') { return code; } } return undefined; } async function expectReject(promise: Promise): Promise { try { await promise; } catch (err) { return err; } throw new Error('Expected promise to reject, but it resolved.'); } describe('notebook-snapshot-node adapters', () => { let workDir = ''; beforeEach(async () => { const rawDir = await mkdtemp(join(tmpdir(), 'notebook-snapshot-node-')); workDir = await realpath(rawDir); }); afterEach(async () => { if (workDir) { await rm(workDir, { recursive: true, force: true }); workDir = ''; } }); describe('createNodeNotebookCommandRunner', () => { test('passes argv verbatim without shell interpretation (spaces, quotes, $(...), ;, *)', async () => { const scriptPath = join(workDir, 'echo-argv.js'); await writeFile( scriptPath, 'process.stdout.write(JSON.stringify(process.argv.slice(2)));\n', 'utf8' ); const runner = createNodeNotebookCommandRunner(); const args = [ scriptPath, 'hello world', `"double" and 'single' quotes`, '$(echo pwned)', 'a;b', '*.ts', ]; const result = await runner.run(process.execPath, args, { timeoutMs: 10_000 }); expect(result.exitCode).toBe(0); expect(result.stderr).toBe(''); expect(JSON.parse(result.stdout)).toEqual(args.slice(1)); }); test('honours cwd, separates stdout/stderr with split multi-byte UTF-8, and resolves non-zero exit codes', async () => { const subDir = join(workDir, 'child-cwd'); await mkdir(subDir); const scriptPath = join(workDir, 'streams-and-exit.js'); await writeFile( scriptPath, [ // Split a 3-byte UTF-8 character ('€' = E2 82 AC) and a 4-byte emoji ('šŸš€' = F0 9F 9A 80) across writes. 'process.stdout.write(Buffer.from([0x63, 0x77, 0x64, 0x3d]));', 'process.stdout.write(process.cwd() + "\\n");', 'process.stdout.write(Buffer.from([0xe2, 0x82]));', 'process.stdout.write(Buffer.from([0xac, 0x0a]));', 'process.stderr.write(Buffer.from([0xf0, 0x9f]));', 'process.stderr.write(Buffer.from([0x9a, 0x80]));', 'process.exit(42);', ].join('\n'), 'utf8' ); const runner = createNodeNotebookCommandRunner(); const result = await runner.run(process.execPath, [scriptPath], { cwd: subDir, timeoutMs: 10_000, }); expect(result.exitCode).toBe(42); expect(result.stdout).toBe(`cwd=${subDir}\n€\n`); expect(result.stderr).toBe('šŸš€'); }); test('rejects with ENOENT when executable does not exist', async () => { const runner = createNodeNotebookCommandRunner(); const missingPath = join(workDir, 'does-not-exist-binary'); const err = await expectReject(runner.run(missingPath, ['--version'], { timeoutMs: 10_000 })); expect(err).toBeInstanceOf(Error); expect(getErrorCode(err)).toBe('ENOENT'); }); test('rejects signal exit with only command basename (no full path, argv, or env values)', async () => { const secretArg = 'SECRET_ARG_TOKEN_987654'; const shimPath = join(workDir, 'signal-self.js'); await writeFile( shimPath, [ '#!/usr/bin/env bun', "process.kill(process.pid, 'SIGKILL');", 'setInterval(() => {}, 10_000);', ].join('\n'), 'utf8' ); await chmod(shimPath, 0o755); const runner = createNodeNotebookCommandRunner(); const err = await expectReject(runner.run(shimPath, [secretArg], { timeoutMs: 10_000 })); expect(err).toBeInstanceOf(Error); const message = (err as Error).message; expect(message).toContain('signal-self.js'); expect(message).toContain('SIGKILL'); expect(message).not.toContain(workDir); expect(message).not.toContain(secretArg); expect(message).not.toContain(process.env.PATH ?? '__no_path__'); }); test('kills timed-out child with SIGKILL and rejects ETIMEDOUT only after child is dead (ESRCH)', async () => { const pidFile = join(workDir, 'sleeper.pid'); const scriptPath = join(workDir, 'sleep-forever.js'); await writeFile( scriptPath, [ "import { writeFileSync } from 'node:fs';", 'writeFileSync(process.argv[2], String(process.pid), "utf8");', 'setInterval(() => {}, 10_000);', ].join('\n'), 'utf8' ); const runner = createNodeNotebookCommandRunner(); const err = await expectReject( runner.run(process.execPath, [scriptPath, pidFile], { timeoutMs: 800 }) ); // Read the PID synchronously with no intervening await so the liveness // probe checks the process state immediately upon settlement. const pidText = readFileSync(pidFile, 'utf8'); const pid = Number.parseInt(pidText.trim(), 10); let probeError: unknown; try { process.kill(pid, 0); } catch (killErr) { probeError = killErr; } expect(err).toBeInstanceOf(Error); expect(getErrorCode(err)).toBe('ETIMEDOUT'); expect(Number.isInteger(pid) && pid > 0).toBe(true); expect(getErrorCode(probeError)).toBe('ESRCH'); }); test('settles ETIMEDOUT after direct child dies even when a descendant inherits stdout/stderr', async () => { const childPidFile = join(workDir, 'parent.pid'); const grandchildPidFile = join(workDir, 'grandchild.pid'); const grandchildScript = join(workDir, 'grandchild-sleeper.js'); const parentScript = join(workDir, 'spawn-grandchild.js'); // Bounded lifetime well beyond the runner's 800ms deadline so a regression // cannot leak the fixture process indefinitely. await writeFile(grandchildScript, 'setTimeout(() => process.exit(0), 30_000);\n', 'utf8'); await writeFile( parentScript, [ "import { spawn } from 'node:child_process';", "import { writeFileSync } from 'node:fs';", 'const grandchild = spawn(process.execPath, [process.argv[4]], { stdio: "inherit" });', 'writeFileSync(process.argv[2], String(process.pid), "utf8");', 'writeFileSync(process.argv[3], String(grandchild.pid), "utf8");', 'setInterval(() => {}, 10_000);', ].join('\n'), 'utf8' ); let grandchildPid: number | undefined; try { const runner = createNodeNotebookCommandRunner(); const err = await expectReject( runner.run( process.execPath, [parentScript, childPidFile, grandchildPidFile, grandchildScript], { timeoutMs: 800 } ) ); const childPid = Number.parseInt(readFileSync(childPidFile, 'utf8').trim(), 10); grandchildPid = Number.parseInt(readFileSync(grandchildPidFile, 'utf8').trim(), 10); let childProbeError: unknown; try { process.kill(childPid, 0); } catch (killErr) { childProbeError = killErr; } // Grandchild still holds the inherited stdout/stderr pipes open while alive. let grandchildAlive = true; try { process.kill(grandchildPid, 0); } catch { grandchildAlive = false; } expect(err).toBeInstanceOf(Error); expect(getErrorCode(err)).toBe('ETIMEDOUT'); expect(Number.isInteger(childPid) && childPid > 0).toBe(true); expect(Number.isInteger(grandchildPid) && grandchildPid > 0).toBe(true); expect(getErrorCode(childProbeError)).toBe('ESRCH'); expect(grandchildAlive).toBe(true); } finally { if (grandchildPid === undefined) { try { grandchildPid = Number.parseInt(readFileSync(grandchildPidFile, 'utf8').trim(), 10); } catch { // Grandchild never wrote its PID file. } } if (grandchildPid !== undefined && Number.isInteger(grandchildPid) && grandchildPid > 0) { try { process.kill(grandchildPid, 'SIGKILL'); } catch { // Already exited. } } } }); test('handles timeoutMs beyond 32-bit setTimeout limit without firing immediately', async () => { const scriptPath = join(workDir, 'fast-ok.js'); await writeFile(scriptPath, 'process.stdout.write("ok");\n', 'utf8'); const runner = createNodeNotebookCommandRunner(); const result = await runner.run(process.execPath, [scriptPath], { timeoutMs: 3_000_000_000, }); expect(result.exitCode).toBe(0); expect(result.stdout).toBe('ok'); expect(result.stderr).toBe(''); }); test('enforces NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES independently on stdout and stderr', async () => { const scriptPath = join(workDir, 'emit-bytes.js'); await writeFile( scriptPath, [ 'const streamName = process.argv[2];', 'const totalBytes = Number.parseInt(process.argv[3], 10);', 'const chunkSize = 65536;', 'const chunk = Buffer.alloc(chunkSize, 0x61);', 'const target = streamName === "stderr" ? process.stderr : process.stdout;', 'let remaining = totalBytes;', 'function pump() {', ' while (remaining > 0) {', ' const size = Math.min(remaining, chunkSize);', ' remaining -= size;', ' const ok = target.write(size === chunkSize ? chunk : chunk.subarray(0, size));', ' if (!ok) {', ' target.once("drain", pump);', ' return;', ' }', ' }', '}', 'pump();', ].join('\n'), 'utf8' ); const runner = createNodeNotebookCommandRunner(); // Exact cap on stdout succeeds. const stdoutExact = await runner.run( process.execPath, [scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)], { timeoutMs: 30_000 } ); expect(stdoutExact.exitCode).toBe(0); expect(stdoutExact.stdout.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES); expect(stdoutExact.stderr).toBe(''); // One byte over cap on stdout rejects with EOUTPUTLIMIT. const stdoutOverflow = await expectReject( runner.run( process.execPath, [scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)], { timeoutMs: 30_000 } ) ); expect(getErrorCode(stdoutOverflow)).toBe('EOUTPUTLIMIT'); // Exact cap on stderr succeeds. const stderrExact = await runner.run( process.execPath, [scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)], { timeoutMs: 30_000 } ); expect(stderrExact.exitCode).toBe(0); expect(stderrExact.stdout).toBe(''); expect(stderrExact.stderr.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES); // One byte over cap on stderr rejects with EOUTPUTLIMIT. const stderrOverflow = await expectReject( runner.run( process.execPath, [scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)], { timeoutMs: 30_000 } ) ); expect(getErrorCode(stderrOverflow)).toBe('EOUTPUTLIMIT'); }); test('supports custom per-stream maxOutputBytes without sharing cap across streams', async () => { const scriptPath = join(workDir, 'both-streams.js'); await writeFile( scriptPath, [ 'const n = Number.parseInt(process.argv[2], 10);', 'process.stdout.write("a".repeat(n));', 'process.stderr.write("b".repeat(n));', ].join('\n'), 'utf8' ); const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 128 }); const exactBoth = await runner.run(process.execPath, [scriptPath, '128'], { timeoutMs: 10_000, }); expect(exactBoth.exitCode).toBe(0); expect(exactBoth.stdout.length).toBe(128); expect(exactBoth.stderr.length).toBe(128); const overCap = await expectReject( runner.run(process.execPath, [scriptPath, '129'], { timeoutMs: 10_000 }) ); expect(getErrorCode(overCap)).toBe('EOUTPUTLIMIT'); }); test('rejects invalid timeoutMs with RangeError before spawning and invalid maxOutputBytes on construction', async () => { const runner = createNodeNotebookCommandRunner(); const invalidTimeouts = [ 0, -1, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, 1.5, ]; for (const timeoutMs of invalidTimeouts) { const err = await expectReject( runner.run(join(workDir, 'never-spawned'), [], { timeoutMs }) ); expect(err).toBeInstanceOf(RangeError); } expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 0 })).toThrow(RangeError); expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: -5 })).toThrow(RangeError); expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 1.5 })).toThrow(RangeError); }); }); describe('createNodeNotebookSnapshotFs', () => { test('stat returns null for missing, { isFile, size } for file/dir, and propagates ENOTDIR', async () => { const fs = createNodeNotebookSnapshotFs(); const missingPath = join(workDir, 'missing.txt'); const filePath = join(workDir, 'sample.bin'); const dirPath = join(workDir, 'nested-dir'); await writeFile(filePath, new Uint8Array([1, 2, 3, 4, 5])); await mkdir(dirPath); expect(await fs.stat(missingPath)).toBeNull(); expect(await fs.stat(filePath)).toEqual({ isFile: true, size: 5 }); const dirStat = await fs.stat(dirPath); expect(dirStat).not.toBeNull(); expect(dirStat?.isFile).toBe(false); const enotdirErr = await expectReject(fs.stat(join(filePath, 'child'))); expect(getErrorCode(enotdirErr)).toBe('ENOTDIR'); }); test('createExclusive creates an empty file and rejects EEXIST on collision', async () => { const fs = createNodeNotebookSnapshotFs(); const target = join(workDir, 'exclusive.tmp'); await fs.createExclusive(target); expect(await fs.stat(target)).toEqual({ isFile: true, size: 0 }); const err = await expectReject(fs.createExclusive(target)); expect(getErrorCode(err)).toBe('EEXIST'); }); test('readBytes round-trips arbitrary binary bytes including 0x00 and 0xff', async () => { const fs = createNodeNotebookSnapshotFs(); const target = join(workDir, 'binary.dat'); const payload = new Uint8Array([0x00, 0x01, 0x7f, 0x80, 0xfe, 0xff, 0x00, 0x42]); await writeFile(target, payload); const actual = await fs.readBytes(target); expect(actual).toBeInstanceOf(Uint8Array); expect(Array.from(actual)).toEqual(Array.from(payload)); }); test('rename atomically replaces an existing destination file', async () => { const fs = createNodeNotebookSnapshotFs(); const src = join(workDir, 'new.html'); const dst = join(workDir, 'published.html'); await writeFile(dst, 'old content', 'utf8'); await writeFile(src, 'new content', 'utf8'); await fs.rename(src, dst); expect(await fs.stat(src)).toBeNull(); expect(await readFile(dst, 'utf8')).toBe('new content'); }); test('remove is a no-op when absent and rejects non-recursively on a non-empty directory', async () => { const fs = createNodeNotebookSnapshotFs(); await fs.remove(join(workDir, 'absent.tmp')); const regularFile = join(workDir, 'deletable.tmp'); await writeFile(regularFile, 'bye', 'utf8'); await fs.remove(regularFile); expect(await fs.stat(regularFile)).toBeNull(); const nonEmptyDir = join(workDir, 'keep-dir'); const innerFile = join(nonEmptyDir, 'inside.txt'); await mkdir(nonEmptyDir); await writeFile(innerFile, 'precious', 'utf8'); const err = await expectReject(fs.remove(nonEmptyDir)); expect(err).toBeInstanceOf(Error); expect(await readFile(innerFile, 'utf8')).toBe('precious'); }); }); describe('end-to-end exportNotebookSnapshot with real adapters and fake marimo shim', () => { async function writeFakeMarimoShim( name: string, mode: 'clean' | 'check_error' | 'hang_export', logPath: string, extra?: { readonly htmlContent?: string; readonly pidPath?: string } ): Promise { const shimPath = join(workDir, name); const htmlContent = extra?.htmlContent ?? 'OK\n'; const pidPath = extra?.pidPath ?? ''; const script = [ '#!/usr/bin/env bun', "import { appendFileSync, writeFileSync } from 'node:fs';", 'const args = process.argv.slice(2);', `const mode = ${JSON.stringify(mode)};`, `const logPath = ${JSON.stringify(logPath)};`, `const htmlContent = ${JSON.stringify(htmlContent)};`, `const pidPath = ${JSON.stringify(pidPath)};`, 'appendFileSync(logPath, JSON.stringify({ args, pid: process.pid }) + "\\n", "utf8");', 'if (args[0] === "check") {', ' if (args[1] !== "--format=json" || args.length !== 3) {', ' process.stderr.write("unexpected check argv: " + JSON.stringify(args));', ' process.exit(2);', ' }', ' if (mode === "check_error") {', ' process.stdout.write(JSON.stringify({', ' issues: [{ type: "error", severity: "breaking", message: "undefined name" }],', ' summary: { errored: true, total_files: 1 },', ' }));', ' process.exit(0);', ' }', ' process.stdout.write(JSON.stringify({', ' issues: [],', ' summary: { errored: false, total_files: 1 },', ' }));', ' process.exit(0);', '}', 'if (args[0] === "export" && args[1] === "html") {', ' if (args.length !== 6 || args[3] !== "-o" || args[5] !== "--force") {', ' process.stderr.write("unexpected export argv: " + JSON.stringify(args));', ' process.exit(2);', ' }', ' const outPath = args[4];', ' if (mode === "hang_export") {', ' writeFileSync(outPath, "partial", "utf8");', ' if (pidPath) writeFileSync(pidPath, String(process.pid), "utf8");', ' setInterval(() => {}, 10_000);', ' } else {', ' writeFileSync(outPath, htmlContent, "utf8");', ' process.exit(0);', ' }', '} else {', ' process.stderr.write("unknown command: " + JSON.stringify(args));', ' process.exit(2);', '}', ].join('\n'); await writeFile(shimPath, `${script}\n`, 'utf8'); await chmod(shimPath, 0o755); return shimPath; } test('clean check publishes HTML whose bytes and sha256 match the receipt with no leftover temp files', async () => { const notebookDir = join(workDir, 'notebooks'); const outputDir = join(workDir, 'out'); await mkdir(notebookDir); await mkdir(outputDir); const notebookPath = join(notebookDir, 'study.py'); const outputPath = join(outputDir, 'study.html'); const logPath = join(workDir, 'clean.log.jsonl'); const expectedHtml = '

CA Shorts Study €

\n'; const expectedBytes = Buffer.from(expectedHtml, 'utf8'); const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex'); await writeFile(notebookPath, '# marimo notebook fixture\n', 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-clean', 'clean', logPath, { htmlContent: expectedHtml, }); const receipt = await exportNotebookSnapshot({ notebookPath, outputPath, runner: createNodeNotebookCommandRunner(), fs: createNodeNotebookSnapshotFs(), marimoCommand: shimPath, timeoutMs: 10_000, allowedNotebookRoot: notebookDir, allowedOutputRoot: outputDir, }); expect(receipt.notebookPath).toBe(notebookPath); expect(receipt.outputPath).toBe(outputPath); expect(receipt.bytes).toBe(expectedBytes.byteLength); expect(receipt.sha256).toBe(expectedSha256); expect(receipt.checkDiagnostics).toEqual({ issues: [], summary: { errored: false, total_files: 1 }, }); const published = await readFile(outputPath); expect(published.byteLength).toBe(receipt.bytes); expect(createHash('sha256').update(published).digest('hex')).toBe(receipt.sha256); expect(await readdir(outputDir)).toEqual(['study.html']); const invocations = (await readFile(logPath, 'utf8')) .trim() .split('\n') .map(line => JSON.parse(line) as { args: string[] }); expect(invocations).toHaveLength(2); expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]); expect(invocations[1]?.args[0]).toBe('export'); expect(invocations[1]?.args[1]).toBe('html'); expect(invocations[1]?.args[2]).toBe(notebookPath); expect(invocations[1]?.args[3]).toBe('-o'); expect(invocations[1]?.args[5]).toBe('--force'); }); test('blocking check report on exit 0 rejects CHECK_FAILED, skips export, and writes no output or temp files', async () => { const notebookDir = join(workDir, 'notebooks'); const outputDir = join(workDir, 'out'); await mkdir(notebookDir); await mkdir(outputDir); const notebookPath = join(notebookDir, 'broken.py'); const outputPath = join(outputDir, 'broken.html'); const logPath = join(workDir, 'check-error.log.jsonl'); await writeFile(notebookPath, '# broken marimo notebook fixture\n', 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-check-error', 'check_error', logPath); const err = await expectReject( exportNotebookSnapshot({ notebookPath, outputPath, runner: createNodeNotebookCommandRunner(), fs: createNodeNotebookSnapshotFs(), marimoCommand: shimPath, timeoutMs: 10_000, }) ); expect(err).toBeInstanceOf(NotebookSnapshotError); expect((err as NotebookSnapshotError).code).toBe('CHECK_FAILED'); expect(await readdir(outputDir)).toEqual([]); const invocations = (await readFile(logPath, 'utf8')) .trim() .split('\n') .map(line => JSON.parse(line) as { args: string[] }); expect(invocations).toHaveLength(1); expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]); }); test('hanging export rejects TIMEOUT, kills export child, and leaves no output or partial temp file', async () => { const notebookDir = join(workDir, 'notebooks'); const outputDir = join(workDir, 'out'); await mkdir(notebookDir); await mkdir(outputDir); const notebookPath = join(notebookDir, 'hang.py'); const outputPath = join(outputDir, 'hang.html'); const logPath = join(workDir, 'hang.log.jsonl'); const pidPath = join(workDir, 'hang-export.pid'); await writeFile(notebookPath, '# hanging export fixture\n', 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-hang', 'hang_export', logPath, { pidPath, }); const err = await expectReject( exportNotebookSnapshot({ notebookPath, outputPath, runner: createNodeNotebookCommandRunner(), fs: createNodeNotebookSnapshotFs(), marimoCommand: shimPath, timeoutMs: 800, }) ); const pid = Number.parseInt(readFileSync(pidPath, 'utf8').trim(), 10); let probeError: unknown; try { process.kill(pid, 0); } catch (killErr) { probeError = killErr; } expect(err).toBeInstanceOf(NotebookSnapshotError); expect((err as NotebookSnapshotError).code).toBe('TIMEOUT'); expect(Number.isInteger(pid) && pid > 0).toBe(true); expect(getErrorCode(probeError)).toBe('ESRCH'); expect(await readdir(outputDir)).toEqual([]); const invocations = (await readFile(logPath, 'utf8')) .trim() .split('\n') .map(line => JSON.parse(line) as { args: string[]; pid: number }); expect(invocations).toHaveLength(2); expect(invocations[0]?.args[0]).toBe('check'); expect(invocations[1]?.args[0]).toBe('export'); }); }); });