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 { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import type { NotebookSnapshotReceipt } from '@stock-bot/research'; const REPO_ROOT = fileURLToPath(new URL('../../', import.meta.url)); const CLI_SCRIPT_PATH = join(REPO_ROOT, 'scripts/export-notebook-snapshot.ts'); type FakeMarimoMode = | 'clean' | 'check_nonzero' | 'check_errored_zero' | 'check_breaking_zero' | 'export_nonzero' | 'export_hang'; interface SpawnCliResult { readonly exitCode: number; readonly stdout: string; readonly stderr: string; } 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 runCliSubprocess( args: readonly string[], options?: { readonly cwd?: string; readonly env?: Readonly>; } ): Promise { const proc = Bun.spawn([process.execPath, 'run', CLI_SCRIPT_PATH, ...args], { cwd: options?.cwd ?? REPO_ROOT, env: options?.env ? { ...process.env, ...options.env } : process.env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', }); const [exitCode, stdout, stderr] = await Promise.all([ proc.exited, new Response(proc.stdout).text(), new Response(proc.stderr).text(), ]); return { exitCode, stdout, stderr }; } function assertSingleLineStderr(stderr: string): void { expect(stderr.length).toBeGreaterThan(0); expect(stderr.endsWith('\n')).toBe(true); expect(stderr.slice(0, -1)).not.toContain('\n'); } describe('scripts/export-notebook-snapshot.ts', () => { let workDir = ''; beforeEach(async () => { const rawDir = await mkdtemp(join(tmpdir(), 'export-notebook-snapshot-cli-')); workDir = await realpath(rawDir); }); afterEach(async () => { if (workDir) { await rm(workDir, { recursive: true, force: true }); workDir = ''; } }); async function writeFakeMarimoShim( name: string, mode: FakeMarimoMode, logPath: string, extra?: { readonly htmlContent?: string; readonly pidPath?: string } ): Promise { const shimPath = join(workDir, name); const htmlContent = extra?.htmlContent ?? 'Snapshot 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 (mode === "check_nonzero") {', ' process.stderr.write("syntax error in cell 2\\n");', ' process.exit(1);', ' }', ' if (mode === "check_errored_zero") {', ' process.stdout.write(JSON.stringify({', ' issues: [{ type: "error", message: "undefined variable" }],', ' summary: { errored: true, total_files: 1 },', ' }));', ' process.exit(0);', ' }', ' if (mode === "check_breaking_zero") {', ' process.stdout.write(JSON.stringify({', ' issues: [{ severity: "breaking", message: "cyclic cell graph" }],', ' summary: { errored: false, 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") {', ' const outPath = args[4];', ' if (mode === "export_nonzero") {', ' writeFileSync(outPath, "partial-failure", "utf8");', ' process.stderr.write("export crashed\\n");', ' process.exit(2);', ' }', ' if (mode === "export_hang") {', ' writeFileSync(outPath, "partial-timeout", "utf8");', ' if (pidPath) writeFileSync(pidPath, String(process.pid), "utf8");', ' setInterval(() => {}, 10_000);', ' } else {', ' writeFileSync(outPath, htmlContent, "utf8");', ' process.exit(0);', ' }', '} else {', ' process.stderr.write("unexpected args: " + JSON.stringify(args));', ' process.exit(2);', '}', ].join('\n'); await writeFile(shimPath, `${script}\n`, 'utf8'); await chmod(shimPath, 0o755); return shimPath; } test('package.json defines notebook:snapshot pointing to scripts/export-notebook-snapshot.ts', () => { const pkg = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')) as { scripts?: Record; }; expect(pkg.scripts?.['notebook:snapshot']).toBe('bun run scripts/export-notebook-snapshot.ts'); }); test('clean check + HTML export succeeds with absolute paths, matching receipt sha256/bytes and zero temp leftovers', 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-abs.log.jsonl'); const expectedHtml = '

Study Snapshot

\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-abs', 'clean', logPath, { htmlContent: expectedHtml, }); const result = await runCliSubprocess([ '--notebook', notebookPath, '--out', outputPath, '--marimo', shimPath, '--allowed-notebook-root', notebookDir, '--allowed-output-root', outputDir, '--timeout-ms', '10000', ]); expect(result.exitCode).toBe(0); expect(result.stderr).toBe(''); const receipt = JSON.parse(result.stdout.trim()) as NotebookSnapshotReceipt; 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 diskBytes = await readFile(outputPath); expect(diskBytes.byteLength).toBe(receipt.bytes); expect(createHash('sha256').update(diskBytes).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); }); test('clean check + HTML export resolves relative paths against cwd and supports --flag=value and MARIMO_COMMAND', async () => { const notebookDir = join(workDir, 'notebooks'); const outputDir = join(workDir, 'out'); await mkdir(notebookDir); await mkdir(outputDir); const notebookPath = join(notebookDir, 'relative.py'); const outputPath = join(outputDir, 'relative.html'); const logPath = join(workDir, 'clean-rel.log.jsonl'); const expectedHtml = 'Relative OK\n'; const expectedSha256 = createHash('sha256').update(expectedHtml, 'utf8').digest('hex'); await writeFile(notebookPath, '# relative fixture\n', 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-clean-rel', 'clean', logPath, { htmlContent: expectedHtml, }); const result = await runCliSubprocess( [ '--notebook=notebooks/relative.py', '--out=out/relative.html', '--allowed-notebook-root=notebooks', '--allowed-output-root=out', ], { cwd: workDir, env: { MARIMO_COMMAND: shimPath }, } ); expect(result.exitCode).toBe(0); expect(result.stderr).toBe(''); const receipt = JSON.parse(result.stdout.trim()) as NotebookSnapshotReceipt; expect(receipt.notebookPath).toBe(notebookPath); expect(receipt.outputPath).toBe(outputPath); expect(receipt.sha256).toBe(expectedSha256); expect(await readdir(outputDir)).toEqual(['relative.html']); }); test('fails closed on non-zero marimo check exit, preserves pre-existing HTML, and never invokes export', 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, 'existing.html'); const logPath = join(workDir, 'check-nonzero.log.jsonl'); const priorHtml = 'Prior Verified Snapshot\n'; await writeFile(notebookPath, '# broken\n', 'utf8'); await writeFile(outputPath, priorHtml, 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-check-nz', 'check_nonzero', logPath); const result = await runCliSubprocess([ '--notebook', notebookPath, '--out', outputPath, '--marimo', shimPath, ]); expect(result.exitCode).toBe(1); expect(result.stdout).toBe(''); assertSingleLineStderr(result.stderr); expect(result.stderr).toContain('CHECK_FAILED'); expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); expect(await readdir(outputDir)).toEqual(['existing.html']); 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[0]).toBe('check'); }); test('fails closed on exit 0 with summary.errored=true or severity=breaking, preserving pre-existing HTML', async () => { const notebookDir = join(workDir, 'notebooks'); const outputDir = join(workDir, 'out'); await mkdir(notebookDir); await mkdir(outputDir); const notebookPath = join(notebookDir, 'errored.py'); const outputPath = join(outputDir, 'preserved.html'); const priorHtml = 'Preserved\n'; await writeFile(notebookPath, '# errored\n', 'utf8'); await writeFile(outputPath, priorHtml, 'utf8'); for (const mode of ['check_errored_zero', 'check_breaking_zero'] as const) { const logPath = join(workDir, `${mode}.log.jsonl`); const shimPath = await writeFakeMarimoShim(`fake-marimo-${mode}`, mode, logPath); const result = await runCliSubprocess([ '--notebook', notebookPath, '--out', outputPath, '--marimo', shimPath, ]); expect(result.exitCode).toBe(1); expect(result.stdout).toBe(''); assertSingleLineStderr(result.stderr); expect(result.stderr).toContain('CHECK_FAILED'); expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); expect(await readdir(outputDir)).toEqual(['preserved.html']); 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[0]).toBe('check'); } }); test('fails closed on export non-zero exit, cleans temp file, and preserves pre-existing HTML', async () => { const notebookDir = join(workDir, 'notebooks'); const outputDir = join(workDir, 'out'); await mkdir(notebookDir); await mkdir(outputDir); const notebookPath = join(notebookDir, 'export-fail.py'); const outputPath = join(outputDir, 'stable.html'); const logPath = join(workDir, 'export-nz.log.jsonl'); const priorHtml = 'Stable Prior\n'; await writeFile(notebookPath, '# export fail\n', 'utf8'); await writeFile(outputPath, priorHtml, 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-export-nz', 'export_nonzero', logPath); const result = await runCliSubprocess([ '--notebook', notebookPath, '--out', outputPath, '--marimo', shimPath, ]); expect(result.exitCode).toBe(1); expect(result.stdout).toBe(''); assertSingleLineStderr(result.stderr); expect(result.stderr).toContain('EXPORT_FAILED'); expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); expect(await readdir(outputDir)).toEqual(['stable.html']); }); test('fails closed on partial-write export timeout, reaps child process, cleans temp file, and preserves pre-existing HTML', 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, 'stable.html'); const logPath = join(workDir, 'hang.log.jsonl'); const pidPath = join(workDir, 'hang.pid'); const priorHtml = 'Stable Before Timeout\n'; await writeFile(notebookPath, '# hang\n', 'utf8'); await writeFile(outputPath, priorHtml, 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-hang', 'export_hang', logPath, { pidPath, }); const result = await runCliSubprocess([ '--notebook', notebookPath, '--out', outputPath, '--marimo', shimPath, '--timeout-ms', '600', ]); expect(result.exitCode).toBe(1); expect(result.stdout).toBe(''); assertSingleLineStderr(result.stderr); expect(result.stderr).toContain('TIMEOUT'); expect(await readFile(outputPath, 'utf8')).toBe(priorHtml); expect(await readdir(outputDir)).toEqual(['stable.html']); const pid = Number.parseInt(readFileSync(pidPath, 'utf8').trim(), 10); expect(Number.isInteger(pid) && pid > 0).toBe(true); let probeErr: unknown; try { process.kill(pid, 0); } catch (err) { probeErr = err; } expect(getErrorCode(probeErr)).toBe('ESRCH'); }); test('rejects missing, unknown, duplicate flags, positional args, leading-dash values, and root traversal escapes', 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, 'never-called.log.jsonl'); await writeFile(notebookPath, '# ok\n', 'utf8'); const shimPath = await writeFakeMarimoShim('fake-marimo-never', 'clean', logPath); const invalidInvocations: readonly (readonly string[])[] = [ // Missing --out ['--notebook', notebookPath, '--marimo', shimPath], // Unknown flag ['--notebook', notebookPath, '--out', outputPath, '--bogus', '1'], // Duplicate flag ['--notebook', notebookPath, '--notebook', notebookPath, '--out', outputPath], // Positional arg [notebookPath, '--out', outputPath], // Leading-dash path (option injection) ['--notebook', '-evil.py', '--out', outputPath, '--marimo', shimPath], // Invalid timeout ['--notebook', notebookPath, '--out', outputPath, '--timeout-ms', '0'], // Traversal escape outside --allowed-notebook-root [ '--notebook', join(notebookDir, '..', 'escape.py'), '--out', outputPath, '--marimo', shimPath, '--allowed-notebook-root', notebookDir, ], // Traversal escape outside --allowed-output-root [ '--notebook', notebookPath, '--out', join(outputDir, '..', 'escape.html'), '--marimo', shimPath, '--allowed-output-root', outputDir, ], ]; for (const argv of invalidInvocations) { const result = await runCliSubprocess(argv); expect(result.exitCode).toBe(1); expect(result.stdout).toBe(''); assertSingleLineStderr(result.stderr); } // Traversal escapes must specifically report INVALID_PATH. const escapeResult = await runCliSubprocess([ '--notebook', join(notebookDir, '..', 'escape.py'), '--out', outputPath, '--marimo', shimPath, '--allowed-notebook-root', notebookDir, ]); expect(escapeResult.exitCode).toBe(1); expect(escapeResult.stderr).toContain('INVALID_PATH'); // Help exits 0 with usage on stdout and empty stderr. const helpResult = await runCliSubprocess(['--help']); expect(helpResult.exitCode).toBe(0); expect(helpResult.stderr).toBe(''); expect(helpResult.stdout).toContain('Usage:'); }); });