T-214: M2.1w — Add notebook snapshot CLI, MCP end-to-end study+snapshot+finding test, and fix docs/->design/ path drift

This commit is contained in:
Studio 2026-12-05 13:45:27 -05:00
parent 8e2bf1c7f2
commit 2e71dda7f2
10 changed files with 2192 additions and 43 deletions

View file

@ -0,0 +1,310 @@
/**
* Runnable CLI wrapper for `marimo check`-gated static HTML notebook exports.
*
* Enforces D9 (`design/PLATFORM-PLAN.md`): runs `marimo check --format=json`
* before `marimo export html` and publishes the HTML atomically via a sibling
* temp file. Emits the frozen JSON `NotebookSnapshotReceipt` to stdout on
* success, or a single concise error line to stderr with zero stdout bytes and
* exit code 1 on any validation, check, export, or timeout failure.
*/
import { resolve } from 'node:path';
import {
DEFAULT_MARIMO_COMMAND,
DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS,
type NotebookCommandRunner,
NotebookSnapshotError,
type NotebookSnapshotFs,
exportNotebookSnapshot,
} from '@stock-bot/research';
import {
createNodeNotebookCommandRunner,
createNodeNotebookSnapshotFs,
} from '@stock-bot/research/notebook-snapshot-node';
const STRICT_POSITIVE_INT_RE = /^[1-9]\d*$/;
export interface ExportNotebookSnapshotStream {
write(chunk: string): boolean;
}
export interface ParseExportNotebookSnapshotArgsOptions {
readonly cwd?: string;
readonly env?: Readonly<Record<string, string | undefined>>;
}
export interface ParsedExportNotebookSnapshotRun {
readonly kind: 'run';
readonly notebookPath: string;
readonly outputPath: string;
readonly marimoCommand: string;
readonly timeoutMs: number;
readonly cwd?: string;
readonly allowedNotebookRoot?: string;
readonly allowedOutputRoot?: string;
}
export interface ParsedExportNotebookSnapshotHelp {
readonly kind: 'help';
}
export type ParsedExportNotebookSnapshotArgs =
| ParsedExportNotebookSnapshotRun
| ParsedExportNotebookSnapshotHelp;
export interface ExportNotebookSnapshotCliDeps {
readonly argv?: readonly string[];
readonly cwd?: string;
readonly env?: Readonly<Record<string, string | undefined>>;
readonly stdout?: ExportNotebookSnapshotStream;
readonly stderr?: ExportNotebookSnapshotStream;
readonly runner?: NotebookCommandRunner;
readonly fs?: NotebookSnapshotFs;
}
export class ExportNotebookSnapshotCliError extends Error {
constructor(message: string) {
super(message);
this.name = 'ExportNotebookSnapshotCliError';
Object.setPrototypeOf(this, new.target.prototype);
}
}
export const EXPORT_NOTEBOOK_SNAPSHOT_USAGE = [
'Usage: bun run notebook:snapshot --notebook <path.py> --out <path.html> [options]',
'',
'Options:',
' --notebook <path.py> Required marimo notebook file (.py)',
' --out <path.html> Required output HTML snapshot path (.html)',
` --marimo <cmd> marimo executable (default: $MARIMO_COMMAND or ${DEFAULT_MARIMO_COMMAND})`,
` --timeout-ms <positive-int> Per-command timeout in ms (default: ${DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS})`,
' --cwd <dir> Working directory passed to marimo subprocesses',
' --allowed-notebook-root <dir> Optional root directory bounding --notebook',
' --allowed-output-root <dir> Optional root directory bounding --out',
' -h, --help Show this help message',
'',
].join('\n');
const VALUE_FLAGS = new Set([
'--notebook',
'--out',
'--marimo',
'--timeout-ms',
'--cwd',
'--allowed-notebook-root',
'--allowed-output-root',
]);
function sanitizeSingleLine(message: string): string {
return message.replace(/\r?\n/g, ' ').trim();
}
function validateRawTokenValue(flag: string, rawValue: string): string {
if (rawValue.length === 0 || rawValue.trim().length === 0) {
throw new ExportNotebookSnapshotCliError(`Flag '${flag}' requires a non-empty value.`);
}
if (rawValue.includes('\0')) {
throw new ExportNotebookSnapshotCliError(`Flag '${flag}' value must not contain NUL bytes.`);
}
if (rawValue.startsWith('-')) {
throw new ExportNotebookSnapshotCliError(
`Flag '${flag}' value must not start with '-' (received '${rawValue}').`
);
}
return rawValue;
}
function parsePositiveIntFlag(flag: string, rawValue: string): number {
const validated = validateRawTokenValue(flag, rawValue);
if (!STRICT_POSITIVE_INT_RE.test(validated)) {
throw new ExportNotebookSnapshotCliError(
`Flag '${flag}' must be a positive integer (received '${validated}').`
);
}
const parsed = Number(validated);
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
throw new ExportNotebookSnapshotCliError(
`Flag '${flag}' must be a positive safe integer (received '${validated}').`
);
}
return parsed;
}
function resolveValidatedPath(baseCwd: string, flag: string, rawValue: string): string {
const validated = validateRawTokenValue(flag, rawValue);
return resolve(baseCwd, validated);
}
/**
* Parses and validates CLI arguments for `scripts/export-notebook-snapshot.ts`.
*
* Rejects missing required flags, duplicate flags, unknown flags, positional
* arguments, NUL bytes, and values starting with `-` prior to `path.resolve`.
*/
export function parseExportNotebookSnapshotArgs(
argv: readonly string[],
options?: ParseExportNotebookSnapshotArgsOptions
): ParsedExportNotebookSnapshotArgs {
const baseCwd = options?.cwd ?? process.cwd();
const env = options?.env ?? process.env;
const seen = new Map<string, string>();
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i] as string;
if (token === '--help' || token === '-h') {
return { kind: 'help' };
}
if (token === '--') {
throw new ExportNotebookSnapshotCliError('Unexpected positional argument separator "--".');
}
if (!token.startsWith('-')) {
throw new ExportNotebookSnapshotCliError(`Unexpected positional argument '${token}'.`);
}
const eqIndex = token.indexOf('=');
let flag: string;
let rawValue: string;
if (eqIndex !== -1) {
flag = token.slice(0, eqIndex);
rawValue = token.slice(eqIndex + 1);
if (!VALUE_FLAGS.has(flag)) {
throw new ExportNotebookSnapshotCliError(`Unknown flag '${flag}'.`);
}
} else {
flag = token;
if (!VALUE_FLAGS.has(flag)) {
throw new ExportNotebookSnapshotCliError(`Unknown flag '${flag}'.`);
}
if (i + 1 >= argv.length) {
throw new ExportNotebookSnapshotCliError(`Flag '${flag}' requires a value.`);
}
i += 1;
rawValue = argv[i] as string;
}
if (seen.has(flag)) {
throw new ExportNotebookSnapshotCliError(`Duplicate flag '${flag}'.`);
}
seen.set(flag, validateRawTokenValue(flag, rawValue));
}
const rawNotebook = seen.get('--notebook');
if (rawNotebook === undefined) {
throw new ExportNotebookSnapshotCliError('Missing required flag --notebook <path.py>.');
}
const rawOut = seen.get('--out');
if (rawOut === undefined) {
throw new ExportNotebookSnapshotCliError('Missing required flag --out <path.html>.');
}
const notebookPath = resolveValidatedPath(baseCwd, '--notebook', rawNotebook);
const outputPath = resolveValidatedPath(baseCwd, '--out', rawOut);
const rawMarimo = seen.get('--marimo');
let marimoCommand: string;
if (rawMarimo !== undefined) {
marimoCommand = rawMarimo;
} else {
const envMarimo = env.MARIMO_COMMAND;
marimoCommand =
typeof envMarimo === 'string' && envMarimo.trim().length > 0
? envMarimo
: DEFAULT_MARIMO_COMMAND;
}
const rawTimeoutMs = seen.get('--timeout-ms');
const timeoutMs =
rawTimeoutMs !== undefined
? parsePositiveIntFlag('--timeout-ms', rawTimeoutMs)
: DEFAULT_NOTEBOOK_SNAPSHOT_TIMEOUT_MS;
const rawCwd = seen.get('--cwd');
const cwd = rawCwd !== undefined ? resolveValidatedPath(baseCwd, '--cwd', rawCwd) : undefined;
const rawAllowedNotebookRoot = seen.get('--allowed-notebook-root');
const allowedNotebookRoot =
rawAllowedNotebookRoot !== undefined
? resolveValidatedPath(baseCwd, '--allowed-notebook-root', rawAllowedNotebookRoot)
: undefined;
const rawAllowedOutputRoot = seen.get('--allowed-output-root');
const allowedOutputRoot =
rawAllowedOutputRoot !== undefined
? resolveValidatedPath(baseCwd, '--allowed-output-root', rawAllowedOutputRoot)
: undefined;
return {
kind: 'run',
notebookPath,
outputPath,
marimoCommand,
timeoutMs,
...(cwd !== undefined ? { cwd } : {}),
...(allowedNotebookRoot !== undefined ? { allowedNotebookRoot } : {}),
...(allowedOutputRoot !== undefined ? { allowedOutputRoot } : {}),
};
}
/**
* Executes the notebook snapshot CLI with injectable I/O, runner, and fs deps.
*/
export async function runExportNotebookSnapshotCli(
deps: ExportNotebookSnapshotCliDeps = {}
): Promise<number> {
const argv = deps.argv ?? process.argv.slice(2);
const stdout = deps.stdout ?? process.stdout;
const stderr = deps.stderr ?? process.stderr;
let parsed: ParsedExportNotebookSnapshotArgs;
try {
parsed = parseExportNotebookSnapshotArgs(argv, {
...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}),
...(deps.env !== undefined ? { env: deps.env } : {}),
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
stderr.write(`Invalid arguments: ${sanitizeSingleLine(message)}\n`);
return 1;
}
if (parsed.kind === 'help') {
stdout.write(EXPORT_NOTEBOOK_SNAPSHOT_USAGE);
return 0;
}
try {
const receipt = await exportNotebookSnapshot({
notebookPath: parsed.notebookPath,
outputPath: parsed.outputPath,
marimoCommand: parsed.marimoCommand,
timeoutMs: parsed.timeoutMs,
...(parsed.cwd !== undefined ? { cwd: parsed.cwd } : {}),
...(parsed.allowedNotebookRoot !== undefined
? { allowedNotebookRoot: parsed.allowedNotebookRoot }
: {}),
...(parsed.allowedOutputRoot !== undefined
? { allowedOutputRoot: parsed.allowedOutputRoot }
: {}),
runner: deps.runner ?? createNodeNotebookCommandRunner(),
fs: deps.fs ?? createNodeNotebookSnapshotFs(),
});
stdout.write(`${JSON.stringify(receipt)}\n`);
return 0;
} catch (err) {
if (err instanceof NotebookSnapshotError) {
stderr.write(
`Notebook snapshot export failed [${err.code}]: ${sanitizeSingleLine(err.message)}\n`
);
return 1;
}
const message = err instanceof Error ? err.message : String(err);
stderr.write(`Notebook snapshot export failed: ${sanitizeSingleLine(message)}\n`);
return 1;
}
}
if (import.meta.main) {
process.exitCode = await runExportNotebookSnapshotCli();
}

View file

@ -57,12 +57,13 @@ async function defaultOpenExecutor(
}
async function defaultOpenStore(
config: ResearchCopilotHostConfig
config: ResearchCopilotHostConfig,
env?: Readonly<Record<string, string | undefined>>
): Promise<ManagedMarketDataStore> {
const { openResearchCopilotStore } = await import(
'../libs/data/duckdb/src/research-copilot-store'
);
return openResearchCopilotStore(config);
return openResearchCopilotStore(config, env !== undefined ? { env } : undefined);
}
function defaultCreateLibraryCardReader(
@ -91,7 +92,7 @@ export async function runResearchCopilotMcp(
await runResearchCopilotStdioHost({
config,
openExecutor: deps.openExecutor ?? defaultOpenExecutor,
openStore: deps.openStore ?? defaultOpenStore,
openStore: deps.openStore ?? (hostConfig => defaultOpenStore(hostConfig, deps.env)),
createLibraryCardReader: deps.createLibraryCardReader ?? defaultCreateLibraryCardReader,
newId: deps.newId ?? randomUUID,
now: deps.now ?? Date.now,

View file

@ -0,0 +1,505 @@
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<Record<string, string | undefined>>;
}
): Promise<SpawnCliResult> {
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<string> {
const shimPath = join(workDir, name);
const htmlContent = extra?.htmlContent ?? '<!doctype html><html><body>Snapshot OK</body></html>\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, "<html>partial-failure", "utf8");',
' process.stderr.write("export crashed\\n");',
' process.exit(2);',
' }',
' if (mode === "export_hang") {',
' writeFileSync(outPath, "<html>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<string, string>;
};
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 = '<!doctype html><html><body><h1>Study Snapshot</h1></body></html>\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 = '<!doctype html><html><body>Relative OK</body></html>\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 = '<!doctype html><html><body>Prior Verified Snapshot</body></html>\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 = '<!doctype html><html><body>Preserved</body></html>\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 = '<!doctype html><html><body>Stable Prior</body></html>\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 = '<!doctype html><html><body>Stable Before Timeout</body></html>\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:');
});
});

File diff suppressed because it is too large Load diff